public static bool SetPageLanguage(ZebraPrinter printer) { bool set = false; string setLang = "zpl"; if (PrinterLanguage.ZPL != printer.PrinterControlLanguage) { setLang = "line_print"; } try { VerifyConnection(printer); SGD.SET("device.languages", setLang, printer.Connection); string getLang = SGD.GET("device.languages", printer.Connection); if (getLang.Contains(setLang)) { set = true; } else { Console.WriteLine($"This is not a {setLang} printer."); } } catch (ConnectionException e) { Console.WriteLine($"Unable to set print language: {e.Message}"); } return(set); }
private async void PrintButton_Clicked(object sender, EventArgs eventArgs) { SetInputEnabled(false); Connection connection = null; try { await Task.Factory.StartNew(() => { connection = CreateConnection(); connection.Open(); ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); if (printer.PrinterControlLanguage == PrinterLanguage.LINE_PRINT) { throw new ConnectionException("Operation cannot be performed with a printer set to line print mode"); } string signaturePath = Path.Combine(LocalApplicationDataFolderPath, "signature.jpeg"); double printWidth = double.Parse(SGD.GET("ezpl.print_width", connection)); if (File.Exists(signaturePath)) { File.Delete(signaturePath); } using (Stream stream = SignaturePad.GetImageStream(printWidth)) { using (BinaryReader br = new BinaryReader(stream)) { br.BaseStream.Position = 0; byte[] signatureBytes = br.ReadBytes((int)stream.Length); File.WriteAllBytes(signaturePath, signatureBytes); } } ZebraImageI image = ZebraImageFactory.Current.GetImage(signaturePath); printer.PrintImage(image, 0, 0, image.Width, image.Height, false); }); } catch (Exception e) { await DisplayAlert("Error", e.Message, "OK"); } finally { try { connection?.Close(); } catch (ConnectionException) { } SetInputEnabled(true); } }
/* Sets the page description langauge to ZPL */ private bool SetPrintLangauge(Connection conn) { Debug.WriteLine("START: Set PrintLanguage()"); string pageDescriptionLanguage = "zpl"; //Set the print langaugein the printer SGD.SET("device.languages", pageDescriptionLanguage, conn); //Get the print language in the printer to verify the printe was able to switch string s = SGD.GET("device.languages", conn); if (!s.Contains(pageDescriptionLanguage)) { Debug.WriteLine("Error: " + pageDescriptionLanguage + " not found- Not a ZPL Printer"); return(false); } Debug.WriteLine("END: PrintLanguage() - language set"); return(true); }
private async void GetSettingsButton_Clicked(object sender, EventArgs eventArgs) { ClearSettings(); SetInputEnabled(false); Connection connection = null; bool linePrintEnabled = false; try { await Task.Factory.StartNew(() => { connection = CreateConnection(); connection.Open(); string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); } UpdateSettingsTable(connection, originalPrinterLanguage); }); } catch (Exception e) { await DisplayAlert("Error", e.Message, "OK"); } finally { if (linePrintEnabled) { await Task.Factory.StartNew(() => { try { connection?.Open(); SGD.SET(DeviceLanguagesSgd, "line_print", connection); } catch (ConnectionException) { } }); } try { connection?.Close(); } catch (ConnectionException) { } SetInputEnabled(true); } }
public string getAnswerFromPrinter() { if (m_connection != null && m_connection.IsConnected()) { string result = null; for (int i = 0; i < 5; i++) { result = SGD.GET("file.dir", m_connection); Thread.Sleep(500); if (result != null && result.Length != 0) { break; } } return(result); } return(null); }
private void Run() { try { if (ConnectionType == PrinterZebra.EPrinterConnectionType.eTCP) { Connection = new TcpPrinterConnection(Address, Port, MaxTimeoutForRead, TimeToWaitForMoreData); } else if (ConnectionType == PrinterZebra.EPrinterConnectionType.eBluetooth) { Connection = new BluetoothPrinterConnection(Address, MaxTimeoutForRead, TimeToWaitForMoreData); } else if (ConnectionType == PrinterZebra.EPrinterConnectionType.eUSB) { Connection = new UsbPrinterConnection(Address); } if (Connection == null) { return; } Connection.Open(); if (Connection != null && !Connection.IsConnected()) { Close(); return; } if (Connection != null) { if (ConnectionType != PrinterZebra.EPrinterConnectionType.eUSB) { SGD.SET("device.languages", "ZPL", Connection); } else { //Do nothing for USB } Printer = ZebraPrinterFactory.GetInstance(PrinterLanguage.ZPL, Connection); if (ConnectionType != PrinterZebra.EPrinterConnectionType.eUSB) { FriendlyName = SGD.GET("device.friendly_name", Connection); } else { FriendlyName = "USB Printer"; } if (FriendlyName.Length == 0) { Logger.Write("friendly name is empty, return device name"); FriendlyName = Address; } } } catch (ZebraPrinterConnectionException e) { Logger.Write("Connect exception [connection]: " + e.Message); Close(); } catch (ZebraGeneralException e) { Logger.Write("Connect exception [general]: " + e.Message); Close(); } catch (Exception e) { Logger.Write("Connect exception [system]: " + e.Message); Close(); } }
private async Task SavePrinterFormatAsync(FormatViewModel format) { PrintStationDatabase.StoredFormat storedFormat = null; Connection connection = null; bool fileWriteAttempted = false; bool linePrintEnabled = false; try { await Task.Factory.StartNew(async() => { connection = ConnectionCreator.Create(ViewModel.SelectedPrinter); connection.Open(); string originalPrinterLanguage = SGD.GET(PrintFormatPage.DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(PrintFormatPage.DeviceLanguagesSgd, "zpl", connection); } ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); string formatContent = Encoding.UTF8.GetString(printer.RetrieveFormatFromPrinter(format.PrinterPath)); fileWriteAttempted = true; storedFormat = new PrintStationDatabase.StoredFormat { DriveLetter = format.DriveLetter, Name = format.Name, Extension = format.Extension, Content = formatContent }; await App.Database.SaveStoredFormatAsync(storedFormat); }); } catch (Exception e) { await Task.Factory.StartNew(async() => { if (fileWriteAttempted && storedFormat != null) { await App.Database.DeleteStoredFormatByIdAsync(storedFormat.Id); } }); await AlertCreator.ShowErrorAsync(this, e.Message); } finally { if (linePrintEnabled) { await Task.Factory.StartNew(() => { try { connection?.Open(); SGD.SET(PrintFormatPage.DeviceLanguagesSgd, "line_print", connection); } catch (ConnectionException) { } }); } await Task.Factory.StartNew(() => { try { connection?.Close(); } catch (ConnectionException) { } }); } }
public async Task PrintAsync(DiscoveredPrinter printer, string message) { Connection connection = null; bool linePrintEnabled = false; try { await Task.Factory.StartNew(() => { connection = ConnectionCreator.Create(printer); connection.Open(); string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); } ZebraPrinter zebraPrinter = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(zebraPrinter); string errorMessage = GetPrinterStatusErrorMessage(zebraPrinter.GetCurrentStatus()); if (errorMessage != null) { throw new PrinterNotReadyException($"{errorMessage}. Please check your printer and try again."); } else { connection.Write(Encoding.UTF8.GetBytes(message)); } }); if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } } catch (PrinterNotReadyException e) { if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } throw new Exception(e.Message); } catch (Exception e) { if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } throw new Exception(e.Message); } finally { await Task.Factory.StartNew(() => { try { connection?.Close(); } catch (ConnectionException) { } }); } }
private async Task PopulateVariableFieldListAsync() { await Task.Factory.StartNew(() => { viewModel.IsVariableFieldListRefreshing = true; try { viewModel.FormatVariableList.Clear(); } catch (NotImplementedException) { viewModel.FormatVariableList.Clear(); // Workaround for Xamarin.Forms.Platform.WPF issue: https://github.com/xamarin/Xamarin.Forms/issues/3648 } }); Connection connection = null; bool linePrintEnabled = false; try { await Task.Factory.StartNew(() => { connection = ConnectionCreator.Create(selectedPrinter); connection.Open(); string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); } ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); if (format.Source == FormatSource.Printer) { format.Content = Encoding.UTF8.GetString(printer.RetrieveFormatFromPrinter(format.PrinterPath)); } FieldDescriptionData[] variableFields = printer.GetVariableFields(format.Content); foreach (FieldDescriptionData variableField in variableFields) { viewModel.FormatVariableList.Add(new FormatVariable { Name = variableField.FieldName ?? $"Field {variableField.FieldNumber}", Index = variableField.FieldNumber, }); } }); } catch (Exception e) { await AlertCreator.ShowErrorAsync(this, e.Message); } finally { if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } await Task.Factory.StartNew(() => { try { connection?.Close(); } catch (ConnectionException) { } viewModel.IsVariableFieldListRefreshing = false; }); } }
private async void PrintButton_Clicked(object sender, EventArgs eventArgs) { await Task.Factory.StartNew(() => { viewModel.IsSendingPrintJob = true; }); Connection connection = null; bool linePrintEnabled = false; try { await Task.Factory.StartNew(() => { connection = ConnectionCreator.Create(selectedPrinter); connection.Open(); string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); } ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); string errorMessage = GetPrinterStatusErrorMessage(printer.GetCurrentStatus()); if (errorMessage != null) { throw new PrinterNotReadyException($"{errorMessage}. Please check your printer and try again."); } else { if (format.Source != FormatSource.Printer) { connection.Write(Encoding.UTF8.GetBytes(format.Content)); } linkOsPrinter.PrintStoredFormatWithVarGraphics(format.PrinterPath, BuildFormatVariableDictionary(), "UTF-8"); } }); if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } await Task.Factory.StartNew(() => { viewModel.IsSendingPrintJob = false; }); } catch (PrinterNotReadyException e) { if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } await Task.Factory.StartNew(() => { viewModel.IsSendingPrintJob = false; }); await AlertCreator.ShowAsync(this, "Printer Error", e.Message); } catch (Exception e) { if (linePrintEnabled) { await ResetPrinterLanguageToLinePrintAsync(connection); } await Task.Factory.StartNew(() => { viewModel.IsSendingPrintJob = false; }); await AlertCreator.ShowErrorAsync(this, e.Message); } finally { await Task.Factory.StartNew(() => { try { connection?.Close(); } catch (ConnectionException) { } }); } }
private async void TestButton_Clicked(object sender, EventArgs eventArgs) { SetInputEnabled(false); bool printJobFinished = false; MultichannelConnection multichannelConnection = null; try { multichannelConnection = CreateMultichannelConnection(); if (multichannelConnection == null) { return; } ZebraPrinter linkOsPrinter = null; await Task.Factory.StartNew(() => { multichannelConnection.Open(); linkOsPrinter = ZebraPrinterFactory.GetLinkOsPrinter(multichannelConnection.StatusChannel); }); Task statusTask = Task.Factory.StartNew(() => { int queryCount = 0; List <string> odometerSettings = new List <string> { "odometer.total_label_count", "odometer.total_print_length" }; while (multichannelConnection.StatusChannel.Connected && !printJobFinished) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); LinkOsInformation linkOsInformation = new LinkOsInformation(SGD.GET("appl.link_os_version", multichannelConnection)); Dictionary <string, string> odometerSettingsMap = new SettingsValues().GetValues(odometerSettings, multichannelConnection.StatusChannel, linkOsPrinter.PrinterControlLanguage, linkOsInformation); PrinterStatus printerStatus = linkOsPrinter.GetCurrentStatus(); queryCount++; stopwatch.Stop(); Device.BeginInvokeOnMainThread(() => { UpdateResult(queryCount, stopwatch.ElapsedMilliseconds, printerStatus, odometerSettingsMap); }); } }); Task printingTask = Task.Factory.StartNew(async() => { try { multichannelConnection.PrintingChannel.Write(GetTestLabelBeginningBytes(linkOsPrinter.PrinterControlLanguage)); await Task.Delay(500); multichannelConnection.PrintingChannel.Write(GetTestLabelEndBytes(linkOsPrinter.PrinterControlLanguage)); await Task.Delay(3000); } catch (Exception e) { throw e; } finally { printJobFinished = true; } }); Task aggregateTask = Task.WhenAll(statusTask, printingTask); await aggregateTask; if (aggregateTask.Exception != null) { throw aggregateTask.Exception; } } catch (Exception e) { ResultLabel.Text = $"Error: {e.Message}"; await DisplayAlert("Error", e.Message, "OK"); } finally { try { multichannelConnection?.Close(); } catch (ConnectionException) { } SetInputEnabled(true); } }
private async void SaveSettingsButton_Clicked(object sender, EventArgs eventArgs) { SetInputEnabled(false); Connection connection = null; bool linePrintEnabled = false; bool deviceLanguageUpdated = false; try { await Task.Factory.StartNew(() => { connection = CreateConnection(); connection.Open(); ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); if (linkOsPrinter != null) { string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); printer = ZebraPrinterFactory.GetInstance(connection); linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); } foreach (string key in modifiedSettings.Keys) { if (linkOsPrinter.IsSettingReadOnly(key) == false) { linkOsPrinter.SetSetting(key, modifiedSettings[key]); } } deviceLanguageUpdated = modifiedSettings.ContainsKey(DeviceLanguagesSgd); modifiedSettings.Clear(); ClearSettings(); UpdateSettingsTable(connection, originalPrinterLanguage); } else { Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Connection Error", "Connected printer does not support settings", "OK"); }); } }); } catch (Exception e) { await DisplayAlert("Error", e.Message, "OK"); } finally { if (linePrintEnabled && !deviceLanguageUpdated) { await Task.Factory.StartNew(() => { try { connection?.Open(); SGD.SET(DeviceLanguagesSgd, "line_print", connection); } catch (ConnectionException) { } }); } try { connection?.Close(); } catch (ConnectionException) { } SetInputEnabled(true); } }
private async void UploadProfileButton_Clicked(object sender, EventArgs eventArgs) { SetInputEnabled(false); Connection connection = null; bool linePrintEnabled = false; try { await Task.Factory.StartNew(() => { connection = CreateConnection(); connection.Open(); ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); printer = ZebraPrinterFactory.GetInstance(connection); linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); } string selectedFilename = (string)FileListView.SelectedItem; if (selectedFilename != null) { if (linkOsPrinter != null) { string path = Path.Combine(LocalApplicationDataFolderPath, selectedFilename); linkOsPrinter.LoadProfile(path, FileDeletionOption.NONE, false); Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Profile Uploaded Successfully", $"Profile loaded successfully to printer", "OK"); }); } else { Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Error", "Profile loading is only available on Link-OS\u2122 printers", "OK"); }); } } else { Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("No Profile Selected", "Please select a profile to upload", "OK"); }); } }); } catch (Exception e) { await DisplayAlert("Error", e.Message, "OK"); } finally { if (linePrintEnabled) { await Task.Factory.StartNew(() => { try { connection?.Open(); SGD.SET(DeviceLanguagesSgd, "line_print", connection); } catch (ConnectionException) { } }); } try { connection?.Close(); } catch (ConnectionException) { } SetInputEnabled(true); } }
private async void CreateProfileButton_Clicked(object sender, EventArgs eventArgs) { SetInputEnabled(false); string filename = FilenameEntry.Text; Connection connection = null; bool linePrintEnabled = false; try { if (!string.IsNullOrWhiteSpace(filename)) { await Task.Factory.StartNew(() => { connection = CreateConnection(); connection.Open(); ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection); ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); string originalPrinterLanguage = SGD.GET(DeviceLanguagesSgd, connection); linePrintEnabled = "line_print".Equals(originalPrinterLanguage, StringComparison.OrdinalIgnoreCase); if (linePrintEnabled) { SGD.SET(DeviceLanguagesSgd, "zpl", connection); printer = ZebraPrinterFactory.GetInstance(connection); linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer); } if (linkOsPrinter != null) { if (!filename.EndsWith(".zprofile")) { filename += ".zprofile"; } string path = Path.Combine(LocalApplicationDataFolderPath, filename); linkOsPrinter.CreateProfile(path); Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Profile Created Successfully", $"Profile created successfully with filename {filename}", "OK"); }); RefreshLocalApplicationDataFiles(); } else { Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Error", "Profile creation is only available on Link-OS\u2122 printers", "OK"); }); } }); } else { await DisplayAlert("Invalid Filename", "Please enter a valid filename", "OK"); SetInputEnabled(true); } } catch (Exception e) { await DisplayAlert("Error", e.Message, "OK"); } finally { if (linePrintEnabled) { await Task.Factory.StartNew(() => { try { connection?.Open(); SGD.SET(DeviceLanguagesSgd, "line_print", connection); } catch (ConnectionException) { } }); } try { connection?.Close(); } catch (ConnectionException) { } SetInputEnabled(true); } }