Ejemplo n.º 1
0
        public PrinterStatus GetPrinterStatus(string ipAddress)
        {
            Connection connection = new TcpConnection(ipAddress, TcpConnection.DEFAULT_ZPL_TCP_PORT);

            try
            {
                connection.Open();
                var printer = ZebraPrinterFactory.GetInstance(connection);

                return(printer.GetCurrentStatus());
            }
            catch (ConnectionException e)
            {
                throw;
            }
            catch (ZebraPrinterLanguageUnknownException e)
            {
                throw;
            }

            finally
            {
                connection.Close();
            }
        }
        private void PrintFormat(string formatName)
        {
            Connection printerConnection = null;

            try {
                printerConnection = connectionSelector.GetConnection();
                printerConnection.Open();

                Dictionary <int, string> formatVars = GetFormatVariables();
                ZebraPrinterFactory.GetInstance(printerConnection).PrintStoredFormat(formatName, formatVars, "UTF-8");
            } catch (ArgumentException e) {
                MessageBoxCreator.ShowError(e.Message, "Communication Error");
            } catch (ConnectionException e) {
                MessageBoxCreator.ShowError(e.Message, "Communication Error");
            } catch (ZebraPrinterLanguageUnknownException e) {
                MessageBoxCreator.ShowError(e.Message, "Communication Error");
            } finally {
                if (printerConnection != null)
                {
                    try {
                        printerConnection.Close();
                    } catch (ConnectionException) { }
                }
            }
        }
Ejemplo n.º 3
0
        private async Task <string> RetrieveFormatContentAsync(FormatViewModel format)
        {
            string     formatContent = null;
            Connection connection    = null;

            try {
                await Task.Factory.StartNew(() => {
                    connection = ConnectionCreator.Create(ViewModel.SelectedPrinter);
                    connection.Open();

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

                    formatContent = Encoding.UTF8.GetString(printer.RetrieveFormatFromPrinter(format.PrinterPath));
                });
            } catch (Exception e) {
                await AlertCreator.ShowErrorAsync(this, e.Message);
            } finally {
                await Task.Factory.StartNew(() => {
                    try {
                        connection?.Close();
                    } catch (ConnectionException) { }
                });
            }

            return(formatContent);
        }
Ejemplo n.º 4
0
        public static void PrintWareHouse(string WMS, string WMS_NM)
        {
            try
            {
                if (Printer == null)
                {
                    Printer = ZebraPrinterFactory.GetInstance(PrinterConnection);
                }

                int    DefaultX = 10;
                int    DefaultY = 10;
                string command  = "^XA" +
                                  "^SEE:UHANGUL.DAT^FS" +
                                  "^CW1,E:KFONT3.TTF" +
                                  "^CI28^FS" +
                                  "^CF1,35" + // 폰트설정
                                  "^FO" + (DefaultX + 140).ToString() + "," + (DefaultY + 50).ToString() + "^FD" + WMS + ":" + WMS_NM + "^FS" +
                                  "^BCN,70,N,N,N" + "^FO" + (DefaultX + 140).ToString() + "," + (DefaultY + 90).ToString() + "^FD" + WMS + "000001" + "^FS" +
                                  "^FO" + (DefaultX + 160).ToString() + "," + (DefaultY + 170).ToString() + "^FD" + WMS + "000001" + "^FS";
                command = command + "^XZ";
                Printer.SendCommand(command);
            }
            catch (ConnectionException ex)
            {
                MessageBox.Show("프린트 실패" + Environment.NewLine + ex.ToString(), "실패", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show("프린트 실패" + Environment.NewLine + ex.ToString(), "실패", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.Hide();
            System.Threading.Thread.Sleep(10000);
            try
            {
                screen_image = GetScreenCapture();   //Get bitmap image of the screen
                String myMacAddress = textBox1.Text; //Printer's Bluetooth MAC Address.
                ZebraPrinterConnection zebraPrinterConnection = new BluetoothPrinterConnection(myMacAddress);
                zebraPrinterConnection.Open();
                ZebraPrinter printer = ZebraPrinterFactory.GetInstance(zebraPrinterConnection);

                int x = 10;
                int y = 200;
                zebraPrinterConnection.Write(Encoding.Default.GetBytes("! 0 200 200 1200 1\r\n"));
                printer.GetGraphicsUtil().PrintImage(screen_image, x, y, -1, -1, true);  //Print the screen caputre image.
                zebraPrinterConnection.Write(Encoding.Default.GetBytes("FORM\r\nPRINT\r\n"));
                zebraPrinterConnection.Close();
            }
            catch
            {
                MessageBox.Show("Unable to print screen image");
            }

            this.Show();
        }
Ejemplo n.º 6
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");
        }
        private void UploadProfile(string profilePath, Connection connection)
        {
            if (connection != null)
            {
                try {
                    connection.Open();
                    ZebraPrinter       genericPrinter = ZebraPrinterFactory.GetInstance(connection);
                    ZebraPrinterLinkOs printer        = ZebraPrinterFactory.CreateLinkOsPrinter(genericPrinter);

                    if (printer != null)
                    {
                        printer.LoadProfile(profilePath, FileDeletionOption.NONE, false);
                        string printerAddress = connectionSelector.getConnectionAddress();
                        MessageBoxCreator.ShowInformation($"Profile loaded successfully to printer {printerAddress}", "Profile Uploaded Successfully");
                    }
                    else
                    {
                        MessageBoxCreator.ShowError("Profile loading is only available on Link-OS(TM) printers", "Error");
                    }
                } catch (ConnectionException e) {
                    MessageBoxCreator.ShowError(e.Message, "Connection Error");
                } catch (ZebraPrinterLanguageUnknownException e) {
                    MessageBoxCreator.ShowError(e.Message, "Connection Error");
                } catch (IOException e) {
                    MessageBoxCreator.ShowError(e.Message, "Connection Error");
                } catch (Exception e) {
                    MessageBoxCreator.ShowError(e.Message, "Upload Profile Error");
                } finally {
                    SetButtonStates(true);
                    try {
                        connection.Close();
                    } catch (ConnectionException) { }
                }
            }
        }
        /// <summary>
        ///
        /// head.resolution.in_dpi:203
        /// zpl.label_length:590
        /// odometer.label_dot_length:590
        /// media.width_sense.in_mm:104.1
        /// media.width_sense.in_cm:10.41
        /// media.width_sense.in_dots:832
        /// media.width_sense.in_inches:4.099
        /// sensor.width.cur:209
        /// sensor.width.in_dots:832
        ///
        /// </summary>
        /// <param name="c"></param>
        private static void DisplaySettings(Connection c)
        {
            ZebraPrinter       genericPrinter = ZebraPrinterFactory.GetInstance(c);
            ZebraPrinterLinkOs linkOsPrinter  = ZebraPrinterFactory.CreateLinkOsPrinter(genericPrinter);

            if (linkOsPrinter != null)
            {
                Console.WriteLine("Available Settings for myDevice");
                HashSet <string> availableSettings = linkOsPrinter.GetAvailableSettings();
                foreach (string setting in availableSettings)
                {
                    Console.WriteLine($"{setting}: Range = ({linkOsPrinter.GetSettingRange(setting)})");
                }

                Console.WriteLine("\nCurrent Setting Values for myDevice");
                Dictionary <string, string> allSettingValues = linkOsPrinter.GetAllSettingValues();
                foreach (string settingName in allSettingValues.Keys)
                {
                    Console.WriteLine($"{settingName}:{allSettingValues[settingName]}");
                }

                string darknessSettingId = "print.tone";
                string newDarknessValue  = "10.0";
                if (availableSettings.Contains(darknessSettingId) &&
                    linkOsPrinter.IsSettingValid(darknessSettingId, newDarknessValue) &&
                    linkOsPrinter.IsSettingReadOnly(darknessSettingId) == false)
                {
                    linkOsPrinter.SetSetting(darknessSettingId, newDarknessValue);
                }

                Console.WriteLine($"\nNew {darknessSettingId} Value = {linkOsPrinter.GetSettingValue(darknessSettingId)}");
            }
        }
Ejemplo n.º 9
0
        public override ConnectionA GetConnection()
        {
            DiscoveredPrinterDriver        driverPrinter = null;
            List <DiscoveredPrinterDriver> printers      = UsbDiscoverer.GetZebraDriverPrinters();

            if (printers == null || printers.Count <= 0)
            {
                //MessageBox.Show("没有检测到打印机,请检查打印机是否开启!");
                myEventLog.LogInfo("没有检测到打印机,请检查打印机是否开启!");
                return(null);
            }
            driverPrinter = printers[0];

            var connection = new DriverPrinterConnection(driverPrinter.Address);

            connection.Open();
            try
            {
                ZebraPrinterFactory.GetInstance(connection);
            }
            catch (Exception ex)
            {
            }
            try
            {
                ZebraPrinterFactory.GetLinkOsPrinter(connection);
            }
            catch (Exception ex)
            {
            }



            return(connection);
        }
        private async void SendFileButton_Clicked(object sender, EventArgs eventArgs)
        {
            SetInputEnabled(false);

            string     filePath   = null;
            Connection connection = null;

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

                    ZebraPrinter printer = ZebraPrinterFactory.GetInstance(connection);

                    filePath = CreateDemoFile(printer.PrinterControlLanguage);
                    printer.SendFileContents(filePath);
                });
            } catch (Exception e) {
                await DisplayAlert("Error", e.Message, "OK");
            } finally {
                try {
                    connection?.Close();
                } catch (ConnectionException) { }

                if (filePath != null)
                {
                    try {
                        new FileInfo(filePath).Delete();
                    } catch (Exception) { }
                }

                SetInputEnabled(true);
            }
        }
Ejemplo n.º 11
0
        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();
            }
        }
Ejemplo n.º 12
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);
            }
        }
Ejemplo n.º 13
0
        private static void TestPrint()
        {
            var connection = new TcpConnection("192.168.2.3", 9100);

            try {
                connection.Open();
                var zebraPrinter = ZebraPrinterFactory.GetInstance(connection);


                var path   = $"{Directory.GetCurrentDirectory()}\\zpl\\biostoom.prn";
                var status = zebraPrinter?.GetCurrentStatus();
                if (status != null && status.isReadyToPrint)
                {
                    var zpl = FormatZpl(path);
                    connection.Write(Encoding.UTF8.GetBytes(zpl));
                }
                else
                {
                    // Do additional checks and log
                    // log status.isPaperOut
                }
            }
            catch (ConnectionException e) {
                Console.WriteLine(e.ToString());
            }
            finally {
                connection.Close();
            }
        }
Ejemplo n.º 14
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);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 获取ZebraPrinter
        /// </summary>
        /// <returns></returns>
        public ZebraPrinter GetPrinter()
        {
            if (TryOpenPrinterConnection())
            {
                if (printer != null && printer.Connection.Connected == false)
                {
                    myEventLog.LogInfo("Printer连接失败,重置Printer!");

                    lock (printerHelper)
                    {
                        printer = null;
                    }
                }
                if (printer == null)
                {
                    lock (connectionHelper)
                    {
                        try
                        {
                            printer = ZebraPrinterFactory.GetInstance(connection);
                        }
                        catch (Exception ex)
                        {
                            myEventLog.LogError("Printer连接出错:" + ex.Message, ex);
                        }
                    }
                }
            }
            return(printer);
        }
        /**
         * When a ZebraPrinterConnection has been established, this method
         * gets the printer and gathers information from the printer such as
         * the printer language and prints to the printer
         * **/

        private void threadedConnect(String addressName)
        {
            try
            {
                /**
                 * Open the connection
                 * **/
                connection.Open();
                Thread.Sleep(1000);
            }
            catch (ZebraPrinterConnectionException)
            {
                updateGuiFromWorkerThread("Unable to connect with printer", Color.Red);
                disconnect();
            }
            catch (Exception)
            {
                updateGuiFromWorkerThread("Error communicating with printer", Color.Red);
                disconnect();
            }

            printer = null;
            if (connection != null && connection.IsConnected())
            {
                /**
                 * Get the printer instance and the printer language, then print image
                 * **/
                try
                {
                    updateGuiFromWorkerThread("Getting printer...", Color.Goldenrod);
                    Thread.Sleep(1000);
                    printer = ZebraPrinterFactory.GetInstance(connection);
                    updateGuiFromWorkerThread("Got Printer, getting Language...", Color.LemonChiffon);
                    Thread.Sleep(1000);
                    PrinterLanguage pl = printer.GetPrinterControlLanguage();
                    updateGuiFromWorkerThread("Printer Language " + pl.ToString(), Color.LemonChiffon);
                    Thread.Sleep(1000);
                    updateGuiFromWorkerThread("Formatting Image", Color.AliceBlue);
                    printer.GetGraphicsUtil().PrintImage(image, 0, 0, 550, 412, false);
                    updateGuiFromWorkerThread("Printing To " + addressName, Color.Green);
                    Thread.Sleep(2000);
                    disconnect();
                }
                catch (ZebraPrinterConnectionException)
                {
                    updateGuiFromWorkerThread("Unknown Printer Language", Color.Red);
                    printer = null;
                    Thread.Sleep(1000);
                    disconnect();
                }
                catch (ZebraPrinterLanguageUnknownException)
                {
                    updateGuiFromWorkerThread("Unknown Printer Language", Color.Red);
                    printer = null;
                    Thread.Sleep(1000);
                    disconnect();
                }
            }
            updateButtonFromWorkerThread(true);
        }
        private static void PrintImage(string address, int port)
        {
            Connection connection = new TcpConnection(address, port);

            try
            {
                connection.Open();
                ZebraPrinter printer = ZebraPrinterFactory.GetInstance(PrinterLanguage.ZPL, connection);

                int x = 0;
                int y = 0;
                printer.PrintImage("data/mooncake.png", x, y);
            }
            catch (ConnectionException e)
            {
                Console.WriteLine(e.ToString());
            }
            catch (ZebraPrinterLanguageUnknownException e)
            {
                Console.WriteLine(e.ToString());
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 18
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);
                }
            }
        }
        /**
         * When a ZebraPrinterConnection has been established, this method
         * gets the printer and gathers information from the printer such as
         * the printer language.  ToolsUtil will then be used to default the printer.
         * **/

        private void threadedConnect(String addressName)
        {
            try
            {
                /**
                 * Open the connection
                 * **/
                connection.Open();
                Thread.Sleep(1000);
            }
            catch (ZebraPrinterConnectionException)
            {
                updateGuiFromWorkerThread("Unable to connect with printer", Color.Red);
                disconnect();
            }
            catch (Exception)
            {
                updateGuiFromWorkerThread("Error communicating with printer", Color.Red);
                disconnect();
            }

            printer = null;
            if (connection != null && connection.IsConnected())
            {
                /**
                 * Get the printer instance and the printer language, then do a factory default on the printer.
                 * **/
                try
                {
                    updateGuiFromWorkerThread("Getting printer...", Color.Goldenrod);
                    Thread.Sleep(1000);
                    printer = ZebraPrinterFactory.GetInstance(connection);
                    updateGuiFromWorkerThread("Got Printer, getting Language...", Color.LemonChiffon);
                    Thread.Sleep(1000);
                    PrinterLanguage pl = printer.GetPrinterControlLanguage();
                    updateGuiFromWorkerThread("Printer Language " + pl.ToString(), Color.LemonChiffon);
                    ToolsUtil printer_default = printer.GetToolsUtil();
                    printer_default.RestoreDefaults();
                    updateGuiFromWorkerThread("Restoring Defaults", Color.Aqua);
                    Thread.Sleep(1000);
                    disconnect();
                }
                catch (ZebraPrinterConnectionException)
                {
                    updateGuiFromWorkerThread("Unknown Printer Language", Color.Red);
                    printer = null;
                    Thread.Sleep(1000);
                    disconnect();
                }
                catch (ZebraPrinterLanguageUnknownException)
                {
                    updateGuiFromWorkerThread("Unknown Printer Language", Color.Red);
                    printer = null;
                    Thread.Sleep(1000);
                    disconnect();
                }
            }
        }
Ejemplo n.º 20
0
        //链接打印机
        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("");
        }
Ejemplo n.º 21
0
        /**
         * Common function used to open the connection depending on connection
         * type such as IP/DNS, Serial and Bluetooth(R). Sends a sample label
         * to print for checking connectivity and then close the connection.
         **/
        private void threadedConnect(String addressName)
        {
            // Open the connection
            try
            {
                connection.Open();
                Thread.Sleep(1000);
            }
            catch (ZebraPrinterConnectionException)
            {
                updateGuiFromWorkerThread("Unable to connect with printer", Color.Red);
                disconnect();
            }
            catch (Exception)
            {
                updateGuiFromWorkerThread("Error communicating with printer", Color.Red);
                disconnect();
            }

            printer = null;

            // If connection opened successfully than get the printer language and display it.
            // Also sends a sample lable to print and than close the connection.
            if (connection != null && connection.IsConnected())
            {
                try
                {
                    updateGuiFromWorkerThread("Getting printer...", Color.Goldenrod);
                    Thread.Sleep(1000);
                    printer = ZebraPrinterFactory.GetInstance(connection);
                    updateGuiFromWorkerThread("Got Printer, getting Language...", Color.LemonChiffon);
                    Thread.Sleep(1000);
                    PrinterLanguage pl = printer.GetPrinterControlLanguage();
                    updateGuiFromWorkerThread("Printer Language " + pl.ToString(), Color.LemonChiffon);
                    Thread.Sleep(1000);
                    updateGuiFromWorkerThread("Connected to " + addressName, Color.Green);
                    Thread.Sleep(1000);
                    sendLabel();
                    Thread.Sleep(1000);
                    disconnect();
                }
                catch (ZebraPrinterConnectionException)
                {
                    updateGuiFromWorkerThread("Unknown Printer Language", Color.Red);
                    printer = null;
                    Thread.Sleep(1000);
                    disconnect();
                }
                catch (ZebraPrinterLanguageUnknownException)
                {
                    updateGuiFromWorkerThread("Unknown Printer Language", Color.Red);
                    printer = null;
                    Thread.Sleep(1000);
                    disconnect();
                }
            }
        }
Ejemplo n.º 22
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] {
                    "", "", ""
                });
            }
        }
Ejemplo n.º 23
0
        /*
         * Connect to a printer using the Zebra API
         */
        private void ConnectToPrinter()
        {
            DiscoveredUsbPrinter discoveredPrinter = UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter())[0];
            Connection           connection        = discoveredPrinter.GetConnection();

            connection.Open();
            printer = ZebraPrinterFactory.GetInstance(connection);
            ConnectionLabel.Text = "Printer Connected!";
        }
Ejemplo n.º 24
0
        /**********************************************************************************
         * Desc: This sends the selected image file to zebra printer for printing.
         ***********************************************************************************/
        private void printImage(String filePath)
        {
            if (zebraPrinterConnection != null && macAddrBox.Text.Length == 12)
            {
                ZebraPrinter printer = ZebraPrinterFactory.GetInstance(zebraPrinterConnection);

                // Send image to print
                printer.GetGraphicsUtil().PrintImage(filePath, 0, 0, 550, 412, false);
            }
        }
        private void UpdateSettingsTable()
        {
            Connection connection = null;

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

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

                if (printer != null)
                {
                    Dictionary <string, Sdk.Settings.Setting> settings = printer.GetAllSettings();

                    Application.Current.Dispatcher.Invoke(() => {
                        if (settings != null)
                        {
                            foreach (string key in settings.Keys)
                            {
                                viewModel.Settings.Add(new Setting {
                                    Key = key, Value = settings[key].Value, Range = printer.GetSettingRange(key)
                                });
                            }
                        }
                        else
                        {
                            MessageBoxCreator.ShowError("Error reading settings", "Settings Error");
                        }

                        printerSettingsGrid.UnselectAll();
                    });
                }
                else
                {
                    MessageBoxCreator.ShowError("Connected printer does not support settings", "Connection Error");
                }
            } catch (ConnectionException e) {
                MessageBoxCreator.ShowError(e.Message, "Connection Error");
            } catch (ZebraPrinterLanguageUnknownException e) {
                MessageBoxCreator.ShowError(e.Message, "Connection Error");
            } catch (SettingsException e) {
                MessageBoxCreator.ShowError(e.Message, "Settings Error");
            } catch (Exception e) {
                MessageBoxCreator.ShowError(e.Message, "Save Settings Error");
            } finally {
                SetButtonStates(true);
                try {
                    if (connection != null)
                    {
                        connection.Close();
                    }
                } catch (ConnectionException) { }
            }
        }
Ejemplo n.º 26
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);
            }
        }
Ejemplo n.º 27
0
        private void commandPrint()
        {
            UsbConnection connection = null;

            try
            {
                DiscoveredUsbPrinter        usbPrinter = null;
                List <DiscoveredUsbPrinter> printers   = UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter());
                if (printers == null || printers.Count <= 0)
                {
                    MessageBox.Show("没有检测到打印机,请检查打印机是否开启!");
                    myEventLog.LogInfo("没有检测到打印机,请检查打印机是否开启!");
                    return;
                }
                usbPrinter = printers[0];

                connection = new UsbConnection(usbPrinter.Address);

                connection.Open();
                var printer = ZebraPrinterFactory.GetInstance(connection);

                //printer.SendCommand("~JA");


                var startTime = DateTime.Now;
                var command   = GetCommandFromDb();
                Console.WriteLine($"生成打印命令花费时间:{(DateTime.Now - startTime).TotalMilliseconds}ms");


                System.Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"));
                startTime = DateTime.Now;

                for (int i = 0; i < 20; i++)
                {
                    printer.SendCommand(command);
                    Console.WriteLine($"打印内容发送成功!花费时间:{(DateTime.Now - startTime).TotalMilliseconds}ms");
                    Thread.Sleep(200);
                    startTime = DateTime.Now;
                }
                //System.Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"));

                //printer.SendCommand(command);
                //Console.WriteLine($"打印内容发送成功!花费时间:{(DateTime.Now - startTime).TotalMilliseconds}ms");


                //Thread.Sleep(5000);

                //printer.SendCommand("~JA");
            }
            catch (Exception e)
            {
                connection.Close();
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Set Printer Parameters
        /// </summary>
        /// <returns>The printer.</returns>
        /// <param name="address">Address.</param>
        public static PrintResult SetDefaultPrinterSettings(string address)
        {
            var result = new PrintResult();

            IConnection connection = null;

            try
            {
                connection = new BluetoothConnectionInsecure(address);
                connection.Open();

                using (var printer = ZebraPrinterFactory.GetInstance(PrinterLanguage.Zpl, connection))
                {
                    // set printer to bluetooth classic only
                    printer.SendCommand("! U1 setvar \"bluetooth.le.controller_mode\" \"classic\"" + "\r\n");

                    // disable wifi
                    printer.SendCommand("! U1 setvar \"wlan.enable\" \"off\"" + "\r\n");

                    // disable wifi power save
                    printer.SendCommand("! U1 setvar \"wlan.power_save\" \"off\"" + "\r\n");

                    // disable bonding
                    printer.SendCommand("! U1 setvar \"bluetooth.bonding\" \"off\"" + "\r\n");

                    // disable sleep mode
                    printer.SendCommand("! U1 setvar \"power.sleep.enable\" \"off\"" + "\r\n");

                    // never power down due to inactivity
                    printer.SendCommand("! U1 setvar \"power.inactivity_timeout\" \"0\"" + "\r\n");

                    // set sleep timeout to 8 hours - not sure if sleep.enable = off overrides this?
                    printer.SendCommand("! U1 setvar \"power.sleep.timeout\" \"28000\"" + "\r\n");
                }

                result.Status = PrintStatus.Success;

                return(result);
            }
            catch (Exception exception)
            {
                Microsoft.AppCenter.Crashes.Crashes.TrackError(exception);
                result.Message = "Print failed. Check the printer is switched on and try again.";
                result.Status  = PrintStatus.PrintException;

                return(result);
            }
            finally
            {
                Thread.Sleep(SignaturePauseMilliseconds);
                connection.Close();
            }
        }
Ejemplo n.º 29
0
        private void GetFormatVariables(object sender, DoWorkEventArgs e)
        {
            object[] parameters               = e.Argument as object[];
            dynamic  selectedFormat           = parameters[0] as dynamic;
            string   lastFormatOpened         = (string)parameters[1];
            string   lastFormatOpenedSource   = (string)parameters[2];
            string   lastFormatOpenedContents = (string)parameters[3];

            object[] results = new object[4];

            long formatId = long.Parse(selectedFormat.FormatId);

            lastFormatOpened       = selectedFormat.FormatDrive + selectedFormat.FormatName + selectedFormat.FormatExtension;
            lastFormatOpenedSource = selectedFormat.FormatSource;

            try {
                OpenConnection();
                ZebraPrinterLinkOs printer = ZebraPrinterFactory.GetLinkOsPrinter(printerConnection);

                if (lastFormatOpenedSource.Equals("Sample") && formatId > 0)
                {
                    using (SavedFormatProvider provider = new SavedFormatProvider()) {
                        lastFormatOpenedContents = provider.GetFormatContents(formatId);
                    }
                }
                else
                {
                    byte[] formatInBytes = printer.RetrieveFormatFromPrinter(lastFormatOpened);
                    lastFormatOpenedContents = Encoding.UTF8.GetString(formatInBytes);
                }

                fieldDescDataVars = printer.GetVariableFields(lastFormatOpenedContents).ToList();
                fieldDescDataVars = FormatFieldDescriptionDataVars(fieldDescDataVars);

                formatVariableCollection = new ObservableCollection <FormatVariable>();
                for (int i = 0; i < fieldDescDataVars.Count; ++i)
                {
                    formatVariableCollection.Add(new FormatVariable {
                        FieldName = fieldDescDataVars[i].FieldName, FieldValue = ""
                    });
                }

                results[0] = lastFormatOpened;
                results[1] = lastFormatOpenedSource;
                results[2] = lastFormatOpenedContents;
                results[3] = formatVariableCollection;
                e.Result   = results;
            } catch (ConnectionException error) {
                errorMessage = "Connection Error: " + error.Message;
            } finally {
                CloseConnection();
            }
        }
Ejemplo n.º 30
0
        private void RetrieveFormatsFromPrinter(object sender, DoWorkEventArgs e)
        {
            List <SavedFormat> savedFormats = GetSavedFormats();

            foreach (SavedFormat format in savedFormats)
            {
                Dictionary <string, string> formatAttributes = new Dictionary <string, string> {
                    { attributeKeys[0], format.formatDrive },
                    { attributeKeys[1], format.formatName },
                    { attributeKeys[2], format.formatExtension },
                    { attributeKeys[3], "/Resources/btn_star_big_on.png" },
                    { FORMAT_SOURCE_KEY, format.sourcePrinterName },
                    { SavedFormat._ID, format.id.ToString() }
                };

                AddFormatToList(formatAttributes);
            }

            try {
                OpenConnection();
                ZebraPrinterLinkOs printer        = ZebraPrinterFactory.GetLinkOsPrinter(printerConnection);
                string[]           printerFormats = printer.RetrieveFileNames(new string[] { "ZPL" });
                foreach (string format in printerFormats)
                {
                    int colonPosition = format.IndexOf(":");
                    int dotPosition   = format.LastIndexOf(".");

                    if (dotPosition < 0)
                    {
                        dotPosition = format.Length;
                    }

                    string drive     = format.Substring(0, colonPosition + 1);
                    string extension = format.Substring(dotPosition);
                    string name      = format.Substring(colonPosition + 1, dotPosition - 2);

                    Dictionary <string, string> formatAttributes = new Dictionary <string, string> {
                        { attributeKeys[0], drive },
                        { attributeKeys[1], name },
                        { attributeKeys[2], extension },
                        { attributeKeys[3], "/Resources/btn_star_big_off.png" },
                        { FORMAT_SOURCE_KEY, FORMAT_SOURCE_PRINTER },
                        { SavedFormat._ID, "-1" }
                    };

                    AddFormatToList(formatAttributes);
                }
            } catch (ConnectionException error) {
                errorMessage = "Connection Error: " + error.Message;
            } finally {
                CloseConnection();
            }
        }