WeX5 3.8开发工具之蓝牙打印(全流程记录不是最全,胜似最全)

技术分享

记录踩过的坑和别的大佬没有叽歪的点

开始做蓝牙打印看到网上很多做混合开发 和安卓开发,ios开发的例子,插件等等版本大同小异,并不是像其他博客上所说的那么简单,[下载插件,无需改动,连接打印开始,图片为证],没那么简单.往往困扰我们没有进行下去的是细节,那么

为了能让小伙伴们少走弯路我来分享一下吧,

这个插件很多 随便下载一个 列表,连接,打印 断连 这四个功能

蓝牙打印插件下载

插件放在  软件 目录 WeX5_V3.8\model\Native\plugins  下 

插件内java文件可以手动修改 根据自己的需要, 有的需要 改写蓝牙连接功能, new一个线程去连接,我这里没有new,连接需要时间, 可能会报错 read failed,socket might closed or timeout,read ret:-1

java

package cordova.plugin.bluetooth.printer;import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Set;
import java.util.UUID;import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;import android.content.Context;public class BluetoothPrinter extends CordovaPlugin {private static final String LOG_TAG = "BluetoothPrinter";BluetoothAdapter mBluetoothAdapter;BluetoothSocket mmSocket;BluetoothDevice mmDevice;OutputStream mmOutputStream;InputStream mmInputStream;Thread workerThread;byte[] readBuffer;int readBufferPosition;int counter;volatile boolean stopWorker;public BluetoothPrinter() {}@Overridepublic boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {if (action.equals("list")) {listBT(callbackContext);////return true;} else if (action.equals("connect")) {String name = args.getString(0);if (findBT(callbackContext, name)) {try {connectBT(callbackContext);} catch (IOException e) {Log.e(LOG_TAG, e.getMessage());e.printStackTrace();}} else {callbackContext.error("Bluetooth Device Not Found: " + name);}return true;} else if (action.equals("disconnect")) {try {disconnectBT(callbackContext);} catch (IOException e) {Log.e(LOG_TAG, e.getMessage());e.printStackTrace();}return true;}else if (action.equals("print")) {try {String msg = args.getString(0);print(callbackContext, msg);} catch (IOException e) {Log.e(LOG_TAG, e.getMessage());e.printStackTrace();}return true;}else if (action.equals("printPOSCommand")) {try {String msg = args.getString(0);printPOSCommand(callbackContext, hexStringToBytes(msg));} catch (IOException e) {Log.e(LOG_TAG, e.getMessage());e.printStackTrace();}return true;}return false;}//This will return the array list of paired bluetooth printersvoid listBT(CallbackContext callbackContext) {BluetoothAdapter mBluetoothAdapter = null;String errMsg = null;try {mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (mBluetoothAdapter == null) {errMsg = "No bluetooth adapter available";Log.e(LOG_TAG, errMsg);callbackContext.error(errMsg);return;}if (!mBluetoothAdapter.isEnabled()) {Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);this.cordova.getActivity().startActivityForResult(enableBluetooth, 0);}Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();if (pairedDevices.size() > 0) {JSONArray json = new JSONArray();for (BluetoothDevice device : pairedDevices) {/*Hashtable map = new Hashtable();map.put("type", device.getType());map.put("address", device.getAddress());map.put("name", device.getName());JSONObject jObj = new JSONObject(map);*/json.put(device.getName());}callbackContext.success(json);} else {callbackContext.error("No Bluetooth Device Found");}//Log.d(LOG_TAG, "Bluetooth Device Found: " + mmDevice.getName());} catch (Exception e) {errMsg = e.getMessage();Log.e(LOG_TAG, errMsg);e.printStackTrace();callbackContext.error(errMsg);}}// This will find a bluetooth printer deviceboolean findBT(CallbackContext callbackContext, String name) {try {mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (mBluetoothAdapter == null) {Log.e(LOG_TAG, "No bluetooth adapter available");}if (!mBluetoothAdapter.isEnabled()) {Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);this.cordova.getActivity().startActivityForResult(enableBluetooth, 0);}Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();if (pairedDevices.size() > 0) {for (BluetoothDevice device : pairedDevices) {if (device.getName().equalsIgnoreCase(name)) {mmDevice = device;return true;}}}Log.d(LOG_TAG, "Bluetooth Device Found: " + mmDevice.getName());} catch (Exception e) {String errMsg = e.getMessage();Log.e(LOG_TAG, errMsg);e.printStackTrace();callbackContext.error(errMsg);}return false;}// Tries to open a connection to the bluetooth printer deviceboolean connectBT(CallbackContext callbackContext) throws IOException {try {// Standard SerialPortService IDUUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);//String cmd="Qsprinter";//PrintService.pl.connect(cmd);mmSocket.connect();mmOutputStream = mmSocket.getOutputStream();mmInputStream = mmSocket.getInputStream();beginListenForData();//Log.d(LOG_TAG, "Bluetooth Opened: " + mmDevice.getName());callbackContext.success("Bluetooth Opened: " + mmDevice.getName());//callbackContext.success("Bluetooth Opened: " + "ceshi_shebei");return true;} catch (Exception e) {String errMsg = e.getMessage();Log.e(LOG_TAG, errMsg);e.printStackTrace();callbackContext.error(errMsg);}return false;}// After opening a connection to bluetooth printer device, // we have to listen and check if a data were sent to be printed.void beginListenForData() {try {final Handler handler = new Handler();// This is the ASCII code for a newline characterfinal byte delimiter = 10;stopWorker = false;readBufferPosition = 0;readBuffer = new byte[1024];workerThread = new Thread(new Runnable() {public void run() {while (!Thread.currentThread().isInterrupted() && !stopWorker) {try {int bytesAvailable = mmInputStream.available();if (bytesAvailable > 0) {byte[] packetBytes = new byte[bytesAvailable];mmInputStream.read(packetBytes);for (int i = 0; i < bytesAvailable; i++) {byte b = packetBytes[i];if (b == delimiter) {byte[] encodedBytes = new byte[readBufferPosition];System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);/*final String data = new String(encodedBytes, "US-ASCII");readBufferPosition = 0;handler.post(new Runnable() {public void run() {myLabel.setText(data);}});*/} else {readBuffer[readBufferPosition++] = b;}}}} catch (IOException ex) {stopWorker = true;}}}});workerThread.start();} catch (NullPointerException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}//This will send data to bluetooth printerboolean print(CallbackContext callbackContext, String msg) throws IOException {try {//mmOutputStream.write(new byte[] { 0x1b, 0x74,0x15 });//后添加//mmOutputStream.write(msg.getBytes());mmOutputStream.write(msg.getBytes("GBK"));//防止中文打印乱码//mmOutputStream.write(new byte[] { 0x1d, 0x0c });//后添加/*String message="20160825888";if (message.length() > 0) {byte[] btdata=null;try {btdata=message.getBytes("ASCII");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}//Enable the barcodemmOutputStream.write(new byte[]{0x1d,0x45,0x43,0x01});//Set the barcode height is 162mmOutputStream.write(new byte[]{0x1d,0x68,(byte) 0xa2});//Set HRI character print location on bottommmOutputStream.write(new byte[]{0x1d,0x48,0x02});mmOutputStream.write(new byte[]{0x1d,0x77,0x02});//Print the barcode use code128byte[] qrHead=new byte[]{0x1d,0x6b,0x49,(byte) btdata.length};
//				byte[] qrHead=new byte[]{0x1d,0x6b,0x44,(byte) btdata.length};byte[] barCodeData=new byte[qrHead.length+btdata.length];System.arraycopy(qrHead, 0, barCodeData, 0, qrHead.length);System.arraycopy(btdata, 0, barCodeData, qrHead.length, btdata.length);mmOutputStream.write(barCodeData);mmOutputStream.write(new byte[] { 0x1d, 0x0c });//mmOutputStream.printText("\r\n");//				Bitmap btMap = BarcodeCreater.creatBarcode(PrintBarCodeActivity.this,
//						message, 384, 100, true, 1);
//				PrintService.pl.printImage(btMap);
//				PrintService.pl.write(new byte[] { 0x1d, 0x0c });}//结束*///mmOutputStream.write(new byte[] { 0x1b, 0x74,0x15 });////mmOutputStream.write(msg.getBytes("UTF-8"));//mmOutputStream.write(new byte[] { 0x1d, 0x0c });///*mmOutputStream.write(new byte[] { 0x1b, 0x74,0x15 });////mmOutputStream.write(msg.getBytes());mmOutputStream.write(msg.getBytes("GBK"));//防止中文打印乱码mmOutputStream.write(new byte[] { 0x1d, 0x0c });//*/// tell the user data were sent//Log.d(LOG_TAG, "Data Sent");callbackContext.success("Data Sent success");return true;} catch (Exception e) {String errMsg = e.getMessage();Log.e(LOG_TAG, errMsg);e.printStackTrace();callbackContext.error(errMsg);}return false;}boolean printPOSCommand(CallbackContext callbackContext, byte[] buffer) throws IOException {try {mmOutputStream.write(buffer);// tell the user data were sentLog.d(LOG_TAG, "Data Sent");callbackContext.success("Data Sent");return true;} catch (Exception e) {String errMsg = e.getMessage();Log.e(LOG_TAG, errMsg);e.printStackTrace();callbackContext.error(errMsg);}return false;}// disconnect bluetooth printer.boolean disconnectBT(CallbackContext callbackContext) throws IOException {try {stopWorker = true;mmOutputStream.close();mmInputStream.close();mmSocket.close();callbackContext.success("Bluetooth Disconnect");return true;} catch (Exception e) {String errMsg = e.getMessage();Log.e(LOG_TAG, errMsg);e.printStackTrace();callbackContext.error(errMsg);}return false;}public byte[] getText(String textStr) {// TODO Auto-generated method stubbyte[] send;byte[] send=null;try {send = textStr.getBytes("GBK");} catch (UnsupportedEncodingException e) {send = textStr.getBytes();}return send;}public static byte[] hexStringToBytes(String hexString) {hexString = hexString.toLowerCase();String[] hexStrings = hexString.split(" ");byte[] bytes = new byte[hexStrings.length];for (int i = 0; i < hexStrings.length; i++) {char[] hexChars = hexStrings[i].toCharArray();bytes[i] = (byte) (charToByte(hexChars[0]) << 4 | charToByte(hexChars[1]));}return bytes;}private static byte charToByte(char c) {return (byte) "0123456789abcdef".indexOf(c);}}

js

var exec = require('cordova/exec');var BTPrinter = {list: function(fnSuccess, fnError){exec(fnSuccess, fnError, "BluetoothPrinter", "list", []);},connect: function(fnSuccess, fnError, name){exec(fnSuccess, fnError, "BluetoothPrinter", "connect", [name]);},disconnect: function(fnSuccess, fnError){exec(fnSuccess, fnError, "BluetoothPrinter", "disconnect", []);},print: function(fnSuccess, fnError, str){exec(fnSuccess, fnError, "BluetoothPrinter", "print", [str]);},printPOSCommand: function(fnSuccess, fnError, str){exec(fnSuccess, fnError, "BluetoothPrinter", "printPOSCommand", [str]);}
};module.exports = BTPrinter;

示例下载

示例下载

//蓝牙打印Model.prototype.btClick = function(event){debugger;var strCmd1 = "T 12 2 0 10 12号字体测试\n";//文本var strCmd2 = addCPCLQRCode(0,40,'M', 2, 5, "12号中文字二维码测试");//二维码			var strCmd3 = addCPCLBarCode(150,10,'128',50,0,1,1,'123456');//条形码var strCmd4 = "T 12 2 180 70 123456\n";//文本var byte2 = "! 0 200 200 300 1\n" //这是开始代码+strCmd1+strCmd2+strCmd3+strCmd4+"PRINT\n";//这是结束代码//蓝牙打印if( this.blueConect) {var packageID = this.packageID;BTPrinter.print ( function (data){console.log ( "success" ) ;console.log (packageID) ;alert (data) ;},function(err){console.log ( "Error") ;console.log (err);alert (err) ;}, byte2);}};

 

 

 

 

 

最后说几个问题

图一

 连接蓝牙之前需要用手机的蓝牙模块先连接蓝牙打印机  点击蓝牙列表>> 蓝牙连接(3秒左右会连接成功)>>打印

2

用手机连接蓝牙时也是我被坑的地方这个手没有出现 ble_name,但是不影响我阐述, 看图4图5 打印机有两个蓝牙信号 一个name[打印机信号名] 一个ble_name[打印机蓝牙信号名]

咱不知道为啥要两个 看图标一个是蓝牙标识,一个是打印机标识 两个名字只差一个L字母 开始我连接的是 带L的信号(蓝牙信号),不用配对密码可以直接连接,打印机也会显示连接成功的信号,

所以没在意一直以为是程序问题 功能上只有列表可以用,连接 打印都无法使用,就是因为当初输了1234没成功所以固执的认为这个是给配对用的参考,就没有输入0000,

其实0000才是配对密码,打印不需要输入配对是默认的,只要在手机一方输入即可配对成功,后来才知道要用带打印机图标的信号,程序没有问题,是信号选择的问题.每一个细节都肯能困扰你打印失败,让你排错的方向走叉

3

 

4
图5

 

总结一下,1插件名错误,

2,修改插件要重新编译打包

3.cordova 基本插件引入

4.测试最好单开app 减少干扰项,后期排错方便

5.打印机说明书

6.打印机信号都试试

7.UI2 打包 网络 网速影响app

8.打印纸安装

9.打印距离

10.手机版本4.2以上.

11.蓝牙打印机蓝牙低功耗4.0以上

记着的就这么多,有问题的可以留言,其实功能很简单无非是一些细节没有控制好,知道了就简单的一逼

祝你们好运

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/553288.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

扫一扫闪退的可能性之一[wex5开发]

这两个插件不可以同时存在 因为这一句插件的引入导致整个项目搜索了一下午,什么活都没干 蓝牙打印时 一般会有扫码的功能 并用 所以..... require("cordova!com.justep.cordova.plugin.barcodescanner");//require("cordova!phonegap-plugin-barcodescanner&…

jeecg 查看 页面 父子表 横向滚动条效果 官方被禁用

关键代码注释替换 if (tabs) {//增加width属性&#xff0c;fit属性之前写死&#xff0c;改为由页面设定&#xff0c;不填默认truesb.append("<div id\"" id "\" tabPosition\"" tabPosition "\" borderflase style\"…

JEECG 缓存用法

1 .配置文件 ehcache.xml 添加 2.Controller 手动更新接口数据 启动执行接口 声明接口 实现接口

JeeCG - <t:choose/> 标签用法 输入框控件 查询输入

页面 <td class"value"><!-- <input id"mateCode" name"mateCode" type"text" maxlength"32" style"width: 150px" class"inputxt" datatype"*" ignore"checked" /&…

关于js函数未定义not defined引发的感想

越是简单的问题往往越会被忽略,很多时候我们的代码都是copy , 粘贴的时候未修改对应函数名称,有时修改的大小写都导致我们犯错,一次一次的核对,自我感觉没有问题 现在的编程变得简便,牛逼的开发人员手上,可用的代码块宝典不尽其数,复制就显得尤为重要,一段可克隆的代码,在你我…

ORA-06550 PLS-00172 字符串太长 超过3W 处理方式

问题 描述 帖子 通过sql插入clob数据(数据库对应字段类型为clob), 在执行insert语句时(待插入的字符串有2W多), 总是报错如下: 不是说clob支持4G大小么? 有些资料说是sql本身的长度不能超过4000字符串? 但是类似博客类型的内容字段, 不是很正常就成千上W么 以下是问题补充&…

JEECG datagrid 页面刷新reloadTable

reloadTable 方法在进入页面执行函数触发刷新 多余10条分页状态是刷新失效,执行删除操作后刷新恢复有效, 故 使用datagrid("reload") 方法刷新 比较靠谱 reloadTable();$(#dbPassBoxList).datagrid(reload);//刷新 需要这两句联用 页面才会刷新

NC 633 BP类集锦 根据包名定位modules文件夹

ic 调拨出入 4Y 4E 采购入库 45 其他出入库 4I(4i) 4A 销售出库 4C so 销售订单 30 销售发货 4331 pu 采购订单 21 其他出入库 插入触发BP类路径 nc.impl.ic.m4i.action.InsertAction

vue+播放rtsp流视频监控

vue播放rtsp流视频监控-海康摄像头使用工具vuejsencryptjsWebControl思路解决办法1:弹出新页面vue代码解决办法2:采用组建的方式使用工具vuejsencryptjsWebControl 注:使用海康demo,下载地址:https://open.hikvision.com/download/5c67f20bb254d61550c2f63e?type10 需要注册&…

浏览器播放rtmp

rtmp播放 文章目录rtmp播放1、rtmp测试路径地址2、video.js播放rtmp3、ezuikit播放rtmp1、rtmp测试路径地址 https://www.cnblogs.com/yeminglong/p/14704789.html 2、video.js播放rtmp 注意&#xff1a; 1.如果写在html本地运行&#xff0c;请使用http-server启动&#xff…

网页打开微信公众号关注界面

代码 <a href"https://mp.weixin.qq.com/mp/profile_ext?actionhome&__biz微信公众号biz号码&scene110#wechat_redirect">进入公众号</a>例如&#xff1a;<a href"https://mp.weixin.qq.com/mp/profile_ext?actionhome&__bizMjgz…

海康、大华网络摄像机RTSP URL格式组成及参数配置

经常有开发者咨询我们关于海康、大华网络摄像机RTSP url拼接规则和相关参数配置&#xff0c;虽然很简单&#xff0c;考虑到资料不全&#xff0c;写个博客记录下&#xff1a; 1. 海康摄像机&#xff1a; 在IE浏览器输入网络摄像机的IP地址&#xff0c;输入配置的用户名、密码&…

直播系统中使用SEI传输用户自定义数据方案讨论

在直播系统中&#xff0c;除了直播音视频之外&#xff0c;有时候还想从主播端发布文本信息等&#xff0c;这些信息可以不通过视频传输通道发送给用户播放端&#xff0c;但如果传输的数据想和视频保持精准同步&#xff0c;那最好的办法就是这些信息和视频数据打包在一起传输, 通…

安卓端/iOS端如何播放4K分辨率的RTMP/RTSP流

关于4K分辨率 4K分辨率即40962160的像素分辨率&#xff0c;它是2K投影机和高清电视分辨率的4倍&#xff0c;属于超高清分辨率。在此分辨率下&#xff0c;观众将可以看清画面中的每一个细节&#xff0c;每一个特写。影院如果采用惊人的40962160像素&#xff0c;无论在影院的哪个…

干货:如何实现RTSP推送H.264、RTSP推送H.265(hevc)

rtsp推送相关的资料和测试软件比较少&#xff0c;本文介绍rtsp推送相关信令和测试效果&#xff1a; 1. rtsp推送流程. 主要分两部分&#xff1a;第一部分先发送信令&#xff1b;第二部分发送rtp包。 信令流程: 1.1 先发送OPTIONS, OPTIONS比较常用&#xff0c;就不做详细说明…

如何支持RTSP播放H.265(HEVC)流

随着H.265的普及&#xff0c;越来越多的开发者希望大牛直播SDK能支持低延迟的RTSP H.265播放&#xff0c;并分享相关经验&#xff1a; 实现思路&#xff1a; 对rtsp来说&#xff0c;要播放h265只要正确解析sdp和rtp包即可. 下面对这些相关内容做一些介绍. 1. H265 Nal Unit …

直播协议的选择:RTMP vs. HLS

前言 随着直播业务的兴起&#xff0c;越来越多的直播平台开始涌现&#xff0c;这火热的程度好像一个应用不带上直播业务出来都不好意思跟人打招呼。想要做一个直播业务&#xff0c;主要包括三个部分&#xff1a;采集推流端、流媒体服务端、播放端。这里不多说&#xff0c;就主…

Flutter下实现低延迟的跨平台RTSP/RTMP播放

为什么要用Flutter&#xff1f; Flutter是谷歌的移动UI框架&#xff0c;可以快速在iOS和Android上构建高质量的原生用户界面。 Flutter可以与现有的代码一起工作。在全世界&#xff0c;Flutter正在被越来越多的开发者和组织使用&#xff0c;并且Flutter是完全免费、开源的。 …

如何推送和播放RTMP H265流 (RTMP HEVC)

rtmp 播放h265 首先要扩展flv协议&#xff0c;国内常用扩展方式是给flv的videotag.codecid增加一个新类型(12)来表示h265(hevc),其他和h264规则差不多&#xff0c;另外和h264不同的地方是要解析HEVCDecoderConfigurationRecord&#xff0c;从HEVCDecoderConfigurationRecord中解…

5张图看懂如何实现Windows RTMP实时导播功能

一直以来&#xff0c;好多开发者苦于如何实现RTMP导播数据源实时切换&#xff0c;以下是大牛直播SDK导播切换说明&#xff0c;支持只切换数据源模式&#xff0c;或音视频混音合成输出模式&#xff1a; 数据源&#xff1a; 1. rtmp/rtsp音视频流&#xff1b; 2. 本地屏幕/摄像…