## 用到的工具:
react-native
react-native-ble-manager
iconv-lite
buffer
## 安装
npm install react-native-ble-manager
npm install buffer
npm install iconv-lite
新建 Ecs.js 文件,贴代码
```
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",//正常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、Read、Write、WriteWithoutResponse的serviceUUID和characteristicUUID
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;//当前蓝牙正在连接中
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;
//为undefined代表此蓝牙广播信息里不包括Mac地址
if(!macAddressInAdvertising){
return;
}
macAddressInAdvertising =macAddressInAdvertising.replace("<","").replace(">","").replace(" ","");
if(macAddressInAdvertising !=undefined &&macAddressInAdvertising !=null &&macAddressInAdvertising !='') {
macAddressInAdvertising =this.swapEndianWithColon(macAddressInAdvertising);
}
return macAddressInAdvertising;
}
/**
* ios从广播中获取的mac地址进行大小端格式互换,并加上冒号:
* @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";
//确保全局只有一个BleManager实例,BleModule类保存着蓝牙的连接信息
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连接时不需要用到Mac地址,但跨平台识别同一设备时需要Mac地址
//如果广播携带有Mac地址,ios可通过广播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();//断开连接后清空UUID
this.setState({
data:newData,
isConnected:false,
writeData:'',
readData:'',
receiveData:'',
text:'',
});
}
//接收到新数据
handleUpdateValue=(data)=>{
//ios接收到的是小写的16进制,android接收的是大写的16进制,统一转化为大写16进制
let value = data.value.toUpperCase();
this.bluetoothReceiveData.push(value);
console.log('BluetoothUpdateValue',value);
this.setState({receiveData:this.bluetoothReceiveData.join('')})
}
connect(item){
//当前蓝牙正在连接时不能打开另一个连接进程
if(BluetoothManager.isConnecting){
console.log('当前蓝牙正在连接时不能打开另一个连接进程');
return;
}
if(this.state.scaning){//当前正在扫描中,连接时关闭扫描
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){//当前正在扫描中
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('正定新区许翠蔬菜店');
ESC.printAndNewLine();
ESC.text('采购订货单');
ESC.printAndNewLine();
ESC.printAndNewLine();
ESC.init();
ESC.text('下单时间:2016-09-06 19:30:23');
ESC.printAndNewLine();
ESC.text('单据编号:T2345-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?'正在搜索中':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,
},
})
```