ZebraManger.cs 15.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
        ZebraPrinter printer;
        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
                {
                    if (string.IsNullOrEmpty(ConnectionEndpoint))
                    {

                        var dl = GetUsbDirectAddress();
                        if (dl.Count == 0)
                        {
                            new Exception("没有找到打印机");
                        }
                        ConnectionEndpoint = dl.First().Key;
                    }
                    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>
        /// 连接打印机
        /// </summary>
        /// <param name="msg">错误消息</param>
        /// <returns>是否成功</returns>
        public bool Connection(out string msg)
        {
            msg = "";
            try
            {
                Debug.WriteLine("Connection1");
                printerConnection = GetConnection();
                Debug.WriteLine("Connection2");
                printerConnection.Open();
                Debug.WriteLine("Connection3");
                PrinterDPI = GetPrinterDPI();
                Debug.WriteLine("Connection4");
                printer = ZebraPrinterFactory.GetInstance(printerConnection);
                Debug.WriteLine("Connection5");
                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 e)
            {
                msg = "Exception:" + e.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) {
            return PrintImage(bmp, out msg, true);
        }
        /// <summary>
        /// 打印图像
        /// </summary>
        /// <param name="bmp"></param>
        /// <param name="msg">错误消息</param>
        /// <param name="checkPeeler">是否检查剥离器</param>
        /// <returns>是否成功</returns>
        public bool PrintImage(Bitmap bmp, out string msg, bool checkPeeler, bool checkstatus = true) {
            return PrintImage(bmp, bmp.Width, bmp.Height, out msg, checkPeeler, checkstatus);
        }
        public bool PrintImage(Bitmap bmp,int width, int height, out string msg,bool checkPeeler,bool checkstatus=true)
        {
            msg = "";
            Debug.WriteLine("StartPrintImage");
            if (checkstatus)
            {
                if (!CheckAndGetStatus(out PrinterStatus status, out msg))
                    return false;
                Debug.WriteLine("CheckAndGetStatus");
                if (status.labelsRemainingInBatch > 0)
                    CancelAll();
                Debug.WriteLine("labelsRemainingInBatch");
                if (!status.isReadyToPrint)
                {
                    string[] printerStatusString = new PrinterStatusMessages(status).GetStatusMessage();

                    msg = string.Join("\r\n", printerStatusString);
                    return false;
                }
                Debug.WriteLine("isReadyToPrint");
                if (checkPeeler && IsLabelOnPeeler)
                {
                    msg = "上一个标签尚未移走";
                    return false;
                }
                Debug.WriteLine("IsLabelOnPeeler");
            }
            try
            {
                //var width = bmp.Width * ((double)PrinterDPI / 300);
                //var height = bmp.Height * ((double)PrinterDPI / 300);
                //var db = GetReducedImage(bmp, (int)width, (int)height);
                //db.Save("temp.bmp");
                ZebraImageI image = ZebraImageFactory.GetImage(bmp);
                Debug.WriteLine("ZebraImageFactory.GetImage");
                printer.PrintImage(image, 0, 0, (int)bmp.Width, (int)bmp.Height, false);
                return true;
            }
            catch (ConnectionException e)
            {
                msg = "Connection Error:" + e.ToString();
            }
            catch (ZebraPrinterLanguageUnknownException e)
            {
                msg = "Language Unknown:" + e.ToString();
            }
            catch (IOException e)
            {
                msg = "Image Error" + e.ToString();
            }
            catch (ZebraIllegalArgumentException e)
            {
                msg = "Illegal Arguments:" + e.ToString();
            }
            catch (ArgumentException e)
            {
                msg = "Invalid File Path:" + e.ToString();
            }
            catch (Exception e)
            {
                msg = "Exception:" + e.Message;
            }
            finally
            {

            }
            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;
                }
            }
            Debug.WriteLine("StartGetStatus");
            status = GetStatus();
            if (status == null)
            {
                Debug.WriteLine("GetStatusAgain");
                status = GetStatus();
                if (status == null)
                {
                    Close();
                    ReTryCount++;
                    if (ReTryCount > 3)
                    {
                        msg = "连接打印机失败";
                        return false;
                    }
                    goto ReTry;
                }
            }
            Debug.WriteLine("isPaused");
            ReTryCount = 0;
            if (status.isPaused)
            {
                PrintStartMode();
                ReTryCount++;
                if (ReTryCount > 2)
                {
                    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, 5000, 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()
        {

            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);
            }
            else
            {
                throw new ZebraPrinterLanguageUnknownException("Get DPI Error!");
            }
            return 203;

        }
        /// <summary>
        /// 取消所有任务
        /// </summary>
        public void CancelAll()
        {
            try
            {
                string d = "~JA\n";
                var b = Encoding.ASCII.GetBytes(d);
                printerConnection.Write(b);
            }
            catch
            {
            }
        }
        /// <summary>
        /// 写入ZPL指令
        /// </summary>
        /// <param name="zplcommand"></param>
        public void WriteZPL(string zplcommand)
        {
            var b = Encoding.ASCII.GetBytes(zplcommand);
            printerConnection.Write(b);
        }
        /// <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)
            {
                Debug.WriteLine("ReConnection");
                if (!Connection(out string m))
                {
                    //msg = m;
                    //return false;
                }
            }
            try
            {
                Debug.WriteLine("GetCurrentStatus");
                return printer.GetCurrentStatus();
                //ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.CreateLinkOsPrinter(printer);
                //Debug.WriteLine("linkOsPrinter:"+ linkOsPrinter==null);
                //return (linkOsPrinter != null) ? linkOsPrinter.GetCurrentStatus() : printer.GetCurrentStatus();
            }
            catch(Exception ex)
            {
                Debug.WriteLine("GetCurrentStatusError:"+ex);
                return null;
            }
        }
        public static Dictionary<string, Dictionary<string, string>> GetUsbDirectAddress()
        {
            var devicelist = new Dictionary<string, Dictionary<string, string>>();
            foreach (DiscoveredUsbPrinter printer in UsbDiscoverer.GetZebraUsbPrinters(new ZebraPrinterFilter()))
            {
                devicelist[printer.Address] = printer.DiscoveryDataMap;
            }
            return devicelist;
        }
        private Image GetReducedImage(Image resourceImage, int width, int height)
        {
            try
            {
                Image data = null;
                //用指定的大小和格式初始化Bitmap类的新实例 
                using (Bitmap bitmap = new Bitmap(width, height, resourceImage.PixelFormat))
                {
                    //从指定的Image对象创建新Graphics对象 
                    using (Graphics graphics = Graphics.FromImage(bitmap))
                    {
                        //清除整个绘图面并以透明背景色填充 
                        //graphics.Clear(Color.Transparent);
                        //在指定位置并且按指定大小绘制原图片对象
                        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
                        //graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
                        graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
                        graphics.DrawImage(resourceImage, new Rectangle(0, 0, width, height));
                    }
                    data = new Bitmap(bitmap);
                }
                return data;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }


    public enum ConnectionType
    {

        [Description("Network")]
        Network,

        [Description("USB")]
        USB,

        [Description("USB Direct")]
        UsbDirect,

        [Description("Bluetooth")]
        Bluetooth
    }
}