Не удается подключиться к сопряженному устройству Bluetooth

#android #react-native #bluetooth #react-native-android #bluetooth-printing

#Android #react-родной #bluetooth #react-native-android #bluetooth-печать

Вопрос:

Я пытаюсь подключить сопряженные и непарные устройства Bluetooth. Ниже я прикрепил весь файл. Я могу выполнить сопряжение устройств, но не смог подключить устройства. Как мне это сделать?

Я использовал приведенную ниже ссылку для настройки модуля.

https://www.npmjs.com/package/react-native-bluetooth-escpos-printer

Окружающая среда:

«реагировать»: «16.9.0»,

«react-native»: «^ 0.63.3»,

«react-native-bluetooth-escpos-printer»: «0.0.5»

 import React, { useState, useEffect } from 'react';
import {
    SafeAreaView,
    Text,
    View,
    Platform,
    StyleSheet,
    Alert,
    DeviceEventEmitter,
    ScrollView,
    TouchableOpacity,
    ActivityIndicator,
    Dimensions,
    StatusBar
} from 'react-native';
import { BluetoothManager, BluetoothEscposPrinter, BluetoothTscPrinter } from 'react-native-bluetooth-escpos-printer';


const statusBarHeight = StatusBar.currentHeight;
const height = (Dimensions.get('window').height - statusBarHeight) / 12;
const customHeight = height * 0.9;
const customMargin = height / 20;
const width = (Dimensions.get('window').width - 10) / 2;
const fontSize = Dimensions.get('window').height / 40;

const BluetoothPrinter = () => {
    const [pairedDs, setPairedDevices] = useState([]);
    const [foundDs, setFoundDevices] = useState([]);
    const [paired, setPaired] = useState([]);
    const [found, setFound] = useState([]);
    const [loading, setLoading] = useState(false);
    const [boundAddress, setBoundAddress] = useState([]);
    const [options, setOptions] = useState('');
    const [waiting, setWaiting] = useState(true);

    function enableBT() {
        BluetoothManager.enableBluetooth().then((r) => {
            var paired = [];
            if (r amp;amp; r.length > 0) {
                for (var i = 0; i < r.length; i  ) {
                    try {
                        paired.push(JSON.parse(r[i])); // NEED TO PARSE THE DEVICE INFORMATION
                        if (ss.paired.length > 0) {
                            setWaiting(false);
                        }
                    } catch (e) {
                        //ignore
                    }
                }
            }
            console.log(JSON.stringify(paired));
            Alert.alert("Enabled")
            scanBTDevices();
        }, (err) => {
            alert(err)
        });
    }

    function disableBT() {
        BluetoothManager.disableBluetooth().then(() => {
            // do something.
        }, (err) => { alert(err) });
    }

    function scanBTDevices() {
        BluetoothManager.scanDevices()
            .then((s) => {
                var ss = JSON.parse(s);
                console.log(".................................")
                console.log(ss.found);
                if (ss.found.length > 0) {
                    setWaiting(false);
                }
                setPairedDevices(ss.paired);
                setFoundDevices(ss.found);
                setLoading(false);
                setPaired(ss.paired);
                setFound(ss.found);
                connectBTDevice({ "address": "64:6C:B2:DA:19:3D", "name": "Galaxy Grand Prime" });
            }, (er) => {
                setLoading(false),
                alert('error'   JSON.stringify(er));
            });
    }

    function connectBTDevice(rowData) {
        console.log("Connect device");
        Alert.alert("Connecting......................");
        BluetoothManager.connect(rowData.address) // the device address scanned.
            .then((s) => {
                console.log(s);
                Alert.alert(s);
                setLoading(false);
                setBoundAddress(rowData.address);
                // print();
            }, (e) => {
                console.log(e);
                setLoading(false);
                alert(e);
            })
    }

    function _deviceAlreadPaired(rsp) {
        console.log(rsp.devices);
    }

    function _deviceFoundEvent(rsp) {
        console.log(rsp.devices);
    }

    useEffect(() => {
        BluetoothManager.isBluetoothEnabled().then((enabled) => {
            console.log(enabled);
            if (!enabled) {
                enableBT();
            } else {
                Alert.alert("Enabled")
                scanBTDevices();
            }
        }, (err) => {
            Alert.alert("err", err)
        });
        DeviceEventEmitter.addListener(
            BluetoothManager.EVENT_DEVICE_ALREADY_PAIRED, (rsp) => {
                _deviceAlreadPaired(rsp) // rsp.devices would returns the paired devices array in JSON string.
            });
        DeviceEventEmitter.addListener(
            BluetoothManager.EVENT_DEVICE_FOUND, (rsp) => {
                _deviceFoundEvent(rsp) // rsp.devices would returns the found device object in JSON string
            });
    }, []);

    return (
        <SafeAreaView style={{ flex: 1 }}>
            {
                waiting ?
                    <View style={[styles.container2, styles.horizontal]}>
                        <ActivityIndicator size="large" color="#0000ff" />
                    </View>
                    :
                    <ScrollView>
                        {
                            foundDs.length amp;amp; foundDs.length > 0 ? (
                                foundDs.map((item, key) => {
                                    return (
                                        <TouchableOpacity
                                            key={key}
                                            style={styles.surface}
                                            onPress={() => connectBTDevice(item)}>
                                            <Text style={styles.itemInfo}>{item.name}</Text>
                                        </TouchableOpacity>
                                    );
                                })
                            )
                                : false
                        }
                    </ScrollView>
            }
        </SafeAreaView>
    );
};

export default BluetoothPrinter;

const styles = StyleSheet.create({
    container2: {
        justifyContent: "center",
    },
    horizontal: {
        flexDirection: "row",
        justifyContent: "space-around",
    },
    itemInfo: {
        fontSize,
        fontWeight: 'bold',
    },
    surface: {
        margin: customMargin,
        justifyContent: 'center',
        alignItems: 'center',
        height: customHeight,
        width: width,
        elevation: 2,
        borderRadius: 2,
        backgroundColor: 'lightblue',
    },
});
 

Комментарии:

1. Любая помощь? Я также сталкиваюсь с той же проблемой с «react-native»: «^ 0.64.0»

2. Я использовал другой модуль @PraveenShekhawat

3. npmjs.com/package/react-native-thermal-receipt-printer