react-native react-native-ble-manager 瀹炵幇 灏忕エ鎵撳嵃鍔熻兘

## 鐢ㄥ埌鐨勫伐鍏凤細

react-native

react-native-ble-manager

iconv-lite

buffer

## 瀹夎聽

npm install聽react-native-ble-manager

npm install聽buffer

npm install聽iconv-lite

鏂板缓 Ecs.js 鏂囦欢锛岃创浠g爜

```

const _ = require('lodash');

const Util = require('./util');

const Buffer = require('buffer').Buffer;

var iconv = require('iconv-lite');

const Common = {

INIT:"1B 40",//鍒濆鍖�

聽 聽 ALIGN_LEFT:"1B 61 00",//宸﹀榻�

聽 聽 ALIGN_RIGHT:"1B 61 02",//灞呭彸瀵归綈

聽 聽 ALIGN_CENTER:"1B 61 01",//灞呬腑瀵归綈

聽 聽 UNDER_LINE:"1C 2D 01",//涓嬪垝绾�

聽 聽 PRINT_AND_NEW_LINE:"0A",//鎵撳嵃骞舵崲琛�

聽 聽 FONT_SMALL:"1B 4D 01",//灏忓彿瀛椾綋9x17

聽 聽 FONT_NORMAL:"1B 4D 00",//姝e父12x24

聽 聽 FONT_BOLD:"1B 45 01",//绮椾綋

聽 聽 FONT_HEIGHT_TIMES:'1B 21 10',

FONT_WIDTH_TIMES:'1B 21 20',

FONT_HEIGHT_WIDTH_TIMES:'1B 21 30',

SOUND:"1B 42 02 02" // 铚傞福 2娆�/100ms

};

const Config = {

wordNumber:48 // 鍙墦鍗扮殑瀛楁暟锛屽搴�80mm绾稿紶

};

let printArray = [];

function writeTextToDevice(text){

let re =iconv.encode(text,'gbk')

console.log("writeTextToDevice",Array.from(re));

// return an array of bytes

聽 聽 printArray =printArray.concat(Array.from(re));

return re;

}

function writeHexToDevice(hexString) {

let str = hexString.toLowerCase().replace(" ","");

let pos =0;

let len =str.length;

if (len %2 !=0) {

return null;

}

len /=2;

let hexA =new Array();

for (let i =0;i

let s =str.substr(pos,2);

let v =parseInt(s,16);

hexA.push(v);

pos +=2;

}

console.log("writeHexToDevice",hexA);

printArray =printArray.concat(hexA);

return hexA;

}

function setConfig(config) {

Object.assign(Config, config);

}

function leftRight(left, right, wordNumber =Config.wordNumber) {

return left +Util.getSpace(wordNumber -Util.getWordsLength(left) -Util.getWordsLength(right)) + right;

}

function keyValue(name, value, wordNumber =Config.wordNumber) {

const nameLen =Util.getWordsLength(name);

let vArr = [],temp ='';

_.each(value, (v, i) => {

const tvLen =Util.getWordsLength(temp + v);

const diff =tvLen - (wordNumber -nameLen);

if (diff <=0) {

temp += v;

if (i === value.length -1) {

vArr.push(temp);

}

}else {

if (Util.isChinese(v) &&diff ===1) {

temp +=' ';

}

vArr.push(temp);

temp = v;

}

});

return _.map(vArr, (v, i) => {

if (i ===0) {

return name + v;

}else {

return Util.getSpace(name.length) + v;

}

}).join('');

}

const ESC = {

Common,

Util: {

leftRight,

keyValue,

},

setConfig,

init(){

writeHexToDevice(Common.INIT);

},

printAndNewLine(){

writeHexToDevice(Common.PRINT_AND_NEW_LINE);

},

alignLeft(){

writeHexToDevice(Common.ALIGN_LEFT);

},

alignCenter(){

writeHexToDevice(Common.ALIGN_CENTER);

},

alignRight(){

writeHexToDevice(Common.ALIGN_RIGHT);

},

underline(){

writeHexToDevice(Common.UNDER_LINE);

},

fontSmall(){

writeHexToDevice(Common.FONT_SMALL);

},

fontNormal(){

writeHexToDevice(Common.FONT_NORMAL);

},

fontBold(){

writeHexToDevice(Common.FONT_BOLD);

},

fontHeightTimes(){

writeHexToDevice(Common.FONT_HEIGHT_TIMES);

},

fontHeightTimes(){

writeHexToDevice(Common.FONT_WIDTH_TIMES);

},

fontHeightTimes(){

writeHexToDevice(Common.FONT_HEIGHT_WIDTH_TIMES);

},

text(str){

writeTextToDevice(str)

},

sound(){

writeHexToDevice(Common.SOUND);

},

getByte(){

return printArray;

},

resetByte(){

printArray = [];

}

};

module.exports =ESC;

```

鏂板缓util.js 璐翠唬鐮�

```

const _ = require('lodash');

function isChinese(word) {

const charCode = word.charCodeAt(0);

return !(charCode >=0 &&charCode <=128)

}

function getWordLength(word) {

return isChinese(word) ?2 :1;

}

function getWordsLength(words) {

return _.reduce(words, (m, v) => m +getWordLength(v),0);

}

function getSpace(len) {

return _.times(len, () =>' ').join('');

}

module.exports = {

isChinese,

getWordsLength,

getWordLength,

getSpace

};

```

鏂板缓聽BleModule.js 璐翠唬鐮�

```

/**

* Created by guang on 2016/11/21.

*/

import {

Platform,

NativeModules,

NativeEventEmitter

}from 'react-native';

import BleManagerfrom 'react-native-ble-manager';

const BleManagerModule =NativeModules.BleManager;

//閫氳繃NativeAppEventEmitter.addListener娣诲姞鐩戝惉鐨勬柟娉曞畼鏂瑰凡涓嶅缓璁娇鐢�

const bleManagerEmitter =new NativeEventEmitter(BleManagerModule);

export default class BleModule{

constructor(){

this.isConnecting =false;//钃濈墮鏄惁杩炴帴

聽 聽 聽 聽 this.bluetoothState ='off';//钃濈墮鎵撳紑鐘舵��

聽 聽 聽 聽 this.initUUID();

}

/**

聽 聽 * 娣诲姞鐩戝惉鍣�

聽 聽 * 鎵�鏈夌洃鍚簨浠跺涓�

聽 聽 * BleManagerStopScan锛氭壂鎻忕粨鏉熺洃鍚�

聽 聽 * BleManagerDiscoverPeripheral锛氭壂鎻忓埌涓�涓柊璁惧

聽 聽 * BleManagerDidUpdateState锛氳摑鐗欑姸鎬佹敼鍙�

聽 聽 * BleManagerDidUpdateValueForCharacteristic锛氭帴鏀跺埌鏂版暟鎹�

聽 聽 * BleManagerConnectPeripheral锛氳摑鐗欒澶囧凡杩炴帴

聽 聽 * BleManagerDisconnectPeripheral锛氳摑鐗欒澶囧凡鏂紑杩炴帴

聽 聽 * */

聽 聽 addListener(str,fun){

return bleManagerEmitter.addListener(str,fun);

}

/**

聽 聽 * 鍒濆鍖栬摑鐗欐ā鍧�

聽 聽 * Init the module.

* */

聽 聽 start(){

BleManager.start({showAlert:false})

.then( ()=>{

this.checkState();

console.log('Init the module success.');

}).catch(error=>{

console.log('Init the module fail.');

});

}

/**

聽 聽 * 寮哄埗妫�鏌ヨ摑鐗欑姸鎬�

聽 聽 * Force the module to check the state of BLE and trigger a BleManagerDidUpdateState event.

* */

聽 聽 checkState(){

BleManager.checkState();

}

/**

聽 聽 * 鎵弿鍙敤璁惧锛�5绉掑悗缁撴潫

聽 聽 * Scan for availables peripherals.

* */

聽 聽 scan() {

return new Promise( (resolve, reject) =>{

BleManager.scan([],5,true)

.then( () => {

console.log('Scan started');

resolve();

}).catch( (err)=>{

console.log('Scan started fail');

reject(err);

});

});

}

/**

聽 聽 * 鍋滄鎵弿

聽 聽 * Stop the scanning.

* */

聽 聽 stopScan() {

BleManager.stopScan()

.then(() => {

console.log('Scan stopped');

}).catch((err)=>{

console.log('Scan stopped fail',err);

});

}

/**

聽 聽 * 杩斿洖鎵弿鍒扮殑钃濈墮璁惧

聽 聽 * Return the discovered peripherals after a scan.

* */

聽 聽 getDiscoveredPeripherals() {

return new Promise( (resolve, reject) =>{

BleManager.getDiscoveredPeripherals([])

.then((peripheralsArray) => {

console.log('Discovered peripherals: ', peripheralsArray);

resolve(peripheralsArray);

})

.catch(error=>{

});

});

}

/**

* Converts UUID to full 128bit.

*

聽 聽 * @param {UUID} uuid 16bit, 32bit or 128bit UUID.

聽 聽 * @returns {UUID} 128bit UUID.

*/

聽 聽 fullUUID(uuid) {

if (uuid.length ===4){

return '0000' + uuid.toUpperCase() +'-0000-1000-8000-00805F9B34FB'

聽 聽 聽 聽 }

if (uuid.length ===8) {

return uuid.toUpperCase() +'-0000-1000-8000-00805F9B34FB'

聽 聽 聽 聽 }

return uuid.toUpperCase()

}

initUUID(){

this.readServiceUUID = [];

this.readCharacteristicUUID = [];

this.writeWithResponseServiceUUID = [];

this.writeWithResponseCharacteristicUUID = [];

this.writeWithoutResponseServiceUUID = [];

this.writeWithoutResponseCharacteristicUUID = [];

this.nofityServiceUUID = [];

this.nofityCharacteristicUUID = [];

}

//鑾峰彇Notify銆丷ead銆乄rite銆乄riteWithoutResponse鐨剆erviceUUID鍜宑haracteristicUUID

聽 聽 getUUID(peripheralInfo){

this.readServiceUUID = [];

this.readCharacteristicUUID = [];

this.writeWithResponseServiceUUID = [];

this.writeWithResponseCharacteristicUUID = [];

this.writeWithoutResponseServiceUUID = [];

this.writeWithoutResponseCharacteristicUUID = [];

this.nofityServiceUUID = [];

this.nofityCharacteristicUUID = [];

for(let item of peripheralInfo.characteristics){

item.service =this.fullUUID(item.service);

item.characteristic =this.fullUUID(item.characteristic);

if(Platform.OS =='android'){

if(item.properties.Notify =='Notify'){

this.nofityServiceUUID.push(item.service);

this.nofityCharacteristicUUID.push(item.characteristic);

}

if(item.properties.Read =='Read'){

this.readServiceUUID.push(item.service);

this.readCharacteristicUUID.push(item.characteristic);

}

if(item.properties.Write =='Write'){

this.writeWithResponseServiceUUID.push(item.service);

this.writeWithResponseCharacteristicUUID.push(item.characteristic);

}

if(item.properties.WriteWithoutResponse =='WriteWithoutResponse'){

this.writeWithoutResponseServiceUUID.push(item.service);

this.writeWithoutResponseCharacteristicUUID.push(item.characteristic);

}

}else{//ios

聽 聽 聽 聽 聽 聽 聽 聽 for(let property of item.properties){

if(property =='Notify'){

this.nofityServiceUUID.push(item.service);

this.nofityCharacteristicUUID.push(item.characteristic);

}

if(property =='Read'){

this.readServiceUUID.push(item.service);

this.readCharacteristicUUID.push(item.characteristic);

}

if(property =='Write'){

this.writeWithResponseServiceUUID.push(item.service);

this.writeWithResponseCharacteristicUUID.push(item.characteristic);

}

if(property =='WriteWithoutResponse'){

this.writeWithoutResponseServiceUUID.push(item.service);

this.writeWithoutResponseCharacteristicUUID.push(item.characteristic);

}

}

}

}

console.log('readServiceUUID',this.readServiceUUID);

console.log('readCharacteristicUUID',this.readCharacteristicUUID);

console.log('writeWithResponseServiceUUID',this.writeWithResponseServiceUUID);

console.log('writeWithResponseCharacteristicUUID',this.writeWithResponseCharacteristicUUID);

console.log('writeWithoutResponseServiceUUID',this.writeWithoutResponseServiceUUID);

console.log('writeWithoutResponseCharacteristicUUID',this.writeWithoutResponseCharacteristicUUID);

console.log('nofityServiceUUID',this.nofityServiceUUID);

console.log('nofityCharacteristicUUID',this.nofityCharacteristicUUID);

}

/**

聽 聽 * 杩炴帴钃濈墮

聽 聽 * Attempts to connect to a peripheral.

* */

聽 聽 connect(id) {

this.isConnecting =true;//褰撳墠钃濈墮姝e湪杩炴帴涓�

聽 聽 聽 聽 return new Promise( (resolve, reject) =>{

BleManager.connect(id)

.then(() => {

console.log('Connected success.');

return BleManager.retrieveServices(id);

})

.then((peripheralInfo)=>{

console.log('Connected peripheralInfo: ', peripheralInfo);

this.peripheralId = peripheralInfo.id;

this.getUUID(peripheralInfo);

this.isConnecting =false;//褰撳墠钃濈墮杩炴帴缁撴潫

聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 resolve(peripheralInfo);

})

.catch(error=>{

console.log('Connected error:',error);

this.isConnecting =false;//褰撳墠钃濈墮杩炴帴缁撴潫

聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 reject(error);

});

});

}

/**

聽 聽 * 鏂紑钃濈墮杩炴帴

聽 聽 * Disconnect from a peripheral.

* */

聽 聽 disconnect() {

BleManager.disconnect(this.peripheralId)

.then( () => {

console.log('Disconnected');

})

.catch( (error) => {

console.log('Disconnected error:',error);

});

}

/**

聽 聽 * 鎵撳紑閫氱煡

聽 聽 * Start the notification on the specified characteristic.

* */

聽 聽 startNotification(index =0) {

return new Promise( (resolve, reject) =>{

BleManager.startNotification(this.peripheralId,this.nofityServiceUUID[index],this.nofityCharacteristicUUID[index])

.then(() => {

console.log('Notification started');

resolve();

})

.catch((error) => {

console.log('Notification error:',error);

reject(error);

});

});

}

/**

聽 聽 * 鍏抽棴閫氱煡

聽 聽 * Stop the notification on the specified characteristic.

* */

聽 聽 stopNotification(index =0) {

BleManager.stopNotification(this.peripheralId,this.nofityServiceUUID[index],this.nofityCharacteristicUUID[index])

.then(() => {

console.log('stopNotification success!');

resolve();

})

.catch((error) => {

console.log('stopNotification error:',error);

reject(error);

});

}

/**

聽 聽 * 鍐欐暟鎹埌钃濈墮

聽 聽 * 鍙傛暟锛�(peripheralId, serviceUUID, characteristicUUID, data, maxByteSize)

* Write with response to the specified characteristic, you need to call retrieveServices method before.

* */

聽 聽 write(data,index =0) {

// data = this.addProtocol(data);聽 //鍦ㄦ暟鎹殑澶村熬鍔犲叆鍗忚鏍煎紡锛屽0A => FEFD010AFCFB锛屼笉鍚岀殑钃濈墮鍗忚搴斾綔鐩稿簲鐨勬洿鏀�

聽 聽 聽 聽 return new Promise( (resolve, reject) =>{

BleManager.write(this.peripheralId,this.writeWithResponseServiceUUID[index],this.writeWithResponseCharacteristicUUID[index], data)

.then(() => {

console.log('Write success: ',data.toString());

resolve();

})

.catch((error) => {

console.log('Write聽 failed: ',data);

reject(error);

});

});

}

/**

聽 聽 * 鍐欐暟鎹埌钃濈墮锛屾病鏈夊搷搴�

聽 聽 * 鍙傛暟锛�(peripheralId, serviceUUID, characteristicUUID, data, maxByteSize)

* Write without response to the specified characteristic, you need to call retrieveServices method before.

* */

聽 聽 writeWithoutResponse(data,index =0){

return new Promise( (resolve, reject) =>{

BleManager.writeWithoutResponse(this.peripheralId,this.writeWithoutResponseServiceUUID[index],this.writeWithoutResponseCharacteristicUUID[index], data)

.then(() => {

console.log('Write success: ',data);

resolve();

})

.catch((error) => {

console.log('Write聽 failed: ',data);

reject(error);

});

});

}

/**

聽 聽 * 璇诲彇鏁版嵁

聽 聽 * Read the current value of the specified characteristic, you need to call retrieveServices method before

* */

聽 聽 read(index =0){

return new Promise( (resolve, reject) =>{

BleManager.read(this.peripheralId,this.readServiceUUID[index],this.readCharacteristicUUID[index])

.then((data) => {

console.log('Read: ',data);

resolve(data);

})

.catch((error) => {

console.log(error);

reject(error);

});

});

}

/**

聽 聽 * 杩斿洖宸茶繛鎺ョ殑钃濈墮璁惧

聽 聽 * Return the connected peripherals.

* */

聽 聽 getConnectedPeripherals() {

BleManager.getConnectedPeripherals([])

.then((peripheralsArray) => {

console.log('Connected peripherals: ', peripheralsArray);

}).catch(error=>{

})

}

/**

聽 聽 * 鍒ゆ柇鎸囧畾璁惧鏄惁宸茶繛鎺�

聽 聽 * Check whether a specific peripheral is connected and return true or false

*/

聽 聽 isPeripheralConnected(){

return new Promise( (resolve, reject) =>{

BleManager.isPeripheralConnected(this.peripheralId, [])

.then((isConnected) => {

resolve(isConnected);

if (isConnected) {

console.log('Peripheral is connected!');

}else {

console.log('Peripheral is NOT connected!');

}

}).catch(error=>{

reject(error);

})

});

}

/**

聽 聽 * 钃濈墮鎺ユ敹鐨勪俊鍙峰己搴�

聽 聽 * Read the current value of the RSSI

* */

聽 聽 readRSSI(id) {

return new Promise( (resolve, reject) =>{

BleManager.readRSSI(id)

.then((rssi) => {

console.log(id,'RSSI: ',rssi);

resolve(rssi)

})

.catch((error) => {

console.log(error);

reject(error)

});

});

}

/**

聽 聽 * 鎵撳紑钃濈墮(Android only)

* Create the request to the user to activate the bluetooth

* */

聽 聽 enableBluetooth() {

BleManager.enableBluetooth()

.then(() => {

console.log('The bluetooh is already enabled or the user confirm');

})

.catch((error) => {

console.log('The user refuse to enable bluetooth');

});

}

/**

* Android only

聽 聽 * 寮�鍚竴涓粦瀹氳繙绋嬭澶囩殑杩涚▼

聽 聽 * Start the bonding (pairing) process with the remote device

* */

聽 聽 createBond(){

BleManager.createBond(this.peripheralId)

.then(() => {

console.log('createBond success or there is already an existing one');

})

.catch(() => {

console.log('fail to bond');

})

}

/**

* Android only

聽 聽 * 鑾峰彇宸茬粦瀹氱殑璁惧

聽 聽 * Return the bonded peripherals

* */

聽 聽 getBondedPeripherals(){

BleManager.getBondedPeripherals([])

.then((bondedPeripheralsArray) => {

// Each peripheral in returned array will have id and name properties

聽 聽 聽 聽 聽 聽 聽 聽 console.log('Bonded peripherals: ' + bondedPeripheralsArray);

});

}

/**

聽 聽 * 鍦ㄥ凡缁戝畾鐨勭紦瀛樺垪琛ㄤ腑绉婚櫎璁惧

聽 聽 * Removes a disconnected peripheral from the cached list.

* It is useful if the device is turned off,

* because it will be re-discovered upon turning on again

* */

聽 聽 removePeripheral(){

return new Promise( (resolve, reject) =>{

BleManager.removePeripheral(this.peripheralId)

.then(()=>{

resolve();

})

.catch(error=>{

reject(error);

})

});

}

/**

聽 聽 * 娣诲姞钃濈墮鍗忚鏍煎紡锛屽寘澶淬�佹暟鎹暱搴︺�佸寘灏撅紝涓嶅悓鐨勮摑鐗欏崗璁簲浣滅浉搴旂殑鏇存敼

聽 聽 * 0A => FEFD010AFCFB

* */

聽 聽 addProtocol(data){

return 'FEFD' +this.getHexByteLength(data) + data +'FCFB';

}

/**

聽 聽 * 璁$畻鍗佸叚杩涘埗鏁版嵁闀垮害锛屾瘡涓や綅涓�1涓暱搴︼紝杩斿洖鍗佸叚杩涘埗闀垮害

聽 聽 * */

聽 聽 getHexByteLength(str){

let length =parseInt(str.length /2);

let hexLength =this.addZero(length.toString(16));

return hexLength;

}

/**

聽 聽 * 鍦ㄥ瓧绗︿覆鍓嶉潰娣诲姞 0, 榛樿琛ュ厖涓�2浣�

聽 聽 * */

聽 聽 addZero(str, bit=2){

for(let i = str.length;i < bit;i++){

str ='0' + str;

}

return str;

}

/**

聽 聽 * ios绯荤粺浠庤摑鐗欏箍鎾俊鎭腑鑾峰彇钃濈墮MAC鍦板潃

聽 聽 * */

聽 聽 getMacAddressFromIOS(data){

let macAddressInAdvertising = data.advertising.kCBAdvDataManufacturerMacAddress;

//涓簎ndefined浠h〃姝よ摑鐗欏箍鎾俊鎭噷涓嶅寘鎷琈ac鍦板潃

聽 聽 聽 聽 if(!macAddressInAdvertising){

return;

}

macAddressInAdvertising =macAddressInAdvertising.replace("<","").replace(">","").replace(" ","");

if(macAddressInAdvertising !=undefined &&macAddressInAdvertising !=null &&macAddressInAdvertising !='') {

macAddressInAdvertising =this.swapEndianWithColon(macAddressInAdvertising);

}

return macAddressInAdvertising;

}

/**

聽 聽 * ios浠庡箍鎾腑鑾峰彇鐨刴ac鍦板潃杩涜澶у皬绔牸寮忎簰鎹紝骞跺姞涓婂啋鍙�:

聽 聽 * @param string聽 聽 聽 聽 010000CAEA80

聽 聽 * @returns string聽 聽 聽 80:EA:CA:00:00:01

* */

聽 聽 swapEndianWithColon(str){

let format ='';

let len = str.length;

for(let j =2;j <=len;j =j +2){

format += str.substring(len-j,len-(j-2));

if(j !=len) {

format +=":";

}

}

return format.toUpperCase();

}

}

```

鏂板缓聽BlueToothPrinterPage.js 璐翠唬鐮�

```

import React, { Component }from 'react'

import _from 'lodash';

import {

StyleSheet,

Text,

TouchableOpacity,

View,

FlatList,

Platform,

TextInput,

Dimensions,

Alert,

}from 'react-native'

import BleModulefrom './BleModule';

import ESCfrom "../../../components/ecs/Ecs";

//纭繚鍏ㄥ眬鍙湁涓�涓狟leManager瀹炰緥锛孊leModule绫讳繚瀛樼潃钃濈墮鐨勮繛鎺ヤ俊鎭�

global.BluetoothManager =new BleModule();

export default class BlueToothPrinterPageextends Component {

constructor(props) {

super(props);

this.state={

data: [],

scaning:false,

isConnected:false,

text:'',

writeData:'',

receiveData:'',

readData:'',

isMonitoring:false

聽 聽 聽 聽 }

this.bluetoothReceiveData = [];//钃濈墮鎺ユ敹鐨勬暟鎹紦瀛�

聽 聽 聽 聽 this.deviceMap =new Map();

}

componentDidMount(){

BluetoothManager.start();//钃濈墮鍒濆鍖�

聽 聽 聽 聽 this.updateStateListener =BluetoothManager.addListener('BleManagerDidUpdateState',this.handleUpdateState);

this.stopScanListener =BluetoothManager.addListener('BleManagerStopScan',this.handleStopScan);

this.discoverPeripheralListener =BluetoothManager.addListener('BleManagerDiscoverPeripheral',this.handleDiscoverPeripheral);

this.connectPeripheralListener =BluetoothManager.addListener('BleManagerConnectPeripheral',this.handleConnectPeripheral);

this.disconnectPeripheralListener =BluetoothManager.addListener('BleManagerDisconnectPeripheral',this.handleDisconnectPeripheral);

this.updateValueListener =BluetoothManager.addListener('BleManagerDidUpdateValueForCharacteristic',this.handleUpdateValue);

}

componentWillUnmount(){

this.updateStateListener.remove();

this.stopScanListener.remove();

this.discoverPeripheralListener.remove();

this.connectPeripheralListener.remove();

this.disconnectPeripheralListener.remove();

this.updateValueListener.remove();

if(this.state.isConnected){

BluetoothManager.disconnect();//閫�鍑烘椂鏂紑钃濈墮杩炴帴

聽 聽 聽 聽 }

}

//钃濈墮鐘舵�佹敼鍙�

聽 聽 handleUpdateState=(args)=>{

console.log('BleManagerDidUpdateStatea:', args);

BluetoothManager.bluetoothState = args.state;

if(args.state =='on'){//钃濈墮鎵撳紑鏃惰嚜鍔ㄦ悳绱�

聽 聽 聽 聽 聽 聽 this.scan();

}

}

//鎵弿缁撴潫鐩戝惉

聽 聽 handleStopScan=()=>{

console.log('BleManagerStopScan:','Scanning is stopped');

this.setState({scaning:false});

}

//鎼滅储鍒颁竴涓柊璁惧鐩戝惉

聽 聽 handleDiscoverPeripheral=(data)=>{

// console.log('BleManagerDiscoverPeripheral:', data);

聽 聽 聽 聽 console.log(data.id,data.name);

let id;//钃濈墮杩炴帴id

聽 聽 聽 聽 let macAddress;//钃濈墮Mac鍦板潃

聽 聽 聽 聽 if(Platform.OS =='android'){

macAddress = data.id;

id =macAddress;

}else{

//ios杩炴帴鏃朵笉闇�瑕佺敤鍒癕ac鍦板潃锛屼絾璺ㄥ钩鍙拌瘑鍒悓涓�璁惧鏃堕渶瑕丮ac鍦板潃

聽 聽 聽 聽 聽 聽 //濡傛灉骞挎挱鎼哄甫鏈塎ac鍦板潃锛宨os鍙�氳繃骞挎挱0x18鑾峰彇钃濈墮Mac鍦板潃锛�

聽 聽 聽 聽 聽 聽 macAddress =BluetoothManager.getMacAddressFromIOS(data);

id = data.id;

}

this.deviceMap.set(data.id,data);//浣跨敤Map绫诲瀷淇濆瓨鎼滅储鍒扮殑钃濈墮璁惧锛岀‘淇濆垪琛ㄤ笉鏄剧ず閲嶅鐨勮澶�

聽 聽 聽 聽 this.setState({data:[...this.deviceMap.values()]});

}

//钃濈墮璁惧宸茶繛鎺�

聽 聽 handleConnectPeripheral=(args)=>{

console.log('BleManagerConnectPeripheral:', args);

}

//钃濈墮璁惧宸叉柇寮�杩炴帴

聽 聽 handleDisconnectPeripheral=(args)=>{

console.log('BleManagerDisconnectPeripheral:', args);

let newData = [...this.deviceMap.values()]

BluetoothManager.initUUID();//鏂紑杩炴帴鍚庢竻绌篣UID

聽 聽 聽 聽 this.setState({

data:newData,

isConnected:false,

writeData:'',

readData:'',

receiveData:'',

text:'',

});

}

//鎺ユ敹鍒版柊鏁版嵁

聽 聽 handleUpdateValue=(data)=>{

//ios鎺ユ敹鍒扮殑鏄皬鍐欑殑16杩涘埗锛宎ndroid鎺ユ敹鐨勬槸澶у啓鐨�16杩涘埗锛岀粺涓�杞寲涓哄ぇ鍐�16杩涘埗

聽 聽 聽 聽 let value = data.value.toUpperCase();

this.bluetoothReceiveData.push(value);

console.log('BluetoothUpdateValue',value);

this.setState({receiveData:this.bluetoothReceiveData.join('')})

}

connect(item){

//褰撳墠钃濈墮姝e湪杩炴帴鏃朵笉鑳芥墦寮�鍙︿竴涓繛鎺ヨ繘绋�

聽 聽 聽 聽 if(BluetoothManager.isConnecting){

console.log('褰撳墠钃濈墮姝e湪杩炴帴鏃朵笉鑳芥墦寮�鍙︿竴涓繛鎺ヨ繘绋�');

return;

}

if(this.state.scaning){//褰撳墠姝e湪鎵弿涓紝杩炴帴鏃跺叧闂壂鎻�

聽 聽 聽 聽 聽 聽 BluetoothManager.stopScan();

this.setState({scaning:false});

}

let newData = [...this.deviceMap.values()]

newData[item.index].isConnecting =true;

this.setState({data:newData});

BluetoothManager.connect(item.item.id)

.then(peripheralInfo=>{

let newData = [...this.state.data];

newData[item.index].isConnecting =false;

//杩炴帴鎴愬姛锛屽垪琛ㄥ彧鏄剧ず宸茶繛鎺ョ殑璁惧

聽 聽 聽 聽 聽 聽 聽 聽 this.setState({

data:[item.item],

isConnected:true

聽 聽 聽 聽 聽 聽 聽 聽 });

})

.catch(err=>{

let newData = [...this.state.data];

newData[item.index].isConnecting =false;

this.setState({data:newData});

this.alert('杩炴帴澶辫触');

})

}

disconnect(){

this.setState({

data:[...this.deviceMap.values()],

isConnected:false

聽 聽 聽 聽 });

BluetoothManager.disconnect();

}

scan(){

if(this.state.scaning){//褰撳墠姝e湪鎵弿涓�

聽 聽 聽 聽 聽 聽 BluetoothManager.stopScan();

this.setState({scaning:false});

}

if(BluetoothManager.bluetoothState =='on'){

BluetoothManager.scan()

.then(()=>{

this.setState({scaning:true });

}).catch(err=>{

})

}else{

BluetoothManager.checkState();

if(Platform.OS =='ios'){

this.alert('璇峰紑鍚墜鏈鸿摑鐗�');

}else{

Alert.alert('鎻愮ず','璇峰紑鍚墜鏈鸿摑鐗�',[

{

text:'鍙栨秷',

onPress:()=>{ }

},

{

text:'鎵撳紑',

onPress:()=>{BluetoothManager.enableBluetooth() }

}

]);

}

}

}

alert(text){

Alert.alert('鎻愮ず',text,[{text:'纭畾',onPress:()=>{ } }]);

}

/*write=(index)=>{

if(this.state.text.length == 0){

聽 聽 聽 聽 聽 聽 this.alert('璇疯緭鍏ユ秷鎭�');

return;

}

BluetoothManager.write(this.state.text,index)

.then(()=>{

this.bluetoothReceiveData = [];

this.setState({

writeData:this.state.text,

text:'',

})

})

.catch(err=>{

聽 聽 聽 聽 聽 聽 聽 聽 this.alert('鍙戦�佸け璐�');

})

}*/

聽 聽 write=(index)=>{

BluetoothManager.write(this.print(),index)

.then(()=>{

this.bluetoothReceiveData = [];

this.setState({

writeData:this.state.text,

text:'',

})

})

.catch(err=>{

this.alert('鍙戦�佸け璐�');

})

}

print(){

ESC.resetByte();

// 涓�瀹氳閰嶇疆濂�

聽 聽 聽 聽 const Config = {

wordNumber:48

聽 聽 聽 聽 };

ESC.setConfig(Config);

ESC.init();

ESC.alignCenter();

ESC.fontBold();

ESC.printAndNewLine();

ESC.text('姝e畾鏂板尯璁哥繝钄彍搴�');

ESC.printAndNewLine();

ESC.text('閲囪喘璁㈣揣鍗�');

ESC.printAndNewLine();

ESC.printAndNewLine();

ESC.init();

ESC.text('涓嬪崟鏃堕棿锛�2016-09-06 19:30:23');

ESC.printAndNewLine();

ESC.text('鍗曟嵁缂栧彿锛歍2345-CGD-2017-01-14-00005');

ESC.printAndNewLine();

ESC.text('閲囪喘鍗曚綅锛氬皬鍐滃コ渚涘簲閾句紭鍏堝叕鍙�');

ESC.printAndNewLine();

ESC.text('閲囪喘缁忓姙锛氶噰璐憳A');

ESC.printAndNewLine();

ESC.text('鐢德� 聽 璇濓細15201083760');

ESC.printAndNewLine();

ESC.printAndNewLine();

ESC.text('鍟嗗搧鏄庣粏锛氬叡2绉嶅晢鍝�');

ESC.printAndNewLine();

// 鍟嗗搧寮�濮�

聽 聽 聽 聽 ESC.text(

ESC.Util.leftRight('澶у埄(42鏂�/浠�)','',20)

+ ESC.Util.leftRight('84鍏�/浠�','',11)

+ ESC.Util.leftRight('x1浠�','鎬讳环锛�84鍏�',17)

);

ESC.printAndNewLine();

ESC.text(' 锛�3鏂�,1鏂�/鏂�,瑕佹柊椴滅殑锛�+锛�5琚�,5鏂�/琚�,涓嶈鐫″垎澶鐨勶級');

ESC.printAndNewLine();

ESC.text(_.times(Config.wordNumber, () =>'-').join(''));

ESC.printAndNewLine();

// 鍟嗗搧缁撴潫

聽 聽 聽 聽 // 鍟嗗搧寮�濮�

聽 聽 聽 聽 ESC.text(

ESC.Util.leftRight('澶у埄(42鏂�/浠�)','',20)

+ ESC.Util.leftRight('84鍏�/浠�','',11)

+ ESC.Util.leftRight('x1浠�','鎬讳环锛�84鍏�',17)

);

ESC.printAndNewLine();

ESC.text(' 锛�3鏂�,1鏂�/鏂�,瑕佹柊椴滅殑锛�+锛�5琚�,5鏂�/琚�,涓嶈鐫″垎澶鐨勶級');

ESC.printAndNewLine();

ESC.text(_.times(Config.wordNumber, () =>'-').join(''));

ESC.printAndNewLine();

// 鍟嗗搧缁撴潫

聽 聽 聽 聽 ESC.text(_.times(Config.wordNumber, () =>'-').join(''));

ESC.printAndNewLine();

ESC.alignRight();

ESC.text('鍚堣锛�168鍏�');

ESC.printAndNewLine();

ESC.printAndNewLine();

ESC.printAndNewLine();

ESC.init();

ESC.text(ESC.Util.leftRight('閲囪喘缁忓姙锛�','',24) +'渚涘簲鍟嗭細');

ESC.printAndNewLine();

ESC.printAndNewLine();

ESC.printAndNewLine();

ESC.printAndNewLine();

ESC.printAndNewLine();

ESC.printAndNewLine();

ESC.printAndNewLine();

ESC.sound();

ESC.init();

console.log("浼犺緭瀛楄妭",ESC.getByte());

return ESC.getByte();

}

writeWithoutResponse=(index)=>{

if(this.state.text.length ==0){

this.alert('璇疯緭鍏ユ秷鎭�');

return;

}

BluetoothManager.writeWithoutResponse(this.state.text,index)

.then(()=>{

this.bluetoothReceiveData = [];

this.setState({

writeData:this.state.text,

text:'',

})

})

.catch(err=>{

this.alert('鍙戦�佸け璐�');

})

}

read=(index)=>{

BluetoothManager.read(index)

.then(data=>{

this.setState({readData:data});

})

.catch(err=>{

this.alert('璇诲彇澶辫触');

})

}

notify=(index)=>{

BluetoothManager.startNotification(index)

.then(()=>{

this.setState({isMonitoring:true});

this.alert('寮�鍚垚鍔�');

})

.catch(err=>{

this.setState({isMonitoring:false});

this.alert('寮�鍚け璐�');

})

}

renderItem=(item)=>{

let data = item.item;

return(

聽 聽 聽 聽 聽 聽 聽 聽 activeOpacity={0.7}聽 聽 聽 聽 聽 聽 聽 聽 disabled={this.state.isConnected?true:false}聽 聽 聽 聽 聽 聽 聽 聽 onPress={()=>{this.connect(item)}}聽 聽 聽 聽 聽 聽 聽 聽 style={styles.item}>

{data.name?data.name:''}

{data.isConnecting?'杩炴帴涓�...':''}

{data.id}

);

}

renderHeader=()=>{

return(

聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 activeOpacity={0.7}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 style={[styles.buttonView,{marginHorizontal:10,height:40,alignItems:'center'}]}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 onPress={this.state.isConnected?this.disconnect.bind(this):this.scan.bind(this)}>

{this.state.scaning?'姝e湪鎼滅储涓�':this.state.isConnected?'鏂紑钃濈墮':'鎼滅储钃濈墮'}

{this.state.isConnected?'褰撳墠杩炴帴鐨勮澶�':'鍙敤璁惧'}

)

}

renderFooter=()=>{

return(

{this.state.isConnected?

{this.renderWriteView('鍐欐暟鎹�(write)锛�','鍙戦��',BluetoothManager.writeWithResponseCharacteristicUUID,this.write,this.state.writeData)}

{this.renderWriteView('鍐欐暟鎹�(writeWithoutResponse)锛�','鍙戦��',BluetoothManager.writeWithoutResponseCharacteristicUUID,this.writeWithoutResponse,this.state.writeData)}

{this.renderReceiveView('璇诲彇鐨勬暟鎹細','璇诲彇',BluetoothManager.readCharacteristicUUID,this.read,this.state.readData)}

{this.renderReceiveView('閫氱煡鐩戝惉鎺ユ敹鐨勬暟鎹細'+`${this.state.isMonitoring?'鐩戝惉宸插紑鍚�':'鐩戝惉鏈紑鍚�'}`,'寮�鍚�氱煡',BluetoothManager.nofityCharacteristicUUID,this.notify,this.state.receiveData)}

:

}

)

}

renderReceiveView=(label,buttonText,characteristics,onPress,state)=>{

if(characteristics.length ==0){

return;

}

return(

{label}

{state}

{characteristics.map((item,index)=>{

return(

聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 activeOpacity={0.7}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 style={styles.buttonView}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 onPress={()=>{onPress(index)}}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 key={index}>

{buttonText} ({item})

)

})}

)

}

renderWriteView=(label,buttonText,characteristics,onPress,state)=>{

if(characteristics.length ==0){

return;

}

return(

{label}

{this.state.writeData}

{characteristics.map((item,index)=>{

return(

聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 key={index}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 activeOpacity={0.7}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 style={styles.buttonView}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 onPress={()=>{onPress(index)}}>

{buttonText} ({item})

)

})}

聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 style={[styles.textInput]}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 value={this.state.text}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 placeholder='璇疯緭鍏ユ秷鎭�'

聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 onChangeText={(text)=>{

this.setState({text:text});

}}聽 聽 聽 聽 聽 聽 聽 聽 />

)

}

render () {

return (

聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 renderItem={this.renderItem}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 ListHeaderComponent={this.renderHeader}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 ListFooterComponent={this.renderFooter}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 keyExtractor={item=>item.id}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 data={this.state.data}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 extraData={[this.state.isConnected,this.state.text,this.state.receiveData,this.state.readData,this.state.writeData,this.state.isMonitoring,this.state.scaning]}聽 聽 聽 聽 聽 聽 聽 聽 聽 聽 keyboardShouldPersistTaps='handled'

聽 聽 聽 聽 聽 聽 聽 聽 />

)

}

}

const styles =StyleSheet.create({

container: {

flex:1,

backgroundColor:'white',

marginTop:Platform.OS =='ios'?20:0,

},

item:{

flexDirection:'column',

borderColor:'rgb(235,235,235)',

borderStyle:'solid',

borderBottomWidth:StyleSheet.hairlineWidth,

paddingLeft:10,

paddingVertical:8,

},

buttonView:{

height:30,

backgroundColor:'rgb(33, 150, 243)',

paddingHorizontal:10,

borderRadius:5,

justifyContent:"center",

alignItems:'center',

alignItems:'flex-start',

marginTop:10

聽 聽 },

buttonText:{

color:"white",

fontSize:12,

},

content:{

marginTop:5,

marginBottom:15,

},

textInput:{

paddingLeft:5,

paddingRight:5,

backgroundColor:'white',

height:50,

fontSize:16,

flex:1,

},

})

```


你可能感兴趣的:(react-native react-native-ble-manager 瀹炵幇 灏忕エ鎵撳嵃鍔熻兘)