コード例 #1
0
ファイル: MainWindow.xaml.cs プロジェクト: ag12216/linkOs
        private void PrintFormat(object sender, DoWorkEventArgs e)
        {
            Dictionary <int, string> formatVars = GetFormatVariables();

            try {
                OpenConnection();
                ZebraPrinter printer = ZebraPrinterFactory.GetInstance(printerConnection);

                string statusMessage = GetPrinterStatus(printer.GetCurrentStatus());
                if (statusMessage != null)
                {
                    errorMessage = "Printer Error: " + statusMessage + ". Please check your printer and try again.";
                }
                else
                {
                    if (!lastFormatOpenedSource.Equals(FORMAT_SOURCE_PRINTER))
                    {
                        printerConnection.Write(Encoding.UTF8.GetBytes(lastFormatOpenedContents));
                    }

                    printer.PrintStoredFormat(lastFormatOpened, formatVars, "UTF-8");
                    statusMessage = GetPrinterStatus(printer.GetCurrentStatus());
                    if (statusMessage != null)
                    {
                        errorMessage = "Printer Error after Printing: " + statusMessage + ". Please check your printer.";
                    }
                }
            } catch (ConnectionException error) {
                errorMessage = "Connection Error: " + error.Message;
            } finally {
                CloseConnection();
            }
        }
コード例 #2
0
        /* Returns true if the printer is ready to print, else false
         * Called before printing
         */
        private static string CheckPrinterStatus(Connection conn)
        {
            ZebraPrinter printer = ZebraPrinterFactory.GetLinkOsPrinter(conn);

            if (printer == null)
            {
                printer = ZebraPrinterFactory.GetInstance(PrinterLanguage.ZPL, conn);
            }

            PrinterStatus printerStatus = printer.GetCurrentStatus();

            if (printerStatus.isReadyToPrint)
            {
                return("true");
            }
            else if (printerStatus.isPaused)
            {
                return("Error: Printer is paused");
            }
            else if (printerStatus.isHeadOpen)
            {
                return("Error: Printer head is open");
            }
            else if (printerStatus.isPaperOut)
            {
                return("Error: Paper is out");
            }
            return("Error");
        }
コード例 #3
0
        private void statusUpdateThread()
        {
            try {
                ZebraPrinterConnection connection = getConnection();
                ZebraPrinter           printer    = ZebraPrinterFactory.GetInstance(connection);
                String statusMessages;

                while (getConnection() != null && connection.IsConnected())
                {
                    PrinterStatus         printerStatus = printer.GetCurrentStatus();
                    PrinterStatusMessages messages      = new PrinterStatusMessages(printerStatus);
                    String[] messagesArray = messages.GetStatusMessage();

                    statusMessages  = "Ready to Print: " + Convert.ToString(printerStatus.IsReadyToPrint);
                    statusMessages += "\r\nLabels in Batch: " + Convert.ToString(printerStatus.LabelsRemainingInBatch);
                    statusMessages += "\r\nLabels in Buffer: " + Convert.ToString(printerStatus.NumberOfFormatsInReceiveBuffer) + "\r\n\r\n";

                    foreach (String message in messagesArray)
                    {
                        statusMessages += message + "\r\n";
                    }
                    Invoke(new statusEventHandler(updateStatusMessage), statusMessages);
                    Thread.Sleep(4000);
                }
            } catch (ZebraException) {
                disconnected();
                updateGuiFromWorkerThread("COMM Error! Disconnected", Color.Red);
            }
        }
コード例 #4
0
        public async Task <bool> CetakZebraAsync(PrintTicket printData, string printerName)
        {
            var        parser    = new FileIniDataParser();
            IniData    iniData   = parser.ReadFile("Configuration.ini");
            string     serverUrl = iniData["server"]["url"];
            string     serverApi = iniData["server"]["api"];
            Connection conn      = null;

            try
            {
                conn = new DriverPrinterConnection(printerName);
                conn.Open();
                ZebraPrinter  zebraPrinter = ZebraPrinterFactory.GetInstance(conn);
                PrinterStatus printStatus  = zebraPrinter.GetCurrentStatus();
                if (printStatus.isReadyToPrint)
                {
                    foreach (TicketData data in printData.tickets)
                    {
                        byte[] buffer1 = ASCIIEncoding.ASCII.GetBytes(data.ticket);
                        conn.SendAndWaitForResponse(buffer1, 1000, 1000, null);
                        await UpdateStatus(data.id, serverApi, serverUrl, "printed");
                    }
                    conn.Close();
                    return(true);
                }
                else
                {
                    MessageBox.Show("Printer is not ready!");
                    foreach (TicketData data in printData.tickets)
                    {
                        await UpdateStatus(data.id, serverApi, serverUrl, "draft");
                    }
                    return(false);
                }
            }
            catch (ConnectionException e)
            {
                MessageBox.Show(e.Message);
                foreach (TicketData data in printData.tickets)
                {
                    await UpdateStatus(data.id, serverApi, serverUrl, "draft");
                }
                return(false);
            }
            finally
            {
                try
                {
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }
                catch (ConnectionException e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }
コード例 #5
0
ファイル: Printer.cs プロジェクト: Yarikh-Development/demo3
        //链接打印机
        public static string LinkPrinter(string printerName, int port)
        {
            try
            {
                string ip = GetRegistryData(printerName + "\\DsSpooler", "portName");

                if (ip == "" || ip.Split(new char[] { '.' }).Length != 4)
                {
                    throw new ConnectionException("没找到IP");
                }
                foreach (string s in ip.Split(new char[] { '.' }))
                {
                    int.Parse(s);
                }


                Ping      pingSender = new Ping();
                PingReply reply      = pingSender.Send(ip, 1);;
                if (reply.Status != IPStatus.Success)
                {
                    throw new ConnectionException("链接失败!");
                }



                /*Ping pingSender = new Ping();
                 * Thread thread = new Thread(new ThreadStart()));
                 * thread.Start();
                 * PingReply reply = null;
                 * reply = pingSender.Send(ip, 1);//第一个参数为ip地址,第二个参数为ping的时间
                 *
                 * Func<string, int, PingReply> func = new Func<string, int, PingReply>(Printer.PingIP);
                 * reply = func(ip, 1);
                 *
                 * if (reply.Status != IPStatus.Success)
                 *      throw new ConnectionException("链接失败!");*/

                TcpConnection connection = new TcpConnection(ip, port);
                connection.Open();
                printerHTTP   = ZebraPrinterFactory.GetInstance(connection);
                linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printerHTTP);
                printerStatus = printerHTTP.GetCurrentStatus();
            }
            catch (ConnectionException e)
            {
                printerHTTP = null;
                FileTools.WriteLineFile(FileTools.exceptionFilePath, DateTime.Now.ToString() + " " + printerName + e.Message);
                return(printerName + e.Message);
            }
            catch (FormatException e)
            {
                printerHTTP = null;
                FileTools.WriteLineFile(FileTools.exceptionFilePath, DateTime.Now.ToString() + " " + printerName + "IP地址不正确!");
                return(printerName + "IP地址不正确!");
            }

            return("");
        }
コード例 #6
0
        public String[] ReadMagCard(int timeout)
        {
            bool error = true;

            try
            {
                ThePrinterConn.Open();
                printer = ZebraPrinterFactory.GetInstance(ThePrinterConn);
                mcr     = printer.GetMagCardReader();

                PrinterStatus printerStatus = printer.GetCurrentStatus();
                bool          ready         = printerStatus.IsReadyToPrint;
                if (ready == false)
                {
                    return(null);
                }

                //MagCardReader mcr = printer.GetMagCardReader();
                if (mcr != null)
                {
                    //read
                    String[] tracks = mcr.Read(timeout);

                    if (tracks[0] != "" || tracks[1] != "" || tracks[2] != "")
                    {
                        ready = printerStatus.IsReadyToPrint;
                        if (ready)
                        {
                            String header = "! 0 200 200 0 1";
                            ThePrinterConn.Write(Encoding.UTF8.GetBytes(header + "\r\nBEEP 1\r\nPRINT\r\n"));
                        }
                    }

                    //SystemSounds.Beep.Play();
                    return(tracks);
                }

                //thePrinterConn.Close();

                error = false;
            }
            catch (Exception e)
            {
                Logger.Logger.Log(e);
                error = true;
            }
            if (error)
            {
                return(null);
            }
            else
            {
                return(new String[3] {
                    "", "", ""
                });
            }
        }
コード例 #7
0
        public static bool CheckStatusAfter(ZebraPrinter printer)
        {
            PrinterStatus printerStatus = null;

            try
            {
                VerifyConnection(printer);
                printerStatus = printer.GetCurrentStatus();

                while ((printerStatus.numberOfFormatsInReceiveBuffer > 0) && (printerStatus.isReadyToPrint))
                {
                    Thread.Sleep(500);
                    printerStatus = printer.GetCurrentStatus();
                }
            }
            catch (ConnectionException e)
            {
                throw new ConnectionException($"Error getting status from printer: {e.Message}");
            }

            if (printerStatus.isReadyToPrint)
            {
                Console.WriteLine($"Ready To Print");
                return(true);
            }
            else if (printerStatus.isPaused)
            {
                throw new NotSupportedException($"Cannot Print because the printer is paused.");
            }
            else if (printerStatus.isHeadOpen)
            {
                throw new NotSupportedException($"Cannot Print because the printer head is open.");
            }
            else if (printerStatus.isPaperOut)
            {
                throw new NotSupportedException($"Cannot Print because the paper is out.");
            }
            else
            {
                throw new NotSupportedException($"Cannot Print.");
            }
            return(false);
        }
コード例 #8
0
        private async void GetPrinterStatusButton_Clicked(object sender, EventArgs eventArgs)
        {
            AvailableChannelsLabel.Text = "";
            PrinterStatusLabel.Text     = "Retrieving printer status...";
            SetInputEnabled(false);

            StatusConnection statusConnection = null;
            Connection       rawConnection    = null;

            try {
                statusConnection = CreateStatusConnection();

                if (statusConnection == null)
                {
                    return;
                }

                if (GetSelectedConnectionType() == ConnectionType.Bluetooth)
                {
                    try {
                        // Over Bluetooth, the printer only broadcasts the status connection if a valid raw connection is open
                        rawConnection = DependencyService.Get <IConnectionManager>().GetBluetoothConnection(AddressEntry.Text);
                    } catch (NotImplementedException) {
                        throw new NotImplementedException("Bluetooth connection not supported on this platform");
                    }

                    await Task.Factory.StartNew(() => {
                        rawConnection.Open();
                    });

                    await Task.Delay(3000); // Give the printer some time to start the status connection
                }

                await Task.Factory.StartNew(() => {
                    statusConnection.Open();

                    ZebraPrinter printer        = ZebraPrinterFactory.GetLinkOsPrinter(statusConnection);
                    PrinterStatus printerStatus = printer.GetCurrentStatus();

                    Device.BeginInvokeOnMainThread(() => {
                        UpdateResult(printerStatus);
                    });
                });
            } catch (Exception e) {
                PrinterStatusLabel.Text = $"Error: {e.Message}";
                await DisplayAlert("Error", e.Message, "OK");
            } finally {
                try {
                    statusConnection?.Close();
                    rawConnection?.Close();
                } catch (ConnectionException) { }

                SetInputEnabled(true);
            }
        }
コード例 #9
0
        private bool CheckPrintingStatus(ZebraPrinter printer)
        {
            PrinterStatus printerStatus = null;

            try
            {
                printerStatus = printer.GetCurrentStatus();

                while (printerStatus.numberOfFormatsInReceiveBuffer > 0 && printerStatus.isReadyToPrint)
                {
                    Thread.Sleep(100);
                    printerStatus = printer.GetCurrentStatus();
                }
            }
            catch (ConnectionException e)
            {
                Debug.WriteLine("Connection Exception: " + e.ToString());
            }

            return(printerStatus.isReadyToPrint);
        }
コード例 #10
0
        /* Should be called during and after printing to check printer status */
        private bool PostPrintCheckPrinterStatus(Connection conn)
        {
            ZebraPrinter printer = ZebraPrinterFactory.GetLinkOsPrinter(conn, PrinterLanguage.ZPL);

            if (printer == null)
            {
                printer = ZebraPrinterFactory.GetInstance(PrinterLanguage.ZPL, conn);
            }
            PrinterStatus printerStatus = printer.GetCurrentStatus();

            // loop while printing until print is complete or there is an error
            while ((printerStatus.numberOfFormatsInReceiveBuffer > 0) && (printerStatus.isReadyToPrint))
            {
                Thread.Sleep(500);
                printerStatus = printer.GetCurrentStatus();
            }
            if (printerStatus.isReadyToPrint)
            {
                Debug.WriteLine("Printer Status: Ready to Print");
                return(true);
            }
            else if (printerStatus.isPaused)
            {
                Debug.WriteLine("Printer Status: Cannot printer - printer is paused");
            }
            else if (printerStatus.isHeadOpen)
            {
                Debug.WriteLine("Printer Status: Cannot print - head is open");
            }
            else if (printerStatus.isPaperOut)
            {
                Debug.WriteLine("Printer Status: Cannot print - paper is out");
            }
            else
            {
                Debug.WriteLine("Printer Status: Cannot print");
            }
            return(false);
        }
コード例 #11
0
        /*
         * Check if the printer is ready
         */
        private bool PrinterIsReady()
        {
            bool ready;

            try
            {
                ready = printer != null && printer.GetCurrentStatus().isReadyToPrint;
            }catch (Exception)
            {
                ready = false;
            }
            return(ready);
        }
コード例 #12
0
        public bool Print()
        {
            bool error = true;

            try
            {
                // Open the connection - physical connection is established here.
                ThePrinterConn.Open();

                printer = ZebraPrinterFactory.GetInstance(ThePrinterConn);
                PrinterStatus printerStatus = printer.GetCurrentStatus();
                bool          ready         = printerStatus.IsReadyToPrint;
                if (ready == false)
                {
                    return(error);
                }



                //stvaranje oblika za slanje na printer
                String output = "! 0 200 200" + " " + (lastYPos + 100).ToString() + " " + "1\r\n";
                //output += "IN-MILLIMETERS\r\n";
                foreach (String s in buffer)
                {
                    output += s + "\r\n";
                }
                output += "PRINT\r\n";

                // Send the data to the printer as a byte array.
                ThePrinterConn.Write(Encoding.UTF8.GetBytes(output));
                //thePrinterConn.Close();
                error = false;
            }
            catch (Exception e)
            {
                Logger.Logger.Log(e);
                error = true;
            }
            finally
            {
                //brisi buffer
                buffer.Clear();

                //na kraju, baci gresku ako nije izvrseno do kraja...
            }
            return(error);
        }
コード例 #13
0
        public static bool CheckStatus(ZebraPrinter printer)
        {
            PrinterStatus printerStatus = null;

            try
            {
                VerifyConnection(printer);

                printerStatus = printer.GetCurrentStatus();
            }
            catch (ConnectionException e)
            {
                throw new NotSupportedException($"Error getting status from printer: {e.Message}");
            }

            if (null == printerStatus)
            {
                throw new NotSupportedException($"Unable to get status.");
            }
            else if (printerStatus.isReadyToPrint)
            {
                Console.WriteLine($"Ready To Print");
                return(true);
            }
            else if (printerStatus.isPaused)
            {
                throw new NotSupportedException($"Cannot Print because the printer is paused.");
            }
            else if (printerStatus.isHeadOpen)
            {
                throw new NotSupportedException($"Cannot Print because the printer head is open.");
            }
            else if (printerStatus.isPaperOut)
            {
                throw new NotSupportedException($"Cannot Print because the paper is out.");
            }
            else
            {
                throw new NotSupportedException($"Cannot Print.");
            }
            return(false);
        }
コード例 #14
0
        public void Beep(int lenght)
        {
            try
            {
                printer = ZebraPrinterFactory.GetInstance(ThePrinterConn);

                PrinterStatus printerStatus = printer.GetCurrentStatus();
                bool          ready         = printerStatus.IsReadyToPrint;
                if (ready)
                {
                    String header = "! 0 200 200 0 1";
                    ThePrinterConn.Write(Encoding.UTF8.GetBytes(header + "\r\nBEEP " + lenght.ToString() + "\r\nPRINT\r\n"));
                }
            }
            catch (Exception e)
            {
                Logger.Logger.Log(e);
                return;
            }
        }
コード例 #15
0
        public PrinterStatus getPrinterStatus(rho.PrinterZebraImpl.PrinterZebra.EPrinterConnectionType connType, string address, Int32 port)
        {
            Logger.Write("MainWindow.getPrinterStatus call, address=" + address + " port=" + port.ToString());

            PrinterStatus          status     = null;
            ZebraPrinterConnection connection = null;
            ZebraPrinter           printer    = null;

            if (connType == rho.PrinterZebraImpl.PrinterZebra.EPrinterConnectionType.eTCP)
            {
                connection = new TcpPrinterConnection(address, port);
            }
            else if (connType == rho.PrinterZebraImpl.PrinterZebra.EPrinterConnectionType.eBluetooth)
            {
                connection = new BluetoothPrinterConnection(address);
            }
            else if (connType == rho.PrinterZebraImpl.PrinterZebra.EPrinterConnectionType.eUSB)
            {
                connection = new UsbPrinterConnection(address);
            }
            else
            {
                Logger.Write("MainWindow.getPrinterStatus undifined connection type");
                return(null);
            }

            connection.Open();

            if (connection.IsConnected())
            {
                printer = ZebraPrinterFactory.GetInstance(PrinterLanguage.ZPL, connection);

                status = printer.GetCurrentStatus();
            }

            connection.Close();

            Logger.Write("MainWindow.getPrinterStatus call finished");

            return(status);
        }
コード例 #16
0
        private string GetPrinterStatus(ZebraPrinter printer)
        {
            try
            {
                PrinterStatus printerStatus = printer.GetCurrentStatus();

                if (printerStatus.isReadyToPrint)
                {
                    return(Status.Ready);
                }
                else if (printerStatus.isPaused)
                {
                    return(Status.Paused);
                }
                else if (printerStatus.isHeadOpen)
                {
                    return(Status.HeadOpen);
                }
                else if (printerStatus.isPaperOut)
                {
                    return(Status.MediaOut);
                }
                else if (printerStatus.isRibbonOut)
                {
                    return(Status.RibbonOut);
                }
                else
                {
                    return(Status.CannotPrint);
                }
            }
            catch (ConnectionException e)
            {
                return(e.ToString());
            }
            catch (ZebraPrinterLanguageUnknownException e)
            {
                return(e.ToString());
            }
        }
コード例 #17
0
        public bool KeepAlive()
        {
            bool error = true;

            try
            {
                // Open the connection - physical connection is established here.
                ThePrinterConn.Open();

                printer = ZebraPrinterFactory.GetInstance(ThePrinterConn);
                PrinterStatus printerStatus = printer.GetCurrentStatus();
                bool          ready         = printerStatus.IsReadyToPrint;
                if (ready == false)
                {
                    return(error);
                }



                //stvaranje oblika za slanje na printer
                String output = "! 0 200 200 100 1\r\n";
                output += "PRINT\r\n";

                // Send the data to the printer as a byte array.
                ThePrinterConn.Write(Encoding.UTF8.GetBytes(output));
                //thePrinterConn.Close();
                error = false;
            }
            catch (Exception e)
            {
                Logger.Logger.Log(e);
                error = true;
            }
            finally
            {
                //na kraju, baci gresku ako nije izvrseno do kraja...
            }
            return(error);
        }
コード例 #18
0
        private async void CheckPrinterStatusButton_Clicked(object sender, EventArgs eventArgs)
        {
            SetInputEnabled(false);
            PrinterStatusLabel.Text = "Checking printer status...";

            Connection connection = null;

            try {
                await Task.Factory.StartNew(() => {
                    connection = CreateConnection();
                    connection.Open();

                    ZebraPrinter printer             = ZebraPrinterFactory.GetInstance(connection);
                    ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer);

                    PrinterStatus printerStatus = linkOsPrinter?.GetCurrentStatus() ?? printer.GetCurrentStatus();

                    Device.BeginInvokeOnMainThread(() => {
                        PrinterStatusLabel.Text = BuildPrinterStatusString(printerStatus);
                    });
                });
            } catch (Exception e) {
                PrinterStatusLabel.Text = $"Error: {e.Message}";
                await DisplayAlert("Error", e.Message, "OK");
            } finally {
                try {
                    connection?.Close();
                } catch (ConnectionException) { }

                SetInputEnabled(true);
            }
        }
コード例 #19
0
        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) { }
                });
            }
        }
コード例 #20
0
        /// <summary>
        /// 获取打印机状态
        /// </summary>
        /// <returns></returns>
        public PrinterStatus GetPrinterStatus()
        {
            lock (connectionHelper)
            {
                connection = null;
            }

            lock (printerHelper)
            {
                printer = null;
            }
            PrinterStatus printerStatus = null;

            if (TryOpenPrinterConnection())
            {
                printer = GetPrinter();
                if (printer != null)
                {
                    try
                    {
                        ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer);

                        printerStatus = (linkOsPrinter != null) ? linkOsPrinter.GetCurrentStatus() : printer.GetCurrentStatus();
                    }
                    catch (Exception ex)
                    {
                        myEventLog.LogError("获取打印机状态出错!", ex);
                    }
                    finally
                    {
                    }
                }
            }

            return(printerStatus);
        }
コード例 #21
0
        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) { }
                });
            }
        }
コード例 #22
0
        private void GetPrinterStatus()
        {
            Connection printerConnection = null;

            Task.Run(() => {
                try {
                    printerConnection = connectionSelector.GetConnection();
                    printerConnection.Open();

                    ZebraPrinter printer             = ZebraPrinterFactory.GetInstance(printerConnection);
                    ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer);

                    ZebraPrinterStatus status = (linkOsPrinter != null) ? linkOsPrinter.GetCurrentStatus() : printer.GetCurrentStatus();

                    string[] printerStatusString      = new PrinterStatusMessages(status).GetStatusMessage();
                    List <string> printerStatusPrefix = GetPrinterStatusPrefix(status);

                    StringBuilder sb = new StringBuilder();
                    foreach (string s in printerStatusPrefix)
                    {
                        sb.AppendLine(s);
                    }

                    foreach (string s in printerStatusString)
                    {
                        sb.AppendLine(s);
                    }

                    Application.Current.Dispatcher.Invoke(() => {
                        printerStatus.Text = sb.ToString();
                    });
                } catch (ConnectionException e) {
                    MessageBoxCreator.ShowError(e.Message, "Connection Error");
                } catch (ZebraPrinterLanguageUnknownException e) {
                    MessageBoxCreator.ShowError(e.Message, "Connection Error");
                } finally {
                    if (printerConnection != null)
                    {
                        try {
                            printerConnection.Close();
                        } catch (ConnectionException) {
                        } finally {
                            SetTestButtonState(true);
                        }
                    }
                    else
                    {
                        SetTestButtonState(true);
                    }
                }
            });
        }
コード例 #23
0
        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);
            }
        }