0.0.4 • Published 2 years ago

react-native-inateck-scannersdk v0.0.4

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
2 years ago

react-native-inateck-scannersdk

Requirements

RN 0.60+

RN 0.40-0.59 supported until 6.7.X RN 0.30-0.39 supported until 2.4.3

Supported Platforms

  • iOS 8+
  • Android (API 19+)

Step by Step Usage

Android
1. npx react-native init AwesomeProject
2. cd AwesomeProject 
3. yarn add react-native-inateck-scannersdk
4. Open the android/app/src/main/AndroidManifest.xml and add the following information

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.BLUETOOTH" />
  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
  <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"
        android:usesPermissionFlags="neverForLocation" />
  
5. Copy the Examples content to app.js
6. replace appInfo
7. Open the AwesomeProject/android with Android Studio
IOS
1. npx react-native init AwesomeProject
2. cd AwesomeProject 
3. yarn add react-native-inateck-scannersdk
4. cd ios 
5. pod install  
6. Open the ios/AwesomeProject/Info.plist and add the following information

  <key>NSBluetoothAlwaysUsageDescription</key>
  <string>To use bluetooth</string>

7. Copy the Examples content to app.js
8. replace appInfo
9. Open the AwesomeProject/ios/.xcworkspace with xcode 

Install

using NPM:
npm install react-native-inateck-scannersdk --save

using YARN:
yarn add react-native-inateck-scannersdk

The library support the react native autolink feature.

Android - Update Manifest
// file: android/app/src/main/AndroidManifest.xml
<!-- Add xmlns:tools -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="YOUR_PACKAGE_NAME">

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

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="28"/>
    <uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION" tools:targetApi="Q"/>

    <!-- Only when targeting Android 12 or higher -->
    <!-- Please make sure you read the following documentation to have a
         better understanding of the new permissions.
         https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#assert-never-for-location
         -->

    <!-- If your app doesn't use Bluetooth scan results to derive physical location information,
         you can strongly assert that your app
         doesn't derive physical location. -->
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" 
                     android:usesPermissionFlags="neverForLocation"
                     tools:targetApi="s" />

    <!-- Needed only if your app looks for Bluetooth devices. -->
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    <!-- Needed only if your app makes the device discoverable to Bluetooth devices. -->
    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
...

If you need communication while the app is not in the foreground you need the "ACCESS_BACKGROUND_LOCATION" permission.

iOS - Update Info.plist

In iOS >= 13 you need to add the NSBluetoothAlwaysUsageDescription string key.

Note

  • Android API >= 23 require the ACCESS_COARSE_LOCATION permission to scan for peripherals.
  • Android API >= 29 require the ACCESS_FINE_LOCATION permission to scan for peripherals. React-Native 0.63.X started targeting Android API 29.
  • Because location and bluetooth permissions are runtime permissions, you must request these permissions at runtime along with declaring them in your manifest.

Methods

getInateckScannerBarcodeType()

Get the barcode types supported by the scanner Returns a Promise object.

getInateckScannerEventIds()

Get the event type id of the scanner Returns a Promise object.

scan(callback,scanSeconds)

Init the module and Scan for availables peripherals. Returns a Promise object.

Arguments

  • callback - callback - Callback function, receive availables peripherals list, bluetooth status,scan data, battery level notification, scanner connection/disconnection
  • seconds - Integer - the amount of seconds to scan.Default 5 seconds

Examples

  ScanManager.getInateckScannerBarcodeType().then((data) => {
    this.setState({
      InateckScannerBarcodeType: data
    })
  }).catch((err) => {
    console.log(err)
  })

  ScanManager.getInateckScannerEventIds().then((data) => {
    this.setState({
      InateckScannerEventIds: data
    })
  }).catch((err) => {
    console.log(err)
  })

  ScanManager.scan(this.handleScan, 3).then(() => {

  }).catch((err) => {
	  console.log(err)
  })

  handleScan = (args) => {
    let scannerEventIds=this.state.InateckScannerEventIds
    switch (args.code) {
      case scannerEventIds.deviceList:
        this.deviceListData=args.data
        break;
      case scannerEventIds.bleState:
        console.log(args.data)
        break;
      case scannerEventIds.barcodeData:
        console.log("BarcodeData:" + args.data.value)
        break;
      case scannerEventIds.batteryLevel:
        console.log("BatteryLevel:" + args.data)
        break;
      case scannerEventIds.deviceArrival:
        this.setState({ peripheralId: args.data.peripheral })
        break;
      case scannerEventIds.deviceDisconnect:
        console.log("Scanner Disconnect:" + args.data)
        break;
    }
  }

connect(peripheralId, appInfo)

Attempts to connect to a peripheral. In many cases if you can't connect you have to scan for the peripheral before. Returns a Promise object.

In iOS, attempts to connect to a peripheral do not time out (please see Apple's doc), so you might need to set a timer explicitly if you don't want this behavior.

Arguments

  • peripheralId - String - the id/mac address of the peripheral to connect.
  • appInfo - JSON - Authorization information

Examples

  const appInfo = {
	appId: 'M693be162686a',
	developerId: 'bb57d8e1-f911-47ba-b510-693be162686a',
	appKey: 'MC0CFQC85w0MsxDng4wHBICX7+iCOiSqfAIUdSerA4/MJ2kYBGAGgIG/YHemNr8=',
  }

  ScanManager.connect("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", appInfo).then(() => {

  }).catch((err) => {
	this.alert("connection failed")
  })

disconnect(peripheralId)

Disconnect from a scanner.
Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

Examples

  ScanManager.disconnect(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

stopNotification(peripheralId)

Stop the scan notification on the specified scanner. Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

Examples

  ScanManager.stopNotification(peripheralId).then(() => {
    // Success code
  })
  .catch((error) => {
    // Failure code
    console.log(error);
  });

retrieveConnected()

Return the connected peripherals. Returns a Promise object.

Examples

  ScanManager.retrieveConnected().then((peripheralsArray) => {
    // Success code
  })
  .catch((error) => {
    // Failure code
    console.log(error);
  });

isPeripheralConnected(peripheralId)

Check whether a specific peripheral is connected and return true or false. Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

Examples

  ScanManager.isPeripheralConnected(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  ).then((isConnected) => {
	if (isConnected) {
	console.log("Peripheral is connected!");
	} else {
	console.log("Peripheral is NOT connected!");
	}
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

readBatteryLevel(peripheralId)

Read the current battery level of the specified scanner Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

Examples

  ScanManager.readBatteryLevel(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

batteryLevelChangeNotify(peripheralId)

Start battery level change notification Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

Examples

  ScanManager.batteryLevelChangeNotify(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

stopBatteryLevelNotification(peripheralId)

stop battery level change notification Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

Examples

  ScanManager.stopBatteryLevelNotification(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

switchScannerHeaderLight(peripheralId, value)

Turn the scanner light on or off Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.
  • value - Integer - 1 is open 0 is close

Examples

  ScanManager.switchScannerHeaderLight(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", 1
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

openOrCloseBarcodeType(peripheralId, name, value)

Open or close scanner barcode type Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.
  • name - String - Specified scanner barcode type.
  • value - Integer - 1 is open 0 is close

Examples

  ScanManager.openOrCloseBarcodeType(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", 'IATA25', 1
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

vibrationConfirmation(peripheralId)

vibration Confirmation Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

Examples

  ScanManager.vibrationConfirmation(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

openOrCloseLightingLamp(peripheralId,lamps)

Scanner lighting lamps control Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.
  • lamps - String - 00 is On when scanning, 01 is Always on, 10 is Always off.

Examples

  ScanManager.openOrCloseLightingLamp(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX","00"
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

openOrClosePositioningLamp(peripheralId,lamps)

Scanner positioning lamp control Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.
  • lamps - String - 00 is On when scanning, 01 is Always on, 10 is Always off.

Examples

  ScanManager.openOrClosePositioningLamp(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX","00"
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

setSoundVolume(peripheralId,sounds)

Scanner positioning lamp control Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.
  • sounds - Integer - 0 is mute, 2 is low, 4 is middle, 8 is loud.

Examples

  ScanManager.setSoundVolume(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",0
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

openOrCloseShake(peripheralId,reminders)

Turn scanner vibration alert on or off Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.
  • reminders - Integer - 1 is open 0 is close.

Examples

  ScanManager.openOrCloseShake(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",0
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

setScannerName(peripheralId,name)

Set Scanner new name Setting the scanner name will restart the scanner Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.
  • name - String - Scanner new name, maximum length 23

Examples

  ScanManager.setScannerName(
	"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX","inateck-scanner"
  ).then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

openDateSuffix(peripheralId)

Add date suffix after barcode data Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

removeDateSuffix(peripheralId)

Date suffix after removing barcode data Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

openTimeSuffix(peripheralId)

Add time suffix after barcode data Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

removeTimeSuffix(peripheralId)

Time suffix after removing barcode data Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

getSdkVersion()

Get the current sdk version Returns a Promise object.

Examples

  ScanManager.getSdkVersion().then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

getFirmwareVersion(peripheralId)

Get the current scanner firmware version Returns a Promise object.

Arguments

  • peripheralId - String - the id/mac address of the scanner.

Examples

  ScanManager.getFirmwareVersion().then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

unmountScannerEvent()

Remove scanner related events Returns a Promise object.

Examples

  ScanManager.unmountScannerEvent().then((data) => {
	// Success code
  }).catch((error) => {
    // Failure code
    console.log(error);
  });

Error Code

  • 2001 - Bluetooth is not turned on
  • 2002 - Last scan did not end...
  • 2003 - Cannot open another connection process when Bluetooth is currently connected
  • 2004 - Service uuid not found
  • 2005 - Barcode type not found
  • 2006 - Failed to read data
  • 2007 - No response from the server
  • 2008 - Illegal scanner name.Only English, numbers and symbols can be input
  • 2009 - Last operation not completed
  • 2010 - Authorization fails
  • 2011 - Data write failed

Examples

import React, { Component } from 'react';
import {
  AppRegistry,
  Button,
  StyleSheet,
  Text,
  Alert,
  View,
} from 'react-native';

import ScanManager from 'react-native-inateck-scannersdk'

export default class now extends Component {
  constructor(props) {
    super(props);
    this.state = {
      receiveData: "",
      InateckScannerBarcodeType: [],
      InateckScannerEventIds: [],
      peripheralId: ""
    }
  }

  componentDidMount() {
    this.initScan()
  }

  componentWillUnmount() {
    ScanManager.unmountScannerEvent()
  }

  initScan() {
    ScanManager.getInateckScannerBarcodeType().then((data) => {
      this.setState({
        InateckScannerBarcodeType: data
      })
    }).catch((err) => {
      console.log(err)
    })

    ScanManager.getInateckScannerEventIds().then((data) => {
      this.setState({
        InateckScannerEventIds: data
      })
    }).catch((err) => {
      console.log(err)
    })

    ScanManager.scan(this.handleScan, 3).then(() => {
    }).catch((err) => {
      console.log(err)
    })
  }

  alert(text) {
    Alert.alert("Tips", text, [{ text: "OK", onPress: () => { } }]);
  }

  handleScan = (args) => {
    let scannerEventIds=this.state.InateckScannerEventIds
    switch (args.code) {
      case scannerEventIds.deviceList:
        if (args.data.length > 0) {
          const appInfo = {
            appId: 'M693be162686a',
            developerId: 'bb57d8e1-f911-47ba-b510-693be162686a',
            appKey: 'MC0CFQC85w0MsxDng4wHBICX7+iCOiSqfAIUdSerA4/MJ2kYBGAGgIG/YHemNr8=',
          }
          
          ScanManager.connect(args.data[0].id, appInfo).then(() => {
            // Success code
          }).catch((err) => {
            this.alert("connection failed")
          })
        }
        break;
      case scannerEventIds.bleState:
        console.log(args.data)
        break;
      case scannerEventIds.barcodeData:
        msg = "BarcodeData:" + args.data.value
        this.alert(msg)
        break;
      case scannerEventIds.batteryLevel:
        msg = "BatteryLevel" + args.data[0]
        this.alert(msg)
        break;
      case scannerEventIds.deviceArrival:
        this.setState({ peripheralId: args.data.peripheral })
        this.alert("Scanner connected")
        break;
      case scannerEventIds.deviceDisconnect:
        this.alert("Scanner Disconnect")
        break;
    }
  }

  vibrationConfirmation() {
    ScanManager.vibrationConfirmation(this.state.peripheralId).then(() => {
      this.alert("Operation succeeded")
    }).catch((err) => {
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }

  openOrCloseLightingLamp(val) {
    ScanManager.openOrCloseLightingLamp(this.state.peripheralId, val).then(() => {
      this.alert("Operation succeeded")
    }).catch((err) => {
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }

  openOrClosePositioningLamp(val) {
    ScanManager.openOrClosePositioningLamp(this.state.peripheralId, val).then(() => {
      this.alert("Operation succeeded")
    }).catch((err) => {
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }

  setSoundVolume(val) {
    ScanManager.setSoundVolume(this.state.peripheralId, val).then(() => {
      this.alert("Operation succeeded")
    }).catch((err) => {
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }

  openOrCloseShake(val) {
    ScanManager.openOrCloseShake(this.state.peripheralId, val).then(() => {
      this.alert("Operation succeeded")
    }).catch((err) => {
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }

  openOrCloseBarcodeType(val) {
    ScanManager.openOrCloseBarcodeType(this.state.peripheralId, 'IATA25', val).then(() => {
      this.alert("Operation succeeded")
    }).catch((err) => {
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }

  setScannerName() {
    ScanManager.setScannerName(this.state.peripheralId, "HPRT-DAADHPRT-DAAD").then(() => {
      this.alert("Operation succeeded")
    }).catch((err) => {
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }

  readBatteryLevel() {
    ScanManager.readBatteryLevel(this.state.peripheralId).then((data) => {
      let msg = data[0]
      this.alert("Battery Level is:" + msg)
    }).catch((err) => {
      console.log(err)
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }

  openDateSuffix() {
    ScanManager.openDateSuffix(this.state.peripheralId).then(() => {
      this.alert("Operation succeeded")
    }).catch((err) => {
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }

  removeDateSuffix() {
    ScanManager.removeDateSuffix(this.state.peripheralId).then(() => {
      this.alert("Operation succeeded")
    }).catch((err) => {
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }

  openTimeSuffix() {
    ScanManager.openTimeSuffix(this.state.peripheralId).then(() => {
      this.alert("Operation succeeded")
    }).catch((err) => {
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }

  removeTimeSuffix() {
    ScanManager.removeTimeSuffix(this.state.peripheralId).then(() => {
      this.alert("Operation succeeded")
    }).catch((err) => {
      this.alert("Operation failed:" + JSON.stringify(err))
    })
  }


  render() {
    return (
      <View style={styles.container}>
        <View style={styles.fixToText}>
          <Button title="Re search" onPress={() => this.initScan()} />
          <View style={styles.btnMargin}>
            <Button title="Read Battery Level" onPress={() => this.readBatteryLevel()} />
          </View>
          <View style={styles.btnMargin}>
            <Button title="Vibration Confirmation" onPress={() => this.vibrationConfirmation()} />
          </View>
        </View>
        <View style={styles.fixToText}>
          <Button title="Open volume" onPress={() => this.setSoundVolume(2)} />
          <View style={styles.btnMargin}>
            <Button title="Close volume" onPress={() => this.setSoundVolume(0)} />
          </View>
        </View>
        <View style={styles.fixToText}>
          <Button title="Switch Lighting Lamp 1" onPress={() => this.openOrCloseLightingLamp('00')} />
          <View style={styles.btnMargin}>
            <Button title="Switch Lighting Lamp 2" onPress={() => this.openOrCloseLightingLamp('10')} />
          </View>
        </View>
        <View style={styles.fixToText}>
          <Button title="Switch Positioning Lamp 1" onPress={() => this.openOrClosePositioningLamp('00')} />
          <View style={styles.btnMargin}>
            <Button title="Switch Positioning Lamp 2" onPress={() => this.openOrClosePositioningLamp('10')} />
          </View>
        </View>
        <View style={styles.fixToText}>
          <Button title="Open vibration" onPress={() => this.openOrCloseShake(1)} />
          <View style={styles.btnMargin}>
            <Button title="Close vibration" onPress={() => this.openOrCloseShake(0)} />
          </View>
        </View>
        <View style={styles.fixToText}>
          <Button title="Open IATA25 code" onPress={() => this.openOrCloseBarcodeType(1)} />
          <View style={styles.btnMargin}>
            <Button title="Close IATA25 code" onPress={() => this.openOrCloseBarcodeType(0)} />
          </View>
        </View>
        <View style={styles.fixToText}>
          <Button title="Set Scanner Name" onPress={() => this.setScannerName()} />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 30,
  },
  fixToText: {
    margin: 10,
    flexDirection: 'row',
  },
  btnMargin: {
    marginLeft: 10
  }
});

AppRegistry.registerComponent('now', () => now);