2.微信小程序实现蓝牙打印(HBuilderX)-初始化服务和特征

初始化服务和特征之前,一定要先扫描获取到设备的DeviceId,为:3A:11:DC:1E:2C:33这种格式。

微信小程序源码:

var qyl = {
    
    toast:function(str){
		wx.showToast({
		    icon: 'none',
		    title: str
		});
    },
    bluetooth:{
		
		stop:function(){
			wx.stopBluetoothDevicesDiscovery({
				success(res) {
					console.log("stop search")
				}
			})
		},
		
		search:function(callback2){
			
			var myOpen  = function(callback){
				wx.openBluetoothAdapter({//首先初始化蓝牙
					success(res) { 
						callback();
					},fail(res) {
						console.log(res)
						if (res.errCode == 10001) { 
							qyl.toast("蓝牙未打开,请先打开蓝牙");
							
						} else {
							qyl.toast(res.errMsg);
						}  
					}  
				});
			}
			
			var myStart = function(callback){
				var list = [];
				wx.getBluetoothDevices({ //找到老设备
				  success(res) {
				   var devices = res.devices;
				   for(var i=0;i<devices.length;i++){
					   list.push(devices[i]);
				   }
				  }
				})
				
				wx.startBluetoothDevicesDiscovery({ //发现新设备
				  success(res) {
					wx.onBluetoothDeviceFound(function(devices){
						var devices = devices.devices;
						for(var i=0;i<devices.length;i++){
							list.push(devices[i]);
						}
					})
				  }
				});
				
				//延迟函数
				var Delayed = function(ms,callback){
					return new Promise(function(Resolve,Peject){
						setTimeout(function(){
							Resolve(callback);
						},ms);
					});
				}
				//9s停止
				Delayed(9000).then( ()=>{
					qyl.bluetooth.stop();
					console.log(JSON.stringify(list));
					callback(list);
				});
				
			}
			
			//执行搜索
			myOpen(function(){
				myStart(callback2)
			})
		},

            init:function(deviceId,callback2){ //根据设备ID获取特征和服务
		
			var myOpen  = function(callback){
				wx.openBluetoothAdapter({//首先初始化蓝牙
					success(res) { 
						console.log(res);
						callback();
					},fail(res) {
						console.log(res)
						if (res.errCode == 10001) { 
							qyl.toast("蓝牙未打开,请先打开蓝牙");
							var os = qyl.get_os();
							if(os=='android'||os=='ios'){
								var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");  
								var BAdapter = BluetoothAdapter.getDefaultAdapter(); //获得本机蓝牙适配器  
								if (!BAdapter.isEnabled()) {  
									console.log('检测到未打开蓝牙,尝试打开中....');  
									BAdapter.enable();  
								}  
							}
						} else {
							qyl.toast(res.errMsg);
						} 
						
					}  
				});
			}
			
			var createBLE = function(callback){
				console.log(deviceId);
				wx.createBLEConnection({
					deviceId: deviceId,
					complete(res2) {
						
						console.log(res2);
						
						if (res2.errCode == 0||res2.errCode==-1) {//已连接
							callback();
						}else if(res2.errCode==10012){
							
						    createBLE(callback);
						}else{
							
							var link = qyl.get_item("zt_link");
							link.deviceId= "";
							link.serviceId = "";
							qyl.set_item("zt_link",link);
							
							qyl.toast("连接蓝牙失败");
							console.log(link);
						}
					}
				});
			}
			
			var getBLE = function(callback){
				
			
				console.log(deviceId);
				wx.getBLEDeviceServices({
					deviceId: deviceId,
					complete(res3) {
						
						console.log("services-------------------");
						console.log(res3);
						var realServiceId = "";
						for(var i=0;i<res3.services.length;i++ ){
							var serviceId = res3.services[i].uuid;
							if(serviceId == "0000FF00-0000-1000-8000-00805F9B34FB"){
								realServiceId = serviceId;
							}else{
								realServiceId = res3.services[0].uuid;
							}
						}
						 console.log('--------------------------------------');
						 console.log('device设备的id:', deviceId);
						 console.log('device设备的服务id:',realServiceId);	
						 setTimeout(function(){
							
							wx.getBLEDeviceCharacteristics({
								deviceId: deviceId,
								serviceId: realServiceId,
								success(res) {
									console.log("characteristics-------------------");
									//console.log(res);
									var list = [];
								
									for (var c = 0; c < res.characteristics.length; c++) {
										
										if (res.characteristics[c].properties.write == true) {
											let uuid = res.characteristics[c].uuid
											console.log(' deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' +uuid)
											var info = {deviceId:deviceId,serviceId:serviceId,characteristicId:uuid};
											
											list.push(info);
											
										}
										
									}
									
									callback(list);
									
								}
							})
							 
						 },2000);	
						
					}
				});
				
			
			}
			
			//execute
			myOpen(function(){ //已打开
				
				createBLE(function(){ //已连接
				
					setTimeout(function(){
						getBLE(callback2); 
					},2000);
	
				})
			})
			
		}
    }
}

//搜索:qyl.bluetooth.search(function(list){  console.log(list)  });
//获取服务和特征: qyl.bluetooth.init(deviceId,function(res){ console.log(res); });

 

HBuilderX源码:

var qyl = {
    
    toast:function(str){
		uni.showToast({
		    icon: 'none',
		    title: str
		});
    },
    bluetooth:{
		
		stop:function(){
			uni.stopBluetoothDevicesDiscovery({
				success(res) {
					console.log("stop search")
				}
			})
		},
		
		search:function(callback2){
			
			var myOpen  = function(callback){
				uni.openBluetoothAdapter({//首先初始化蓝牙
					success(res) { 
						callback();
					},fail(res) {
						console.log(res)
						if (res.errCode == 10001) { 
							qyl.toast("蓝牙未打开,请先打开蓝牙");
							
						} else {
							qyl.toast(res.errMsg);
						}  
					}  
				});
			}
			
			var myStart = function(callback){
				var list = [];
				uni.getBluetoothDevices({ //找到老设备
				  success(res) {
				   var devices = res.devices;
				   for(var i=0;i<devices.length;i++){
					   list.push(devices[i]);
				   }
				  }
				})
				
				uni.startBluetoothDevicesDiscovery({ //发现新设备
				  success(res) {
					uni.onBluetoothDeviceFound(function(devices){
						var devices = devices.devices;
						for(var i=0;i<devices.length;i++){
							list.push(devices[i]);
						}
					})
				  }
				});
				
				//延迟函数
				var Delayed = function(ms,callback){
					return new Promise(function(Resolve,Peject){
						setTimeout(function(){
							Resolve(callback);
						},ms);
					});
				}
				//9s停止
				Delayed(9000).then( ()=>{
					qyl.bluetooth.stop();
					console.log(JSON.stringify(list));
					callback(list);
				});
				
			}
			
			//执行搜索
			myOpen(function(){
				myStart(callback2)
			})
		},

            init:function(deviceId,callback2){ //根据设备ID获取特征和服务
		
			var myOpen  = function(callback){
				uni.openBluetoothAdapter({//首先初始化蓝牙
					success(res) { 
						console.log(res);
						callback();
					},fail(res) {
						console.log(res)
						if (res.errCode == 10001) { 
							qyl.toast("蓝牙未打开,请先打开蓝牙");
							var os = qyl.get_os();
							if(os=='android'||os=='ios'){
								var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");  
								var BAdapter = BluetoothAdapter.getDefaultAdapter(); //获得本机蓝牙适配器  
								if (!BAdapter.isEnabled()) {  
									console.log('检测到未打开蓝牙,尝试打开中....');  
									BAdapter.enable();  
								}  
							}
						} else {
							qyl.toast(res.errMsg);
						} 
						
					}  
				});
			}
			
			var createBLE = function(callback){
				console.log(deviceId);
				uni.createBLEConnection({
					deviceId: deviceId,
					complete(res2) {
						
						console.log(res2);
						
						if (res2.errCode == 0||res2.errCode==-1) {//已连接
							callback();
						}else if(res2.errCode==10012){
							
						    createBLE(callback);
						}else{
							
							var link = qyl.get_item("zt_link");
							link.deviceId= "";
							link.serviceId = "";
							qyl.set_item("zt_link",link);
							
							qyl.toast("连接蓝牙失败");
							console.log(link);
						}
					}
				});
			}
			
			var getBLE = function(callback){
				
			
				console.log(deviceId);
				uni.getBLEDeviceServices({
					deviceId: deviceId,
					complete(res3) {
						
						console.log("services-------------------");
						console.log(res3);
						var realServiceId = "";
						for(var i=0;i<res3.services.length;i++ ){
							var serviceId = res3.services[i].uuid;
							if(serviceId == "0000FF00-0000-1000-8000-00805F9B34FB"){
								realServiceId = serviceId;
							}else{
								realServiceId = res3.services[0].uuid;
							}
						}
						 console.log('--------------------------------------');
						 console.log('device设备的id:', deviceId);
						 console.log('device设备的服务id:',realServiceId);	
						 setTimeout(function(){
							
							uni.getBLEDeviceCharacteristics({
								deviceId: deviceId,
								serviceId: realServiceId,
								success(res) {
									console.log("characteristics-------------------");
									//console.log(res);
									var list = [];
								
									for (var c = 0; c < res.characteristics.length; c++) {
										
										if (res.characteristics[c].properties.write == true) {
											let uuid = res.characteristics[c].uuid
											console.log(' deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' +uuid)
											var info = {deviceId:deviceId,serviceId:serviceId,characteristicId:uuid};
											
											list.push(info);
											
										}
										
									}
									
									callback(list);
									
								}
							})
							 
						 },2000);	
						
					}
				});
				
			
			}
			
			//execute
			myOpen(function(){ //已打开
				
				createBLE(function(){ //已连接
				
					setTimeout(function(){
						getBLE(callback2); 
					},2000);
	
				})
			})
			
		}
    }
}

//搜索:qyl.bluetooth.search(function(list){  console.log(list)  });
//获取服务和特征: qyl.bluetooth.init(deviceId,function(res){ console.log(res); });

运行结果:

感谢您的支持,写的文章如对您有所帮助,开源不易,请您打赏,谢谢啦~

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值