0

我正在尝试连接已配对和未配对的蓝牙设备。下面我附上了整个文件。我可以配对设备,但无法连接设备。我该怎么做?

我已使用以下链接为模块进行设置。

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

环境:

“反应”:“16.9.0”,

“反应原生”:“^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 && 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 && 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',
    },
});
4

0 回答 0