public class PrintingService : IPrintingService, IDiscoveryHandler, IBluetoothDiscoverer, IDisposable { private static IConnection _connection; public IConnection GetConnection(me.ATDiscoveredPrinter atPrinter) { try { if (String.IsNullOrEmpty(atPrinter.Adress) || atPrinter.Adress == "BT:") return null; if (_connection == null) _connection = ConnectionBuilder.Current.Build(atPrinter.Adress); if (_connection.IsConnected) return _connection; _connection.Open(); return _connection; } catch (Exception ex) { PopupEvent.FireEvent(new EventArgs(), new me.PopupEntity { ViewType = me.ViewType.Alert, Status = me.PopupStatus.Failure, Description = String.Format("Fehler. {0}", ex.Message) }); return null; } } //public void PrintTCP() //{ // IConnection connection = ConnectionBuilder.Current.Build("TCP:192.168.1.100:9100"); // Print(connection); //} //public void PrintBluetooth() //{ // IConnection connection = ConnectionBuilder.Current.Build("BT:00:22:33:44:55:66"); // Print(connection); //} public void PrintBarcode(me.Barcode barcode, me.ATDiscoveredPrinter atPrinter) { if (String.IsNullOrWhiteSpace(atPrinter.Adress)) return; string text = null; switch (barcode.ATBarcodeFormat) { case me.ATBarcodeFormat.CODE_128: //resultPath = PrintingBarcodeHelper.ToImage(barcode.BarcodeNumber, barcode.Height); //^XA //^ FO100,100 ^ BY3 // ^ BCN,100,Y,N,N // ^ FD123456 ^ FS // ^ XZ //^FO200,130 text = @"^XA ^POI^PW1000^LL500 ^FO150,100 ^A0N,60,60 ^BCN,150,Y,N,A ^FD" + barcode.BarcodeNumber + "^FS^XZ\r\n"; break; case me.ATBarcodeFormat.QR_CODE: text = "^XA^FO100,100^BQN,2,10^FD" + barcode.BarcodeNumber + "^FS^XZ\r\n"; //resultPath = PrintingBarcodeHelper.ToImageQR(barcode.BarcodeNumber, barcode.Height); break; case me.ATBarcodeFormat.AZTEC: case me.ATBarcodeFormat.CODABAR: case me.ATBarcodeFormat.CODE_39: case me.ATBarcodeFormat.CODE_93: case me.ATBarcodeFormat.DATA_MATRIX: case me.ATBarcodeFormat.EAN_8: case me.ATBarcodeFormat.EAN_13: case me.ATBarcodeFormat.ITF: case me.ATBarcodeFormat.MAXICODE: case me.ATBarcodeFormat.PDF_417: case me.ATBarcodeFormat.RSS_14: case me.ATBarcodeFormat.RSS_EXPANDED: case me.ATBarcodeFormat.UPC_A: case me.ATBarcodeFormat.UPC_E: case me.ATBarcodeFormat.All_1D: case me.ATBarcodeFormat.UPC_EAN_EXTENSION: case me.ATBarcodeFormat.MSI: case me.ATBarcodeFormat.PLESSEY: case me.ATBarcodeFormat.IMB: default: PopupEvent.FireEvent(new EventArgs(), new me.PopupEntity { ViewType = me.ViewType.Alert, Status = me.PopupStatus.Failure, Description = String.Format("Fehler. {0}", "Barcodetyp wird derzeit nicht unterstützt") }); break; } Task.Factory.StartNew(() => { try { //IConnection _connection = ConnectionBuilder.Current.Build(atPrinter.Adress); try { //_connection.Open(); IConnection _connection = GetConnection(atPrinter); if (_connection == null) return; IZebraPrinter printer = ZebraPrinterFactory.Current.GetInstance(_connection); if ((!CheckPrinterLanguage(_connection)) || (!PreCheckPrinterStatus(printer))) { return; } if (_connection.IsConnected) _connection.Write(GetBytes(text)); PostPrintCheckStatus(printer); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception:" + e.Message); PopupEvent.FireEvent(new EventArgs(), new me.PopupEntity { ViewType = me.ViewType.Alert, Status = me.PopupStatus.Failure, Description = String.Format("Fehler. {0} ", e.Message) }); } finally { if (_connection?.IsConnected ?? false) _connection?.Close(); } } catch (Exception ex) { PopupEvent.FireEvent(new EventArgs(), new me.PopupEntity { ViewType = me.ViewType.Alert, Status = me.PopupStatus.Failure, Description = String.Format("Fehler. {0}", ex.Message) }); } }); } public void StartPrinterDiscovery() { try { IDiscoveryEventHandler handler = DiscoveryHandlerFactory.Current.GetInstance(); handler.OnDiscoveryError += Handler_OnDiscoveryError; handler.OnDiscoveryFinished += Handler_OnDiscoveryFinished; handler.OnFoundPrinter += Handler_OnFoundPrinter; BluetoothDiscoverer.Current.FindPrinters(Android.App.Application.Context, handler); } catch { } //For Android //BluetoothDiscoverer.Current.FindPrinters(MainActivity.Context, handler); //For iOS //BluetoothDiscoverer.Current.FindPrinters(null, handler); //new Task(new Action(() => { // //NetworkDiscoverer.Current.FindPrinters(this); // //NetworkDiscoverer.Current.LocalBroadcast(this); // BluetoothDiscoverer.Current.FindPrinters(Android.App.Application.Context, handler); //})).Start(); } private void Handler_OnFoundPrinter(IDiscoveryHandler handler, IDiscoveredPrinter discoveredPrinter) { System.Diagnostics.Debug.WriteLine($"Found printer: {discoveredPrinter.ToString()}"); Device.BeginInvokeOnMainThread(() => { PrinterFoundEvent.FireEvent(new EventArgs(), new me.ATDiscoveredPrinter { Adress = discoveredPrinter.Address, IsConnected = DiscoveredPrinter.Connection.IsConnected }); }); } private void Handler_OnDiscoveryFinished(IDiscoveryHandler handler) { Device.BeginInvokeOnMainThread(() => { PrinterFoundEvent.FireEvent(new EventArgs(), new me.ATDiscoveredPrinter { Adress = "kein Drucker" }); }); } private void Handler_OnDiscoveryError(IDiscoveryHandler handler, string message) { Device.BeginInvokeOnMainThread(() => { PrinterFoundEvent.FireEvent(new EventArgs(), new me.ATDiscoveredPrinter { Adress = "kein Drucker" }); // System.Diagnostics.Debug.WriteLine($"Error discovering {Enum.GetName(typeof(ConnectionType), connectionType)} printers: {message}"); PopupEvent.FireEvent(new EventArgs(), new me.PopupEntity { ViewType = me.ViewType.Alert, Status = me.PopupStatus.Failure, Description = String.Format("Fehler. {0}", message) }); }); } private void StartBluetoothDiscovery() { //IDiscoveryEventHandler bthandler = DiscoveryHandlerFactory.Current.GetInstance(); //bthandler.OnDiscoveryError += DiscoveryHandler_OnDiscoveryError; //bthandler.OnDiscoveryFinished += DiscoveryHandler_OnDiscoveryFinished; //bthandler.OnFoundPrinter += DiscoveryHandler_OnFoundPrinter; //var connetionType = ConnectionType.BluetoothSsi; //System.Diagnostics.Debug.WriteLine("Starting Bluetooth Discovery"); //DependencyService.Get().FindBluetoothPrinters(bthandler); } public void DiscoveryError(string message) { Device.BeginInvokeOnMainThread(() => { PrinterFoundEvent.FireEvent(new EventArgs(), new me.ATDiscoveredPrinter { Adress = "kein Drucker" }); // System.Diagnostics.Debug.WriteLine($"Error discovering {Enum.GetName(typeof(ConnectionType), connectionType)} printers: {message}"); PopupEvent.FireEvent(new EventArgs(), new me.PopupEntity { ViewType = me.ViewType.Alert, Status = me.PopupStatus.Failure, Description = String.Format("Fehler. {0}", message) }); }); } public void DiscoveryFinished() { Device.BeginInvokeOnMainThread(() => { PrinterFoundEvent.FireEvent(new EventArgs(), new me.ATDiscoveredPrinter { Adress = "kein Drucker" }); }); } public void FoundPrinter(IDiscoveredPrinter discoveredPrinter) { System.Diagnostics.Debug.WriteLine($"Found printer: {discoveredPrinter.ToString()}"); Device.BeginInvokeOnMainThread(() => { PrinterFoundEvent.FireEvent(new EventArgs(), new me.ATDiscoveredPrinter { Adress = discoveredPrinter.Address, IsConnected = DiscoveredPrinter.Connection.IsConnected }); }); } public void Print(me.CheckItem item) { } public IDiscoveredPrinter _discoveredPrinter; public IDiscoveredPrinter DiscoveredPrinter { get { return _discoveredPrinter; } set { _discoveredPrinter = value; } } public byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length]; bytes = Encoding.UTF8.GetBytes(str); return bytes; } public bool PostPrintCheckStatus(IZebraPrinter printer) { if (printer == null) return false; // Check the status again to verify print happened successfully IPrinterStatus status = printer.CurrentStatus; // Wait while the printer is printing while ((status.NumberOfFormatsInReceiveBuffer > 0) && (status.IsReadyToPrint)) { status = printer.CurrentStatus; } // verify the print didn't have errors like running out of paper if (!status.IsReadyToPrint) { //ShowErrorAlert("Error durring print. Printer is " + status.Status); PopupEvent.FireEvent(new EventArgs(), new me.PopupEntity { ViewType = me.ViewType.Alert, Status = me.PopupStatus.Failure, Description = String.Format("Fehler beim Drucken. Drucker ist {0}", status.Status) }); return false; } return true; } public bool PreCheckPrinterStatus(IZebraPrinter printer) { if (printer == null) return false; // Check the printer status IPrinterStatus status = printer.CurrentStatus; if (!status.IsReadyToPrint) { //ShowErrorAlert("Unable to print. Printer is " + status.Status); PopupEvent.FireEvent(new EventArgs(), new me.PopupEntity { ViewType = me.ViewType.Alert, Status = me.PopupStatus.Failure, Description = String.Format("Drucken nicht möglich. Drucker ist {0}", status.Status) }); return false; } return true; } public bool CheckPrinterLanguage(IConnection connection) { try { if (connection == null) return false; if (!connection.IsConnected) connection.Open(); // Check the current printer language byte[] response = connection.SendAndWaitForResponse(GetBytes("! U1 getvar \"device.languages\"\r\n"), 500, 100); string language = Encoding.UTF8.GetString(response, 0, response.Length); if (language.Contains("line_print")) { //ShowAlert("Switching printer to ZPL Control Language.", "Notification"); PopupEvent.FireEvent(new EventArgs(), new me.PopupEntity { ViewType = me.ViewType.Alert, Status = me.PopupStatus.Failure, Description = String.Format("Einstellung {0} ist aktiviert. Korrektur wird viorgenommen", "") }); } // printer is already in zpl mode else if (language.Contains("zpl")) { return true; } // Set the printer command languege connection.Write(GetBytes("! U1 setvar \"device.languages\" \"zpl\"\r\n")); response = connection.SendAndWaitForResponse(GetBytes("! U1 getvar \"device.languages\"\r\n"), 500, 100); language = Encoding.UTF8.GetString(response, 0, response.Length); if (!language.Contains("zpl")) { // ShowErrorAlert("Printer language not set. Not a ZPL printer."); PopupEvent.FireEvent(new EventArgs(), new me.PopupEntity { ViewType = me.ViewType.Alert, Status = me.PopupStatus.Failure, Description = String.Format("Fehler. {0} ist nicht gesetzt. Kein ZPL Drucker.", "") }); return false; } return true; } catch { return false; } } public void FindPrinters(object androidContext, IDiscoveryHandler handler) { } public void Dispose() { try { if (_connection != null && _connection.IsConnected) _connection.Close(); } catch { } } }