ZebraManger.cs 10.9 KB
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Management;
using Zebra.Sdk.Comm;
using Zebra.Sdk.Device;
using Zebra.Sdk.Graphics;
using Zebra.Sdk.Printer;
using Zebra.Sdk.Printer.Discovery;

namespace ZebraPrinterHelper
{
    public class ZebraManger
    {
       
        ConnectionType ConnectionType;
        string ConnectionEndpoint;
        public int PrinterDPI=203;
        /// <summary>
        /// 初始化打印机设置
        /// </summary>
        /// <param name="endpoint">连接地址</param>
        /// <param name="connectionType">连接类型</param>
        public ZebraManger(string endpoint, ConnectionType connectionType) {
            ConnectionEndpoint = endpoint;
            ConnectionType = connectionType;
        }
        Connection printerConnection = null;
        Connection GetConnection()
        {
            if (ConnectionType == ConnectionType.Network)
            {
                try
                {
                    int port = 9100;
                    return new TcpConnection(ConnectionEndpoint, port);
                }
                catch (Exception e)
                {
                    throw new ConnectionException(e.Message, e);
                }
            }
            else if (ConnectionType == ConnectionType.UsbDirect)
            {
                try
                {
                    return new UsbConnection(ConnectionEndpoint);
                }
                catch (Exception e)
                {
                    throw new ConnectionException(e.Message, e);
                }
            }
            else if (ConnectionType == ConnectionType.USB)
            {
                return new DriverPrinterConnection(ConnectionEndpoint);
            }
            else
            {
                try
                {
                    return new BluetoothConnection(ConnectionEndpoint);
                }
                catch (Exception e)
                {
                    throw new ConnectionException(e.Message, e);
                }
            }
        }
        /// <summary>
        /// 获取USB方式的endpoint地址
        /// </summary>
        /// <returns></returns>
       public static string GetUSBEndpoint()
        {
           return UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter())[0].Address;
        }
        /// <summary>
        /// 连接打印机
        /// </summary>
        /// <param name="msg">错误消息</param>
        /// <returns>是否成功</returns>
        public bool Connection(out string msg) {
            msg = "";
            try
            {
                printerConnection = GetConnection();
                printerConnection.Open();
                PrinterDPI = GetPrinterDPI();
                return true;
            }
            catch (ConnectionException e)
            {
                msg = "Connection Error:" + e.Message;
            }
            catch (ZebraPrinterLanguageUnknownException e)
            {
                msg = "Connection Error:" + e.Message;
            }
            catch (IOException e)
            {
                msg = "Image Error" + e.Message;
            }
            catch (ZebraIllegalArgumentException e)
            {
                msg = "Illegal Arguments" + e.Message;
            }
            catch (ArgumentException e)
            {
                msg = "Invalid File Path" + e.Message;
            }
            catch(Exception ex)
            {
                msg = "Unhandle Exception" + ex.Message;
            }
            finally
            {

            }
            return false;
        }
        /// <summary>
        /// 关闭打印机连接
        /// </summary>
        public void Close() {
            try
            {
                if (printerConnection != null)
                {
                    printerConnection.Close();
                    printerConnection = null;
                }
            }
            catch (ConnectionException)
            {
            }
            finally
            {

            }
        }
        ~ZebraManger() {
            Close();
        }
        /// <summary>
        /// 打印图像
        /// </summary>
        /// <param name="bmp"></param>
        /// <param name="msg">错误消息</param>
        /// <returns>是否成功</returns>
        public bool PrintImage(Bitmap bmp, out string msg)
        {
            msg = "";
             //CheckAndGetStatus(out PrinterStatus status, out msg);
            //if (!CheckAndGetStatus(out PrinterStatus status, out msg))
            //    return false;
            //CancelAll();

            //if (!status.isReadyToPrint)
            //{
            //    string[] printerStatusString = new PrinterStatusMessages(status).GetStatusMessage();

            //    msg = string.Join("\r\n", printerStatusString);
            //    return false;
            //}

            try
            {
                if (IsLabelOnPeeler)
                {
                    msg = "上一个标签尚未移走";
                    return false;
                }
                ZebraImageI image = ZebraImageFactory.GetImage(bmp);
                ZebraPrinterFactory.GetInstance(printerConnection).PrintImage(image, 0, 0, 0, 0, false);
                return true;
            }
            catch (ConnectionException e)
            {
                msg = "Connection Error:" + e.Message;
            }
            catch (ZebraPrinterLanguageUnknownException e)
            {
                msg = "Language Unknown:" + e.Message;
            }
            catch (IOException e)
            {
                msg = "Image Error" + e.Message;
            }
            catch (ZebraIllegalArgumentException e)
            {
                msg = "Illegal Arguments"+e.Message;
            }
            catch (ArgumentException e)
            {
                msg = "Invalid File Path" + e.Message;
            }
            return false;
        }
        bool CheckAndGetStatus(out PrinterStatus status, out string msg) {
            msg = "";
            status = null;
            //int ReTryCount = 0;
            //ReTry:
            if (printerConnection == null || !printerConnection.Connected)
            {
                if (!Connection(out string m))
                {
                    msg = m;
                    return false;
                }
            }
            status =  GetStatus();
            //if (status == null)
            //{
            //    ReTryCount++;
            //    if (ReTryCount > 3)
            //    {
            //        msg = "连接打印机失败";
            //        return false;
            //    }
            //    goto ReTry;
            //}

            return true;
        }
        /// <summary>
        /// 检测标签有没有被取走.
        /// 只在打印任务后可以检测 
        /// 发出打印指令后需等待打印完成约需要1秒才能检测到
        /// </summary>
        public bool IsLabelOnPeeler
        {
            get
            {
                try
                {
                    string d = "! U1 getvar \"sensor.peeler\"\n";
                    var b = Encoding.ASCII.GetBytes(d);
                    var rd = printerConnection.SendAndWaitForResponse(b, 1000, 500, null);
                    var rs = Encoding.ASCII.GetString(rd);
                    //log("sensor.peeler" + rs);
                    return rs.IndexOf("not clear") > -1;
                }
                catch {
                    return false;
                }
            }
        }
        /// <summary>
        /// 获取打印机打印精度DPI
        /// </summary>
        /// <returns></returns>
        public int GetPrinterDPI()
        {

            try
            {
                string d = "! U1 getvar \"head.resolution.in_dpi\"\n";
                var b = Encoding.ASCII.GetBytes(d);
                var rd = printerConnection.SendAndWaitForResponse(b, 5000, 500, null);
                var rs = Encoding.ASCII.GetString(rd);
                if (rs.Length > 0)
                {
                    rs = rs.Trim('\"');
                    return int.Parse(rs);
                }
                return 203;
            }
            catch
            {
                return 203;
            }

        }
        /// <summary>
        /// 取消所有任务
        /// </summary>
        public void CancelAll() {
            try
            {
                string d = "~JA\n";
                var b = Encoding.ASCII.GetBytes(d);
                printerConnection.Write(b);
            }
            catch
            {
            }
        }
        /// <summary>
        /// 打印机暂停模式
        /// </summary>
        public void PauseMode()
        {
            try
            {
                string d = "~PP\n";
                var b = Encoding.ASCII.GetBytes(d);
                printerConnection.Write(b);
            }
            catch
            {
            }
        }
        /// <summary>
        /// 从暂停模式恢复到正常模式
        /// </summary>
        public void PrintStartMode()
        {
            string d = "~PS\n";
            var b = Encoding.ASCII.GetBytes(d);
            printerConnection.Write(b);
        }
        public bool IsPrinterReady(out string msg) {
            msg = "";
            var status = GetStatus();
            string[] printerStatusString = new PrinterStatusMessages(status).GetStatusMessage();

            if (printerStatusString.Length > 0)
            {
                msg = string.Join("\r\n", printerStatusString);
                return false;
            }
            if (status.numberOfFormatsInReceiveBuffer > 0)
            {
                msg = "打印机缓冲池内有未打印文档";
                return false;
            }                
            return true;
        }
        /// <summary>
        /// 获取打印机状态
        /// </summary>
        /// <returns></returns>
        public PrinterStatus GetStatus() {
            if (printerConnection == null || !printerConnection.Connected)
            {
                if (!Connection(out string m))
                {
                    //msg = m;
                    //return false;
                }
            }
            try
            {
                ZebraPrinter printer = ZebraPrinterFactory.GetInstance(printerConnection);
                ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer);

                return (linkOsPrinter != null) ? linkOsPrinter.GetCurrentStatus() : printer.GetCurrentStatus();
            }
            catch {
                return null;
            }
        }
        
    }

    public enum ConnectionType
    {

        [Description("Network")]
        Network,

        [Description("USB")]
        USB,

        [Description("USB Direct")]
        UsbDirect,

        [Description("Bluetooth")]
        Bluetooth
    }
}