Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ble.write() doesn't print or show any error (Android) #1017

Open
shayan-izadi opened this issue Jun 17, 2024 · 3 comments
Open

ble.write() doesn't print or show any error (Android) #1017

shayan-izadi opened this issue Jun 17, 2024 · 3 comments

Comments

@shayan-izadi
Copy link

shayan-izadi commented Jun 17, 2024

Hello. I have an Apache Cordova app and I want to print receipts with this plugin. I use the code below but it does not print data and does not show any error or response. I am really confused and the task is very vital for me. I would appreciate any suggestion or help:)

Here is my test print code (the first 3 variables are correct and I get it automatically from the device.I added as a const here from my printer here to make it easier for you to check):

var BT_device=57:4C:54:03:1D:0D;
var BT_service_id=18f0;
var BT_characteristic_id=2af1;

BT_test_template = function() {
	var data = [];	
	
	var $_line = BT_line(42);	
	
	data = [	   
	   //{"type":"command","value":HW_INIT},
	  {"type":"command","value":TXT_BOLD_ON}, 
	  {"type":"command","value":TXT_ALIGN_RT},
	  {"type":"text","value":"Test receipt"},
	  {"type":"command","value":TXT_BOLD_OFF},	  
	  {"type":"command","value":CTL_LF},
	  {"type":"command","value":CTL_LF},	 
	  {"type":"command","value":TXT_ALIGN_LT},
	  {"type":"command","value":TXT_FONT_B},
	  {"type":"text","value": $_line },
	  {"type":"command","value":CTL_LF},
	  //{"type":"command","value":TXT_NORMAL},
	  {"type":"text","value": "Cheese burger" },
	  {"type":"command","value":CTL_LF},
	  {"type":"text","value": "1 x 2.00" },
	  {"type":"command","value":CTL_LF},
	  //{"type":"command","value":TXT_FONT_B},
	  {"type":"text","value": $_line },
	  {"type":"command","value":CTL_LF},	  
	  {"type":"command","value":TXT_NORMAL},
	  {"type":"command","value":TXT_BOLD_ON}, 
	  {"type":"text","value": "TOTAL" },	  
	  {"type":"command","value":TXT_BOLD_OFF},
	  {"type":"command","value":CTL_LF},
	  {"type":"command","value":TXT_NORMAL},
	  {"type":"text","value": "Cash" },
	  {"type":"command","value":CTL_LF},
	  {"type":"command","value":CTL_LF}	  
	];
	return data;
};

BT_print_test = function(){
	
	try {
	
		current_page_id = getCurrentPage();
		BT_device = $("#" + current_page_id +  " .mac_address").val();
		BT_service_id = $("#" + current_page_id +  " .data1").val();
		BT_characteristic_id = $("#" + current_page_id +  " .data2").val();
		
		BT_tpl = '';
		
		if( !empty(BT_device) && !empty(BT_service_id) && !empty(BT_characteristic_id) ){
			BT_tpl = BT_test_template();				
			checkBluetooth('BT_init_print');
		} else {
			showToast( t("No selected printer. please restart your printer"), 'danger' );
		}
	
	} catch(err) {
		dump2( err.message );
	}
};

checkBluetooth = function( $actions ){
	
	if( isdebug() ){	
		BT_actions( $actions ) ;	
		return ;
	}
	
	//printer_add
	
	
	/*ANDROID*/
		cordova.plugins.diagnostic.hasBluetoothSupport(function(available){
		    if(available){
		    	cordova.plugins.diagnostic.isBluetoothEnabled(function(enabled){
				    if(enabled){
				    	// bluetooth is already enabled				    	
				    	BT_actions( $actions ) ;
				    } else {
				    	ble.enable(function(){
				    		 //dump3("Bluetooth enabled");
				    		 setTimeout(function(){			
				    		    BT_actions( $actions ) ;
				    		 }, 1*500 );
				    	}, function(){
				    		checkBluetooth('');
				    	});
				    }
				}, function(error){
				    showToast( t("The following error occurred:")  + " " + error , 'danger'  );
				});
		    } else {
		    	showToast( t("Bluetooth not available on this device") , 'danger' );
		    }
		}, function(error){	    
		    showToast( t("The following error occurred:")  + " " + error  , 'danger' );
		});
	
};

BT_actions = function( $run_funtions ){
	if( !empty($run_funtions) ){	 
	 	switch ($run_funtions){
	 		case "BT_init_print":
	 		  setTimeout(function(){	
	 		     BT_init_print();
	 		  }, 1*500 );
	 		break;
	 		
	 		case "BT_startScan":
	 		   setTimeout(function(){		 		   	
	 		     BT_startScan();
	 		  }, 1*500 );
	 		break;
	 	}
	 }
};

BT_init_print = function(){
	showDialog(true,'printer_loader');

	BT_print_done = false;
	BT_command_count = 0;
	BT_connect_data = false;
	
	/*DEBUG*/
	if( isdebug() ){
				
		setTimeout(function(){	
		   BT_set_status( t("Connecting")+ "..." );
		}, 1*500 );
				
		BT_connect( BT_device );	    
		
		BT_connect_status = setInterval(function(){
			if(BT_connect_data){
				BT_set_status( t("Printing") + "..." );
				$result = BT_connect_data;
		   	    dump($result);
		   	    BT_connect_data = false;
		   	    
		   	    BT_service_id = $result.service;
			    BT_characteristic_id = $result.characteristic;
			    BT_print( BT_tpl );
			  			    
			    //BT_cron = setInterval(BT_cron_print, 1*1000);		   	    
			}
		}, 1*1000 );
		
		return ;
	}
	/*END DEBUG*/
	
	
	ble.isConnected( BT_device , function(){
		//success		
				
		setTimeout(function(){	
		   BT_set_status( t("Printing")+ "..." );
		}, 1*500 );
		
		BT_print( BT_tpl );	
		//BT_cron = setInterval( BT_cron_print , 1*1000);
		
	}, function(){
		
		//failed		
		setTimeout(function(){	
		   BT_set_status( t("Connecting")+ "..." );
		}, 1*500 );
		
		BT_connect_data = false;
		BT_connect( BT_device );	    
		
		BT_connect_status = setInterval(function(){
			if(BT_connect_data){
				BT_set_status( t("Printing") + "..." );
				$result = BT_connect_data;
		   	    dump($result);
		   	    BT_connect_data = false;
		   	    
		   	    BT_service_id = $result.service;
			    BT_characteristic_id = $result.characteristic;
			    BT_print( BT_tpl );
			  
			    //BT_cron = setInterval( BT_cron_print , 1*1000);		   	    
			}
		}, 2*1000 );
    		
	});	
	
};

BT_set_status = function(message){
	$("#printer_loader h3").html( message );
};

BT_print = function(data){
	dump("BT_print");
	dump(data);
	
	BT_err_msg  = '';
	
	if(data.length>0){
		$.each( data  , function( data, val ) {			
			setTimeout(function(){	
				dump(val);
				switch (val.type){
					case "command":
					  BT_command(val.value);
					break
					
					case "text":
					  BT_text(val.value);
					break
					
					case "image":
					  BT_image(val.value);
					 break;
				}
			}, 1*1000); 
		});					
		
		/*setTimeout(function(){
			BT_print_done = true;        	
        }, 5*1000); */
		
		BT_cron = setInterval( BT_cron_print , 1*1000);
		
	} else {
		BT_print_done = true;
		BT_err_msg = t("No data to print");
		//showToast( t("No data to print"), 'danger' );		
	}
};

BT_cron_print = function(){
	
	try {		
		
		 if( isdebug() ){
		 	 $time_out = 15*1000;
		 } else {
			 $time_out = 15*1000;
			 if(cordova.platformId === "ios"){
		     	$time_out = 4*1000;	     	
		     } 	
		 }
		
		BT_print_timeout = setTimeout(function(){	   
			//dump3("BT_print_timeout");
			BT_command_count = 0;
			/*$dialog = document.getElementById("printer_loader");   
			if($dialog){
				$dialog.hide();
			}*/
			showDialog(false,'printer_loader');
	        clearInterval(BT_cron);	
		}, $time_out );
		
		/*dump3("BT_command_count=>" + BT_command_count);
		dump3("BT_tpl=>" + BT_tpl.length);*/
		
		$tpl_count = BT_tpl.length;	
		if( isNaN($tpl_count)){
			BT_print_done = true;
		}
		
		if( BT_command_count >=  BT_tpl.length ){
			BT_print_done = true;
		}
		
		//dump3("BT_cron_print =>"+ BT_print_done);
		
		if(BT_print_done){		
			BT_command_count = 0;
			if(!empty(BT_err_msg)){
	        	showToast( BT_err_msg , 'danger' );	        	    
	        } 		
	        /*$dialog = document.getElementById("printer_loader");   
			if($dialog){
				$dialog.hide();
			}*/
	        showDialog(false,'printer_loader');
	        clearInterval(BT_cron);
	        clearTimeout(BT_print_timeout);
		}		
		
	
	} catch(err) {
		dump2( err.message );
	}
};


BT_text = function($text){		
	try {		
		var data = stringToBytes($text);
		ble.write( BT_device , BT_service_id , BT_characteristic_id , data, function(result){
	    	//dump3(result);
	    	BT_command_count++;
	    }, function(err){		  
	    	BT_command_count++;  
		    if ((typeof  err.errorMessage !== "undefined") && ( err.errorMessage !== null)) {
		       BT_err_msg+= err.errorMessage;
		       BT_err_msg+="\n";
		    } else {
		       BT_err_msg+= JSON.stringify(err);
		       BT_err_msg+="\n";
		    }
	    });	   	    
    } catch(err) {    
      BT_command_count++;	  
      BT_err_msg+= err.message; 
      BT_err_msg+="\n";
    } 
};

BT_command = function( $command ){		
	try {							
		
		data = new Uint8Array( $command.length );				
		$.each( $command  , function( key, val ) {		
			data[key]=val;
		});
						
	    ble.write( BT_device , BT_service_id , BT_characteristic_id , data.buffer, function(result){
	    	//dump3(result);
	    	BT_command_count++;
	    }, function(err){
	    	BT_command_count++;
		    if ((typeof  err.errorMessage !== "undefined") && ( err.errorMessage !== null)) {
		       BT_err_msg+= err.errorMessage; 
		       BT_err_msg+="\n";
		    } else {
		       BT_err_msg+= JSON.stringify(err); 
		       BT_err_msg+="\n";
		    }
	    });	 

    } catch(err) {
       BT_command_count++;
       BT_err_msg+= err.message; 
       BT_err_msg+="\n";
    }        
};
@peitschie
Copy link
Collaborator

Hi @shayan-izadi

You haven't got any code here showing how the scan or connect is working.
Am I correct in presuming you are able to successfully connect to the printer?

@shayan-izadi
Copy link
Author

shayan-izadi commented Jun 18, 2024

Hi @shayan-izadi

You haven't got any code here showing how the scan or connect is working. Am I correct in presuming you are able to successfully connect to the printer?

@peitschie Hi. That's right I don't have any problem for scanning and connecting to Bluetooth printers and I can connect to printers successfully. Only problem
is when I want to test the printer with this code it shows "Printing..." status and do nothing at the end. Neither printing nor showing any error.
This is just a part of my code that is related to printing function.

@peitschie
Copy link
Collaborator

There's nothing obviously wrong there in the BLE code @shayan-izadi

But... it's fairly complex code, with a lot of setInterval and setTimeouts going on, which makes it extremely difficult to tell if what you're chaining together there functions properly.

I'd highly recommend coming up with the simplest case possible, and seeing if you have more luck there.
Generally speaking, the flow boils down to something like:

const BT_device=57:4C:54:03:1D:0D;
const BT_service_id=18f0;
const BT_characteristic_id=2af1;

/* async/await is available in typescript, and makes life a lot easier */
async function onConnect() {
  const payload1 = new TextEncoder().encode("some value");
  await ble.withPromises.write(BT_device, BT_service, BT_characteristic, payload.buffer);

  const payload2 = new TextEncoder().encode("some value");
  await ble.withPromises.write(BT_device, BT_service, BT_characteristic, payload2.buffer);
 
  ....
}

ble.connect(BT_device, onConnect, console.error);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants