0
import React, {Component} from 'react';
import {
    Animated,
    Dimensions,
    Image,
    StyleSheet,
    Text,
    FlatList,
    TouchableOpacity,
    PermissionsAndroid,
    TouchableHighlight,
    View,
} from 'react-native';
import base64 from 'react-native-base64';
import {Container, Header, Content, Footer} from 'native-base';
import BLE from './BLE';
import {connect} from 'react-redux';
import {BleManager} from 'react-native-ble-plx';
import {
    changeStatus,
    connectedDevice,
    connectedDeviceServices,
    addBLE,
} from './actions/index.js';
// import {connectDevice,startScan} from './actions';
import DataActivityIndicator from './DataActivityIndicator';
const DeviceManager = new BleManager();
const requestLocationPermission = async () => {
    try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
          {
              title: 'Location permission for bluetooth scanning',
              message: 'wahtever',
              buttonNeutral: 'Ask Me Later',
              buttonNegative: 'Cancel',
              buttonPositive: 'OK',
          },
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            console.log('Location permission for bluetooth scanning granted');
            return true;
        } else {
            console.log('Location permission for bluetooth scanning revoked');
            return false;
        }
    } catch (err) {
        console.warn(err);
        return false;
    }
};
class BLEList extends Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
        const subscription = DeviceManager.onStateChange(state => {
            if (state === 'PoweredOn') {
                console.log('powered on');
                this.getPermission();
                subscription.remove();
            }
        }, true);
    }
    getPermission = async () => {
        const permission = await requestLocationPermission();
        if (permission) {
            DeviceManager.startDeviceScan(null, null, (error, device) => {
                this.props.dispatch(changeStatus('Scanning'));
                if (error) {
                    console.log(error);
                }
                if (device) {
                    this.props.dispatch(addBLE(device));
                }
            });
        } else {
            console.log('Error permission');
        }
    };
    discoverAllServices = async d => {
        await DeviceManager.discoverAllServicesAndCharacteristicsForDevice(
          d.id,
          null,
        ).then(response => {
            console.log('%%%%%%%%%%');
            console.log(response, 'discoverAllServicesAndCharacteristicsForDevice');
        });
    };
    discoveringCharastics = async d => {
        console.log('********discoveringCharastics********');
        console.log(d, 'd', d.id, d.serviceUUIDs[0]);
        let allCharacteristicsData = await DeviceManager.characteristicsForDevice(
          d.id,
          d.serviceUUIDs[0],
        );
        // ***********allCharacteristicsData**********
        console.log('***********allCharacteristicsData**********');
        console.log(Object.getOwnPropertyNames(allCharacteristicsData[0]));
        console.log(allCharacteristicsData, 'allCharacteristicsData');
        const data = await DeviceManager.readCharacteristicForDevice(
          d.id,
          d.serviceUUIDs[0],
          null,
          null,
        );
        console.log(data, 'data').then(response => {
            console.log(response, 'response');
        });
        discoverAllServices();
    };
    handleClick = async device => {
        // console.log(device,"device")
        this.props.dispatch(changeStatus('Connecting'));
        DeviceManager.stopDeviceScan();
        await DeviceManager.connectToDevice(device.id, null)
          .then(async device => {
              this.props.dispatch(changeStatus('Discovering'));
              let allCharacteristics = device.discoverAllServicesAndCharacteristics();
              this.props.dispatch(connectedDevice(device));
              let checkDeviceIConnected = await DeviceManager.isDeviceConnected(
                device.id,
              );
              console.log(
                checkDeviceIConnected,
                'status if device connected it returns true',
              );
              if (checkDeviceIConnected === true) {
                  this.props.dispatch(changeStatus('Connected'));
              } else {
                  this.props.dispatch(changeStatus('Disconnected'));
              }
              return allCharacteristics;
          })
          .then(device => {
              let services = device.services(device.id);
              return services;
          })
          .then(
            async services => {
                // ***********sevices*********
                console.log('***********sevices*********');
                console.log('found services: ', services);
                // const services1 = JSON.parse(services);
                console.log(
                  services[0]._manager._eventEmitter._subscriber._subscriptionsForType
                    .appStateDidChange[0].emitter._subscriber._subscriptionsForType
                    .appStateDidChange[0].emitter._subscriber._subscriptionsForType,
                );
                this.props.dispatch(connectedDeviceServices(services));
                this.discoveringCharastics(device);
            },
            error => {
                console.log(this._logError('SCAN', error));
            },
          );
        const descriptor = await DeviceManager.descriptorsForDevice(
          '00:1F:FF:49:C8:6D',
          '4553867f-f809-49f4-aefc-e190a1f459f3',
          '22a4e311-a097-4517-9b81-cf32af60b982',
        );
        console.log('^^^^^^^^^^^');
        console.log('descriptor:', descriptor);
        console.log('^^^^^^^^^^^');
        const readDescriptorForService = await DeviceManager.readDescriptorForDevice(
          '4553867f-f809-49f4-aefc-e190a1f459f3',
          '22a4e311-a097-4517-9b81-cf32af60b982',
          '00002902-0000-1000-8000-00805f9b34fb',
        );
        // const edo = await readDescriptorForService;
        console.log('^^^^^***********^^^^^^');
        console.log('readDescriptorForService:', readDescriptorForService);
        console.log('^^^^^^*********^^^^^');
    };
    connectableString = item => {
        if (item.isConnectable) {
            if (item.name.toString().includes('PR BT')) {
            }
            return 'Tap to connect to: ' + item.name;
        } else {
            return item.name + item.name.toString().includes('PR BT')
              ? base64.decode(base64.encode(item.name))
              : ' ' + ' is not connectable';
        }
    };
    render() {
        return (
          <Container>
              <Header />
              <FlatList
                data={this.props.BLEList}
                renderItem={({item}) => (
                  <>
                      <TouchableHighlight
                        onPress={() => this.handleClick(item)}
                        style={item.isConnectable ? styles.rowFront : styles.rowBack}
                        underlayColor={'#AAA'}>
                          <View>
                              <Text>
                                  {/* {item.name} + {item.id} */}
                                  {this.connectableString(item)}
                              </Text>
                          </View>
                      </TouchableHighlight>
                  </>
                )}
                keyExtractor={item => item.id.toString()}
                ListEmptyComponent={DataActivityIndicator}
              />
              <Footer>
                  <BLE />
              </Footer>
          </Container>
        );
    }
}
const mapStateToProps = state => {
    return {
        BLEList: state.BLEs['BLEList'],
        status: state.BLEs['status'],
    };
};

Blockquote **we connected a Bluetooth device and logged the services, descriptors and characteristics of the device but we are not able to understand how to get the internal data about the device like we are working with Philips respironics dreamStation device when it is connected through Bluetooth we ** Blockquote

Kirill Novikov
  • 2,576
  • 4
  • 20
  • 33
  • Read every characteristic of every service you got using this method https://github.com/innoveit/react-native-ble-manager#readperipheralid-serviceuuid-characteristicuuid You will get the details – Waqas Ahmed Dec 29 '21 at 08:01
  • Even you can contact the manufacturer standard documentation for list of service and characteristic uuids where all the details will be mentioned. – Waqas Ahmed Dec 29 '21 at 08:02
  • we are not having proper document, by refering some codes i got to understand that we can get only uuids ,but iam not able to understand the uuid belongs to which characteristic and iam getting value property in the characteristic object as null – Bommana Keerthi Jan 05 '22 at 13:17

0 Answers0