januslo / react-native-bluetooth-escpos-printer

React-Native plugin for the bluetooth ESC/POS & TSC printers.
MIT License
359 stars 416 forks source link

Error in example when i scan a bluetooth #120

Open michaelVictoriaDev opened 4 years ago

michaelVictoriaDev commented 4 years ago

error{"nativeStackAndroid":[],"userInfo":null,"message":"NOT_STARTED","code":"DISCOVER"}

image

Do you have any Idea? its a fresh project


import React, {Component} from 'react';
import {ActivityIndicator,
    Platform,
    StyleSheet,
    Text,
    View,
    Button,
    ScrollView,
    DeviceEventEmitter,
    NativeEventEmitter,
    Switch,
    TouchableOpacity,
    Dimensions,
    ToastAndroid} from 'react-native';
import {BluetoothEscposPrinter, BluetoothManager, BluetoothTscPrinter} from "react-native-bluetooth-escpos-printer";

var {height, width} = Dimensions.get('window');
export default class Home extends Component {

    _listeners = [];

    constructor(props) {
        super(props);
        this.state = {
            devices: null,
            pairedDs:[],
            foundDs: [],
            bleOpend: false,
            loading: true,
            boundAddress: '',
            debugMsg: ''
        }
    }

    componentDidMount() {//alert(BluetoothManager)
        BluetoothManager.isBluetoothEnabled().then((enabled)=> {
            this.setState({
                bleOpend: Boolean(enabled),
                loading: false
            })
        }, (err)=> {
            err
        });

        if (Platform.OS === 'ios') {
            let bluetoothManagerEmitter = new NativeEventEmitter(BluetoothManager);
            this._listeners.push(bluetoothManagerEmitter.addListener(BluetoothManager.EVENT_DEVICE_ALREADY_PAIRED,
                (rsp)=> {
                    this._deviceAlreadPaired(rsp)
                }));
            this._listeners.push(bluetoothManagerEmitter.addListener(BluetoothManager.EVENT_DEVICE_FOUND, (rsp)=> {
                this._deviceFoundEvent(rsp)
            }));
            this._listeners.push(bluetoothManagerEmitter.addListener(BluetoothManager.EVENT_CONNECTION_LOST, ()=> {
                this.setState({
                    name: '',
                    boundAddress: ''
                });
            }));
        } else if (Platform.OS === 'android') {
            this._listeners.push(DeviceEventEmitter.addListener(
                BluetoothManager.EVENT_DEVICE_ALREADY_PAIRED, (rsp)=> {
                    this._deviceAlreadPaired(rsp)
                }));
            this._listeners.push(DeviceEventEmitter.addListener(
                BluetoothManager.EVENT_DEVICE_FOUND, (rsp)=> {
                    this._deviceFoundEvent(rsp)
                }));
            this._listeners.push(DeviceEventEmitter.addListener(
                BluetoothManager.EVENT_CONNECTION_LOST, ()=> {
                    this.setState({
                        name: '',
                        boundAddress: ''
                    });
                }
            ));
            this._listeners.push(DeviceEventEmitter.addListener(
                BluetoothManager.EVENT_BLUETOOTH_NOT_SUPPORT, ()=> {
                    ToastAndroid.show("Device Not Support Bluetooth !", ToastAndroid.LONG);
                }
            ))
        }
    }

    componentWillUnmount() {
        //for (let ls in this._listeners) {
        //    this._listeners[ls].remove();
        //}
    }

    _deviceAlreadPaired(rsp) {
        var ds = null;
        if (typeof(rsp.devices) == 'object') {
            ds = rsp.devices;
        } else {
            try {
                ds = JSON.parse(rsp.devices);
            } catch (e) {
            }
        }
        if(ds && ds.length) {
            let pared = this.state.pairedDs;
            pared = pared.concat(ds||[]);
            this.setState({
                pairedDs:pared
            });
        }
    }

    _deviceFoundEvent(rsp) {//alert(JSON.stringify(rsp))
        var r = null;
        try {
            if (typeof(rsp.device) == "object") {
                r = rsp.device;
            } else {
                r = JSON.parse(rsp.device);
            }
        } catch (e) {//alert(e.message);
            //ignore
        }
        //alert('f')
        if (r) {
            let found = this.state.foundDs || [];
            if(found.findIndex) {
                let duplicated = found.findIndex(function (x) {
                    return x.address == r.address
                });
                //CHECK DEPLICATED HERE...
                if (duplicated == -1) {
                    found.push(r);
                    this.setState({
                        foundDs: found
                    });
                }
            }
        }
    }

    _renderRow(rows){
        let items = [];
        for(let i in rows){
            let row = rows[i];
            if(row.address) {
                items.push(
                    <TouchableOpacity key={new Date().getTime()+i} style={styles.wtf} onPress={()=>{
                    this.setState({
                        loading:true
                    });
                    BluetoothManager.connect(row.address)
                        .then((s)=>{
                            this.setState({
                                loading:false,
                                boundAddress:row.address,
                                name:row.name || "UNKNOWN"
                            })
                        },(e)=>{
                            this.setState({
                                loading:false
                            })
                            alert(e);
                        })

                }}><Text style={styles.name}>{row.name || "UNKNOWN"}</Text><Text
                        style={styles.address}>{row.address}</Text></TouchableOpacity>
                );
            }
        }
        return items;
    }

    render() {
        return (
            <ScrollView style={styles.container}>
                <Text>{this.state.debugMsg}</Text>
                <Text style={styles.title}>Blutooth Opended:{this.state.bleOpend?"true":"false"} <Text>Open BLE Before Scanning</Text> </Text>
                <View>
                <Switch value={this.state.bleOpend} onValueChange={(v)=>{
                this.setState({
                    loading:true
                })
                if(!v){
                    BluetoothManager.disableBluetooth().then(()=>{
                        this.setState({
                            bleOpend:false,
                            loading:false,
                            foundDs:[],
                            pairedDs:[]
                        });
                    },(err)=>{alert(err)});

                }else{
                    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]));
                                }catch(e){
                                    //ignore
                                }
                            }
                        }
                        this.setState({
                            bleOpend:true,
                            loading:false,
                            pairedDs:paired
                        })
                    },(err)=>{
                        this.setState({
                            loading:false
                        })
                        alert(err)
                    });
                }
            }}/>
                    <Button disabled={this.state.loading || !this.state.bleOpend} onPress={()=>{
                        this._scan();
                    }} title="Scan"/>
                </View>
                <Text  style={styles.title}>Connected:<Text style={{color:"blue"}}>{!this.state.name ? 'No Devices' : this.state.name}</Text></Text>
                <Text  style={styles.title}>Found(tap to connect):</Text>
                {this.state.loading ? (<ActivityIndicator animating={true}/>) : null}
                <View style={{flex:1,flexDirection:"column"}}>
                {
                    this._renderRow(this.state.foundDs)
                }
                </View>
                <Text  style={styles.title}>Paired:</Text>
                {this.state.loading ? (<ActivityIndicator animating={true}/>) : null}
                <View style={{flex:1,flexDirection:"column"}}>
                {
                    this._renderRow(this.state.pairedDs)
                }
                </View>

                {/* <View style={{flexDirection:"row",justifyContent:"space-around",paddingVertical:30}}>
                <Button disabled={this.state.loading || !(this.state.bleOpend && this.state.boundAddress.length > 0 )}
                        title="ESC/POS" onPress={()=>{
                    this.props.navigator.push({
                        component:EscPos,
                        passProps:{
                            name:this.state.name,
                            boundAddress:this.state.boundAddress
                        }
                    })
                }}/>
                <Button disabled={this.state.loading|| !(this.state.bleOpend && this.state.boundAddress.length > 0) }
                        title="TSC" onPress={()=>{
                   this.props.navigator.push({
                       component:Tsc,
                       passProps:{
                           name:this.state.name,
                           boundAddress:this.state.boundAddress
                       }
                   })
                }
                }/>
                </View> */}
            </ScrollView>
        );
    }

    // _selfTest() {
    //     this.setState({
    //         loading: true
    //     }, ()=> {
    //         BluetoothEscposPrinter.selfTest(()=> {
    //         });

    //         this.setState({
    //             loading: false
    //         })
    //     })
    // }

    _scan() {
        this.setState({
            loading: true
        })
        BluetoothManager.scanDevices()
            .then((s)=> {
                var ss = s;
                var found = ss.found;
                try {
                    found = JSON.parse(found);//@FIX_it: the parse action too weired..
                } catch (e) {
                    //ignore
                }
                var fds =  this.state.foundDs;
                if(found && found.length){
                    fds = found;
                }
                this.setState({
                    foundDs:fds,
                    loading: false
                });
            }, (er)=> {
                this.setState({
                    loading: false
                })
                console.log('error' + JSON.stringify(er))
                alert('error' + JSON.stringify(er));
            });
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
    },

    title:{
        width:width,
        backgroundColor:"#eee",
        color:"#232323",
        paddingLeft:8,
        paddingVertical:4,
        textAlign:"left"
    },
    wtf:{
        flex:1,
        flexDirection:"row",
        justifyContent:"space-between",
        alignItems:"center"
    },
    name:{
        flex:1,
        textAlign:"left"
    },
    address:{
        flex:1,
        textAlign:"right"
    }
});
LightningNemesis commented 4 years ago

I got the same error, its occurring when the scan button is pressed and console.log(er) gives "[Error: NOT_STARTED]". I have it running on an actual physical device. Let me know if you are able to solve it.

GanongLS commented 4 years ago

same with me, please if there is update. I am in really desperate need of this printer, because my boss so demanding to have bluetooth printer in our project.

datvp09 commented 4 years ago

same to me

gkothe commented 3 years ago

Also having this problem.

But since In my project i dont really need to scan through the app, it works to get only the already paired devices. If u need to scan, maybe u can try https://github.com/innoveit/react-native-ble-manager for the scan, than show the list and connect with escpos-printer

DeVoresyah commented 3 years ago

Add this to your AndroidManifset.xml

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
yayidg22 commented 3 years ago

Apparently you use a android emulator and this library is not compatible with android emulators try use a cellphone with usb and run npx react-native run-android

Gibrat-Erisov commented 3 years ago

I changed the SDK version from 29 to 28 and then this error disappeared. But with SDK 28, you cannot download apk file on google play.

Gibrat-Erisov commented 3 years ago

I had the same issue when I updated my targetSdkVersion from 28 to 29. Replacing the android permission ACCESS_COARSE_LOCATION with ACCESS_FINE_LOCATION in _nodemodule/react-native-bluetooth-escpos-printer/android/src/main/java/cn/jystudio/bluetooth/RNBluetoothManagerModule.java Hope this helps.

dibyopra commented 3 years ago

I had same issue when I use tablet Samsung Tab A but working on my android devices.

ajiehatajie commented 3 years ago

you must pay attention to this method

init pairing the printer in the android settings menu

  1. first install package version 0.0.6 "react-native-bluetooth-escpos-printer": "git+https://github.com/januslo/react-native-bluetooth-escpos-printer.git",

  2. call and ignore response

    async scan() {
        await BluetoothManager.scanDevices().then(
            (s) => {
                log({scanDevices: s});
            },
            (er) => {
                log({er: er});
               IGNORE THIS ERROR
            },
        );
    }

    3.response scanDevices you can focus to listener

 DeviceEventEmitter.addListener(
                BluetoothManager.EVENT_DEVICE_ALREADY_PAIRED,
                (rsp) => {
                    log({resp: rsp});
                    this._deviceAlreadPaired(rsp);
                },
            ),

please try example https://github.com/januslo/react-native-bluetooth-escpos-printer/blob/master/examples/

image

amirulasrof commented 3 years ago

You need to add uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" and turn on location (GPS ) before scanning for new peripherals.

romeonuen commented 3 years ago

I had the same issue when I updated my targetSdkVersion from 28 to 29. Replacing the android permission ACCESS_COARSE_LOCATION with ACCESS_FINE_LOCATION in _nodemodule/react-native-bluetooth-escpos-printer/android/src/main/java/cn/jystudio/bluetooth/RNBluetoothManagerModule.java Hope this helps.

I had same issue and this solution worked for me

Lakshmi-Narasimha commented 3 years ago

In Android API 29 >= you need to use "ACCESS_FINE_LOCATION" instead of "ACCESS_COARSE_LOCATION".

Replacing the android permission ACCESS_COARSE_LOCATION with ACCESS_FINE_LOCATION in node_module/react-native-bluetooth-escpos-printer/android/src/main/java/cn/jystudio/bluetooth/RNBluetoothManagerModule.java

antzhh commented 3 years ago

Still not working for me after using your fix. I'm trying on Redmi 7A - Android 10. Any suggestion ? targetSdkVersion 28 but also tried with 29

champikamendis commented 2 years ago

Make sure to turn on location in your device. And also need to give proper permissions in Android manifest. I added following to manifest.

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Then cleaned the gradle and built and ran the app. Worked fine for me!

mihir12345 commented 2 years ago

This scanning works fine with mobile devices but does not work with samsung tablet.It gives out error message NOT_STARTED. What can be the reason?

davidcostadev commented 2 years ago

you must pay attention to this method

init pairing the printer in the android settings menu

  1. first install package version 0.0.6 "react-native-bluetooth-escpos-printer": "git+https://github.com/januslo/react-native-bluetooth-escpos-printer.git",
  2. call and ignore response
async scan() {
        await BluetoothManager.scanDevices().then(
            (s) => {
                log({scanDevices: s});
            },
            (er) => {
                log({er: er});
               IGNORE THIS ERROR
            },
        );
    }

3.response scanDevices you can focus to listener

 DeviceEventEmitter.addListener(
                BluetoothManager.EVENT_DEVICE_ALREADY_PAIRED,
                (rsp) => {
                    log({resp: rsp});
                    this._deviceAlreadPaired(rsp);
                },
            ),

please try example https://github.com/januslo/react-native-bluetooth-escpos-printer/blob/master/examples/

image

Hey I'm also trying to connect with a MTP-III or MTP-3, I'm having issues, would like to share a repository with this example that is on this image?

Mahmoud-S97 commented 2 years ago

You need to add these permissions in the AndroidManifset.xml

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

And you need to replace the android permission ACCESS_COARSE_LOCATION with ACCESS_FINE_LOCATION in node_module/react-native-bluetooth-escpos-printer/android/src/main/java/cn/jystudio/bluetooth/RNBluetoothManagerModule.java (Which is the Library native code itself).

Finally, open your location (GPS) on your device and then try again it will work fine :)))

Venkat1P commented 2 years ago

@Mahmoud-S97 you saved my day :) thanks Brother

Mahmoud-S97 commented 2 years ago

@Mahmoud-S97 you saved my day :) thanks Brother

It's my pleasure dear🌷