Ejemplo n.º 1
0
        public short Connect()
        {
            try
            {
                _connection = _discoveredPrinter.GetConnection();
                _connection.Open();

                if (_connection.Connected)
                {
                    _zebraCardPrinter = ZebraCardPrinterFactory.GetInstance(_connection);

                    List <JobStatus> _joblist = _zebraCardPrinter.GetJobList();

                    if (_joblist != null && _joblist.Count > 0)
                    {
                        _currentPrintJob = _joblist.Max(i => i.ID);
                    }
                    else
                    {
                        _currentPrintJob = 0;
                    }

                    _zebraCardPrinter.RegisterAlarmHandler(this);

                    return(PrinterCodes.Success);
                }

                return(PrinterCodes.ConnectFailed);
            }
            catch
            {
                CloseQuietly(_connection, _zebraCardPrinter);
                throw;
            }
        }
        public void basicPrint(string zplbarcode, string lbl_one, string lbl_two, string lbl_three, string lbl_four, string lbl_five, string lbl_six)
        {
            List <DiscoveredPrinter> printerList = GetUSBPrinters();

            string zpl_string = "^XA"
                                + "^FX^FWr^CI28^CFA,40^FO100,50^A0B^FD" + lbl_one + "^FS^FO150,50^A0B^FD" + lbl_two + "^FS^FO200,50^A0B^FD" + lbl_three + "^FS^FO250,50^A0B^FD4MM^FS"
                                + "^FX fifth^FO595,320^A0B^FD" + lbl_four + "^FS"
                                + "^FXfifth formulation^FO510,30^A0B^FD" + lbl_five + "^FS"
                                + "^FXfourthsection with barcode."
                                + "^BY2,2.5,123^FO380,730^BCB,,N,N,N,A^FD" + zplbarcode + "^FS^CFA,40^FO320,730^A0B,0,0^FD" + zplbarcode + "^FS"
                                + "^FX fifth section"
                                + "^CF0,90^FO275,1145^A0B^FD" + lbl_six + "^FS"
                                + "^XZ";

            if (printerList.Count > 0)
            {
                // in this case, we arbitrarily are printing to the first found printer
                DiscoveredPrinter discoveredPrinter = printerList[0];
                Connection        connection        = discoveredPrinter.GetConnection();
                connection.Open();
                connection.Write(Encoding.UTF8.GetBytes(zpl_string));
            }
            else
            {
                Console.WriteLine("No Printers found to print to.");
            }
        }
        public async void SendZplPalletAsync(string header, string ipAddr)
        {
            Connection connection = null;

            try
            {
                if (!string.IsNullOrEmpty(ipAddr))
                {
                    connection = new TcpConnection(ipAddr, 9100);
                }
                else
                {
                    myPrinter  = ConstantManager.PrinterSetting;
                    connection = myPrinter.GetConnection();
                }

                await Task.Run(async() => {
                    try
                    {
                        connection.Open();
                        PrinterLanguage printerLanguage = ZebraPrinterFactory.GetInstance(connection).PrinterControlLanguage;
                        connection.Write(GetTestLabelBytes(printerLanguage, header));
                        await Task.Delay(1000);
                    }
                    catch (Exception e)
                    {
                        // Connection Exceptions and issues are caught here
                        Device.BeginInvokeOnMainThread(async() =>
                        {
                            await _dialogService.DisplayAlertAsync("Error", $"Error: {e.Message}", "Ok");
                        });
                    }
                    finally
                    {
                        try
                        {
                            connection?.Close();
                        }
                        catch (ConnectionException) { }
                    }
                });
            }
            catch (Exception ex)
            {
                // Connection Exceptions and issues are caught here
                Device.BeginInvokeOnMainThread(async() =>
                {
                    await _dialogService.DisplayAlertAsync("Error", "Could not connect to printer", "Ok");
                });
                Crashes.TrackError(ex);
            }
        }
        private void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            DiscoveredPrinter printer = viewModel.SelectedPrinter;
            string            address = printer.Address;

            IndeterminateProgressDialog indeterminateProgressDialog = new IndeterminateProgressDialog($"Connecting to {address}...");

            Task.Run(() => {
                Application.Current.Dispatcher.Invoke(() => {
                    indeterminateProgressDialog.ShowDialog();
                });
            });

            Task.Run(() => {
                Connection connection             = null;
                ZebraCardPrinter zebraCardPrinter = null;

                try {
                    connection = printer.GetConnection();
                    connection.Open();

                    zebraCardPrinter       = ZebraCardPrinterFactory.GetInstance(connection);
                    printerManager.Printer = printer;

                    Application.Current.Dispatcher.Invoke(() => {
                        Close();
                    });
                } catch (Exception exception) {
                    Application.Current.Dispatcher.Invoke(() => {
                        MessageBoxHelper.ShowError($"Error connecting to printer {address}: {exception.Message}");
                    });
                } finally {
                    ConnectionHelper.CleanUpQuietly(zebraCardPrinter, connection);

                    Application.Current.Dispatcher.Invoke(() => {
                        indeterminateProgressDialog.Close();
                    });
                }
            });
        }
        public static ZebraPrinter Connect(DiscoveredPrinter discoveredPrinter, PrinterLanguage language)
        {
            ZebraPrinter printer = null;

            try
            {
                Connection connection = discoveredPrinter.GetConnection();
                printer = ZebraPrinterFactory.GetInstance(language, connection);
                printer.Connection.Open();
                if (printer.Connection.Connected)
                {
                    Console.WriteLine($"Printer Connected");
                }
                else
                {
                    Console.WriteLine($"Printer Not Connected!");
                }
            }
            catch (ConnectionException e)
            {
                Console.WriteLine($"Error connecting to printer: {e.Message}");
            }
            return(printer);
        }
Ejemplo n.º 6
0
        public MainPage()
        {
            InitializeComponent();

            BindingContext = ViewModel;

            if (Device.RuntimePlatform != Device.WPF || !DependencyService.Get <IPlatformHelper>().IsWindows10())
            {
                ToolbarItems.Remove(BluetoothHelpButton); // Bluetooth help dialog is specific to Windows 10
            }

            try {
                if (DependencyService.Get <INfcManager>().IsNfcAvailable())
                {
                    DependencyService.Get <INfcManager>().TagScanned += async(object sender, string nfcData) => {
                        Device.BeginInvokeOnMainThread(async() => {
                            await Navigation.PopToRootAsync(); // Must call Navigation.PopToRootAsync() on UI thread on Windows tablets
                        });

                        await Task.Factory.StartNew(() => {
                            ViewModel.IsSelectingNfcPrinter = true;
                            ViewModel.SelectedPrinter       = null;

                            try {
                                ViewModel.StoredFormatList.Clear();
                            } catch (NotImplementedException) {
                                ViewModel.StoredFormatList.Clear(); // Workaround for Xamarin.Forms.Platform.WPF issue: https://github.com/xamarin/Xamarin.Forms/issues/3648
                            }

                            try {
                                ViewModel.PrinterFormatList.Clear();
                            } catch (NotImplementedException) {
                                ViewModel.PrinterFormatList.Clear(); // Workaround for Xamarin.Forms.Platform.WPF issue: https://github.com/xamarin/Xamarin.Forms/issues/3648
                            }
                        });

                        Connection        connection = null;
                        DiscoveredPrinter printer    = null;
                        bool success = false;

                        try {
                            await Task.Factory.StartNew(() => {
                                printer = NfcDiscoverer.DiscoverPrinter(nfcData);

                                connection = printer.GetConnection();
                                try {
                                    connection.Open(); // Test connection
                                } catch (Exception e) {
                                    throw new ConnectionException("Could not open connection. Please check your printer and device settings and try again.", e);
                                }

                                success = true;
                            });
                        } catch (Exception e) {
                            await AlertCreator.ShowErrorAsync(this, e.Message);
                        } finally {
                            await Task.Factory.StartNew(() => {
                                try {
                                    connection?.Close();
                                } catch (Exception) { }

                                if (success)
                                {
                                    ViewModel.SelectedPrinter       = printer;
                                    ViewModel.IsSelectingNfcPrinter = false;
                                    RefreshFormatLists();
                                }
                                else
                                {
                                    ViewModel.IsSelectingNfcPrinter = false;
                                }
                            });
                        }
                    };
                }
            } catch (TypeLoadException) { } // NFC is not supported on Windows 7

            InitializeStoredFormats();
        }
        public async Task StartPolling(DiscoveredPrinter printer, List <JobInfo> jobInfoList)
        {
            await Task.Run(() => {
                Connection connection             = null;
                ZebraCardPrinter zebraCardPrinter = null;

                bool showAtmDialog = true;
                bool isFeeding     = false;

                try {
                    connection = printer.GetConnection();
                    connection.Open();

                    zebraCardPrinter = ZebraCardPrinterFactory.GetInstance(connection);

                    Stopwatch stopwatch = Stopwatch.StartNew();

                    foreach (JobInfo jobInfo in jobInfoList)
                    {
                        UpdateLog(jobInfo.JobId, $"Polling job status for job ID {jobInfo.JobId}...");
                    }

                    while (jobInfoList.Count > 0)
                    {
                        foreach (JobInfo jobInfo in jobInfoList.ToList())
                        {
                            JobStatusInfo jobStatusInfo = zebraCardPrinter.GetJobStatus(jobInfo.JobId);

                            if (!isFeeding)
                            {
                                stopwatch = Stopwatch.StartNew();
                            }

                            bool isAlarmInfoPresent = jobStatusInfo.AlarmInfo.Value > 0;
                            bool isErrorInfoPresent = jobStatusInfo.ErrorInfo.Value > 0;
                            isFeeding = jobStatusInfo.CardPosition.Contains("feeding");

                            string alarmInfo = isAlarmInfoPresent ? $"{jobStatusInfo.AlarmInfo.Value} ({jobStatusInfo.AlarmInfo.Description})" : jobStatusInfo.AlarmInfo.Value.ToString();
                            string errorInfo = isErrorInfoPresent ? $"{jobStatusInfo.ErrorInfo.Value} ({jobStatusInfo.ErrorInfo.Description})" : jobStatusInfo.ErrorInfo.Value.ToString();

                            string jobStatusMessage = $"Job ID {jobInfo.JobId}: status:{jobStatusInfo.PrintStatus}, position:{jobStatusInfo.CardPosition}, contact:{jobStatusInfo.ContactSmartCardStatus}, " +
                                                      $"contactless:{jobStatusInfo.ContactlessSmartCardStatus}, alarm:{alarmInfo}, error:{errorInfo}";

                            UpdateLog(jobInfo.JobId, jobStatusMessage, jobInfo.JobNumber, jobStatusInfo);

                            if (jobStatusInfo.PrintStatus.Equals("done_ok"))
                            {
                                UpdateLog(jobInfo.JobId, $"Job ID {jobInfo.JobId} completed.", jobInfo.JobNumber, jobStatusInfo);

                                showAtmDialog = true;
                                stopwatch     = Stopwatch.StartNew();
                                jobInfoList.Remove(jobInfo);
                            }
                            else if (jobStatusInfo.PrintStatus.Equals("done_error"))
                            {
                                UpdateLog(jobInfo.JobId, $"Job ID {jobInfo.JobId} completed with error: {jobStatusInfo.ErrorInfo.Description}", jobInfo.JobNumber, jobStatusInfo);

                                showAtmDialog = true;
                                stopwatch     = Stopwatch.StartNew();
                                jobInfoList.Remove(jobInfo);
                            }
                            else if (jobStatusInfo.PrintStatus.Contains("cancelled"))
                            {
                                if (isErrorInfoPresent)
                                {
                                    UpdateLog(jobInfo.JobId, $"Job ID {jobInfo.JobId} cancelled with error: {jobStatusInfo.ErrorInfo.Description}", jobInfo.JobNumber, jobStatusInfo);
                                }
                                else
                                {
                                    UpdateLog(jobInfo.JobId, $"Job ID {jobInfo.JobId} cancelled.", jobInfo.JobNumber, jobStatusInfo);
                                }

                                showAtmDialog = true;
                                stopwatch     = Stopwatch.StartNew();
                                jobInfoList.Remove(jobInfo);
                            }
                            else if (isAlarmInfoPresent)
                            {
                                MessageBoxResult messageBoxResult = MessageBox.Show($"Job ID {jobInfo.JobId} encountered alarm [{jobStatusInfo.AlarmInfo.Description}].\r\n" +
                                                                                    $"Either fix the alarm and click OK once the job begins again or click Cancel to cancel the job.", "Alarm Encountered", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                                if (messageBoxResult == MessageBoxResult.Cancel)
                                {
                                    zebraCardPrinter.Cancel(jobInfo.JobId);
                                }
                            }
                            else if (isErrorInfoPresent)
                            {
                                zebraCardPrinter.Cancel(jobInfo.JobId);
                            }
                            else if (jobStatusInfo.ContactSmartCardStatus.Contains("at_station") || jobStatusInfo.ContactlessSmartCardStatus.Contains("at_station"))
                            {
                                MessageBoxResult messageBoxResult = MessageBox.Show("Please click OK to resume the job or Cancel to cancel the job.", "Card at Station", MessageBoxButton.OKCancel, MessageBoxImage.Information);
                                if (messageBoxResult == MessageBoxResult.Cancel)
                                {
                                    zebraCardPrinter.Cancel(jobInfo.JobId);
                                }
                                else
                                {
                                    zebraCardPrinter.Resume();
                                }
                            }
                            else if (isFeeding)
                            {
                                if (showAtmDialog && jobInfo.CardSource == CardSource.ATM)
                                {
                                    DialogHelper.ShowInsertCardDialog();
                                    showAtmDialog = false;
                                }
                                else if (stopwatch.ElapsedMilliseconds > CardFeedTimeoutMilliseconds)
                                {
                                    UpdateLog(jobInfo.JobId, $"Job ID {jobInfo.JobId} timed out waiting for a card and was cancelled.", jobInfo.JobNumber, jobStatusInfo);
                                    zebraCardPrinter.Cancel(jobInfo.JobId);
                                }
                            }

                            Thread.Sleep(500);
                        }
                    }
                } catch (Exception exception) {
                    MessageBoxHelper.ShowError($"Error polling job status: {exception.Message}");
                } finally {
                    ConnectionHelper.CleanUpQuietly(zebraCardPrinter, connection);
                }
            });
        }