Пример #1
0
        public static void PrintReceipt(Horeka.Data.Occupancy occupancy)
        {
            try
            {
                if (occupancy != null)
                {
                    bool portExists = SerialPort.GetPortNames().Any(x => x == "COM7");

                    if (portExists)
                    {
                        printer = new SerialPrinter("COM7", 115200);
                        e       = new EPSON();
                        Setup();
                        printer.Write(Receipt.GetReceiptHeader(e, occupancy));
                        WriteProducts(occupancy);
                        printer.Write(Receipt.GetReceiptFooter(e));
                        Setup();
                        printer.Write(e.PartialCutAfterFeed(10));
                    }
                    else
                    {
                        throw new IOException("Port does not exist.");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Пример #2
0
        private static void PrintBase(Base baseToPrint, bool draft)
        {
            _log.Info("Print Controller printing Base: " + baseToPrint.Artifact.Name);

            var trimName = ModelMap.GetBaseFolderName(baseToPrint.TokenType, baseToPrint.TokenUnit,
                                                      baseToPrint.RepresentationType);

            _outputFolder = ModelMap.FilePath + ModelMap.BaseFolder + ModelMap.FolderSeparator + trimName +
                            ModelMap.FolderSeparator + ModelMap.Latest;
            _filePath = _outputFolder + ModelMap.FolderSeparator + trimName + ".docx";
            try
            {
                Directory.CreateDirectory(_outputFolder);
                InitWorkingDocument(ModelMap.StyleSource);
            }
            catch (Exception ex)
            {
                _log.Error("Artifact Output Folder: " + _outputFolder + " cannot be created.");
                _log.Error(ex);
                return;
            }
            BasePrinter.PrintTokenBase(_document, baseToPrint, false);
            Utils.InsertCustomWatermark(_document, draft ? ModelMap.DraftWaterMark : ModelMap.WaterMark);
            Utils.AddFooter(_document, baseToPrint.Artifact.Name);
            Save();
        }
Пример #3
0
        public Tuple <bool, Exception> Print(string printerName, BasePrinter entity, MarginModel horiModel = null)
        {
            var tuple = new Tuple <bool, Exception>(true, null);

            try
            {
                if (horiModel == null)
                {
                    horiModel = new MarginModel()
                    {
                        LeftMargin = 0, RightMargin = 0
                    }
                }
                ;
                PrintController pc = new StandardPrintController();
                var             pd = new PrintDocument
                {
                    PrintController     = pc,
                    DefaultPageSettings =
                    {
                        Margins = new Margins((int)(horiModel.LeftMargin / 25.4 * 100),
                                              (int)(horiModel.RightMargin / 25.4 * 100), 0, 0)
                    },
                    OriginAtMargins = true
                };
                pd.PrintPage += (s, e) => Pdoc_PrintPage(e, entity);
                pd.PrinterSettings.PrinterName = printerName;
                pd.Print();
            }
            catch (Exception ex)
            {
                return(new Tuple <bool, Exception>(false, ex));
            }
            return(tuple);
        }
Пример #4
0
        private void Pdoc_PrintPage(PrintPageEventArgs e, BasePrinter pt)
        {
            //e.PageBounds 纸张大小
            //e.PageSettings.PrintableArea 可打印边距、物理边距
            //e.MarginBounds 软件边距
            var graphics          = e.Graphics;
            var width             = e.MarginBounds.Width; //整个页面的大小 189 (1/100inch)
            var sheetPrintManager = new SheetPrintManager(width, 0);

            //_log.Trace($"visit id: {pt.Id} begin printing");
            sheetPrintManager.Print(pt.GetPrintModel(pt), graphics);
        }
Пример #5
0
    public void TestMethod()
    {
        var basePrinter  = this.GetPrinter("base");
        var childPrinter = this.GetPrinter("child");

        basePrinter.PrintIt();
        childPrinter.PrintIt();
        Console.WriteLine($"{basePrinter.SomeBaseFunc()} == {childPrinter.SomeBaseFunc()}");

        var baseP2  = new BasePrinter();
        var childP2 = new ChildPrinter();

        Console.WriteLine($"{baseP2.NumValue} == {childP2.NumValue}");
    }
        /// <summary>
        /// Public method call for print
        /// </summary>
        /// <param name="printer">printer for print</param>
        /// <param name="stream">data stream</param>
        public void Print(BasePrinter printer, Stream stream)
        {
            if (printer == null)
            {
                throw new ArgumentNullException($"Argument {nameof(printer)} is null");
            }

            if (stream == null)
            {
                throw new ArgumentNullException($"Argument {nameof(printer)} is null");
            }

            if (!this.Contains(printer))
            {
                throw new ExistPrinterException($"Printer {nameof(printer)} is absent in list. Please add new printer and than print");
            }

            printer.Print(stream);
        }
Пример #7
0
        /// <summary>
        /// 每个派生类都要实现的打印方法
        /// </summary>
        /// <param name="pt"></param>
        /// <returns></returns>
        public override IList <PrintBaseEntity> GetPrintModel(BasePrinter pt)
        {
            PrintTest entity = pt as PrintTest;

            return(new List <PrintBaseEntity>()
            {
                GenTitle(entity.Title, BasePrinter.LargerFont),
                GenDashLine(),
                GenRow("Row1:", entity.Row1),
                GenRow("Row2:", entity.Row2),
                GenDashLine(),
                GenRow("Row3:", entity.Row3),
                GenRow("Row4:", entity.Row4),
                GenRow("Row5:", entity.Row5),
                GenRow("Row6:", entity.Row6),
                GenRow("Row7:", entity.Row7),
                GenRow("Row7:", entity.Row7),
                GenRow("DeskNo:", entity.DeskNo),
                GenRow("BeginAt:", entity.BeginAt.ToShortDateString()),
                GenRow("FinalMoney:", entity.FinalMoney.ToString())
            });
        }
Пример #8
0
        public Tuple <bool, Exception> PrintTest(string printerName)
        {
            var tuple = new Tuple <bool, Exception>(true, null);

            #region  总写的
            try
            {
                PrintController pc = new StandardPrintController();
                var             pd = new PrintDocument
                {
                    PrintController     = pc,
                    DefaultPageSettings =
                    {
                        Margins = new Margins(0, 0, 0, 0)
                    },
                    OriginAtMargins = true
                };
                BasePrinter entity = new BasePrinter()
                {
                    Title      = "测试",
                    DeskNo     = "666",
                    BeginAt    = DateTime.Now,
                    FinalMoney = Decimal.MaxValue,
                    ExtraStr   = "这是打印测试"
                };
                pd.PrintPage += (s, e) => Pdoc_PrintPage(e, entity);
                pd.PrinterSettings.PrinterName = printerName;
                pd.Print();
            }
            catch (Exception ex)
            {
                return(new Tuple <bool, Exception>(false, ex));
            }


            #endregion
            return(tuple);
        }
Пример #9
0
        /// <summary>
        /// This will create a single OpenXML document.  After it is created, it should be opened and a new Table of Contents before printing to PDF.
        /// </summary>
        internal static PrintResult BuildTtfBook(bool draft)
        {
            var styleSource = ModelMap.StyleSource;

            _filePath = ModelMap.FilePath + ModelMap.FolderSeparator + ".." + ModelMap.FolderSeparator + "TTF-Book.docx";
            try
            {
                InitWorkingDocument(styleSource);
                _document.MainDocumentPart.Document.AppendChild(new Body());
            }
            catch (Exception ex)
            {
                _log.Error("Artifact Output Folder: " + _outputFolder + " cannot be created.");
                _log.Error(ex);
                return(new PrintResult
                {
                    OpenXmlDocument = ""
                });
            }

            CommonPrinter.AddTaxonomyInfo(_document, ModelManager.Taxonomy.Version);

            _log.Info("Adding Bases");
            CommonPrinter.AddSectionPage(_document, "Base Tokens");
            foreach (var b in ModelManager.Taxonomy.BaseTokenTypes.Values)
            {
                BasePrinter.PrintTokenBase(_document, b, true);
            }
            Save();

            _log.Info("Adding Behaviors");
            CommonPrinter.AddSectionPage(_document, "Behaviors");
            foreach (var b in ModelManager.Taxonomy.Behaviors.Values)
            {
                BehaviorPrinter.PrintBehavior(_document, b, true);
            }
            Save();

            _log.Info("Adding Behavior-Groups");
            CommonPrinter.AddSectionPage(_document, "Behavior Groups");
            foreach (var b in ModelManager.Taxonomy.BehaviorGroups.Values)
            {
                BehaviorGroupPrinter.PrintBehaviorGroup(_document, b, true);
            }
            Save();

            _log.Info("Adding Property-Sets");
            CommonPrinter.AddSectionPage(_document, "Property Sets");
            foreach (var ps in ModelManager.Taxonomy.PropertySets.Values)
            {
                PropertySetPrinter.AddPropertySetProperties(_document, ps, true);
            }
            Save();

            _log.Info("Adding Template Formulas");
            CommonPrinter.AddSectionPage(_document, "Template Formulas");
            foreach (var tf in ModelManager.Taxonomy.TemplateFormulas.Values)
            {
                FormulaPrinter.PrintFormula(_document, tf, true);
            }
            Save();

            _log.Info("Adding Template Definitions");
            CommonPrinter.AddSectionPage(_document, "Template Definitions");
            foreach (var td in ModelManager.Taxonomy.TemplateDefinitions.Values)
            {
                DefinitionPrinter.PrintDefinition(_document, td, true);
            }
            Save();

            _log.Info("Adding Specifications");
            CommonPrinter.AddSectionPage(_document, "Token Specifications");
            foreach (var tf in ModelManager.Taxonomy.TemplateDefinitions.Keys)
            {
                var spec = Printer.TaxonomyClient.GetTokenSpecification(new TokenTemplateId
                {
                    DefinitionId = tf
                });
                if (spec == null)
                {
                    continue;
                }
                SpecificationPrinter.PrintSpecification(_document, spec);
            }
            Save();

            Utils.InsertCustomWatermark(_document, draft ? ModelMap.DraftWaterMark : ModelMap.WaterMark);
            Utils.AddFooter(_document, "Token Taxonomy Framework" + " - " + ModelManager.Taxonomy.Version.Version + ": " + ModelManager.Taxonomy.Version.StateHash);
            Save();
            return(GetPrintResult());
        }
        /// <summary>
        /// Check contains printer in printer`s list
        /// </summary>
        /// <param name="printer">instance class printer</param>
        /// <returns>true if contains</returns>
        public bool Contains(BasePrinter printer)
        {
            var equalityComparer = EqualityComparer <BasePrinter> .Default;

            return(this.printers.Contains(printer, equalityComparer));
        }
Пример #11
0
 public override IList <PrintBaseEntity> GetPrintModel(BasePrinter pt)
 {
     throw new NotImplementedException();
 }
Пример #12
0
        private static void Main(string[] args)
        {
            Console.WriteLine("ESCPOS_NET Test Application...");
            Console.WriteLine("1 ) Test Serial Port");
            Console.WriteLine("2 ) Test Network Printer");
            Console.Write("Choice: ");
            var    comPort = "";
            string baudRate;
            string ip;
            string networkPort;
            var    response = Console.ReadLine();
            var    valid    = new List <string> {
                "1", "2"
            };

            if (!valid.Contains(response))
            {
                response = "1";
            }

            var choice = int.Parse(response);

            if (choice == 1)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    while (!comPort.StartsWith("COM"))
                    {
                        Console.Write("COM Port (eg. COM5): ");
                        comPort = Console.ReadLine();
                        if (string.IsNullOrWhiteSpace(comPort))
                        {
                            comPort = "COM5";
                        }
                    }

                    Console.Write("Baud Rate (eg. 115200): ");
                    baudRate = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(baudRate))
                    {
                        baudRate = "115200";
                    }
                    printer = new SerialPrinter(comPort, 115200);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Console.Write("File / virtual com path (eg. /dev/usb/lp0): ");
                    comPort = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(comPort))
                    {
                        comPort = "/dev/usb/lp0";
                    }
                    printer = new FilePrinter(comPort);
                }
            }
            else if (choice == 2)
            {
                Console.Write("IP Address (eg. 192.168.1.240): ");
                ip = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(ip))
                {
                    ip = "192.168.1.240";
                }
                Console.Write("TCP Port (eg. 9000): ");
                networkPort = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(networkPort))
                {
                    networkPort = "9000";
                }
                printer = new NetworkPrinter(ip, int.Parse(networkPort), true);
            }

            var monitor = false;

            Console.Write("Turn on Live Status Back Monitoring? (y/n): ");
            response = Console.ReadLine().Trim().ToLowerInvariant();
            if (response.Length >= 1 && response[0] == 'y')
            {
                monitor = true;
            }

            e = new EPSON();
            var testCases = new Dictionary <Option, string>
            {
                { Option.Printing, "Printing" },
                { Option.LineSpacing, "Line Spacing" },
                { Option.BarcodeStyles, "Barcode Styles" },
                { Option.BarcodeTypes, "Barcode Types" },
                { Option.TwoDimensionCodes, "2D Codes" },
                { Option.TextStyles, "Text Styles" },
                { Option.FullReceipt, "Full Receipt" },
                { Option.Images, "Images" },
                { Option.LegacyImages, "Legacy Images" },
                { Option.LargeByteArrays, "Large Byte Arrays" },
                { Option.CashDrawerPin2, "Cash Drawer Pin2" },
                { Option.CashDrawerPin5, "Cash Drawer Pin5" },
                { Option.Exit, "Exit" }
            };

            while (true)
            {
                foreach (var item in testCases)
                {
                    Console.WriteLine($"{(int) item.Key} : {item.Value}");
                }
                Console.Write("Execute Test: ");

                if (!int.TryParse(Console.ReadLine(), out choice) || !Enum.IsDefined(typeof(Option), choice))
                {
                    Console.WriteLine("Invalid entry. Please try again.");
                    continue;
                }

                var enumChoice = (Option)choice;
                if (enumChoice == Option.Exit)
                {
                    return;
                }

                Console.Clear();

                if (monitor)
                {
                    printer.StartMonitoring();
                }
                Setup(monitor);

                printer?.Write(e.PrintLine($"== [ Start {testCases[enumChoice]} ] =="));

                switch (enumChoice)
                {
                case Option.Printing:
                    printer.Write(Tests.Printing(e));
                    break;

                case Option.LineSpacing:
                    printer.Write(Tests.LineSpacing(e));
                    break;

                case Option.BarcodeStyles:
                    printer.Write(Tests.BarcodeStyles(e));
                    break;

                case Option.BarcodeTypes:
                    printer.Write(Tests.BarcodeTypes(e));
                    break;

                case Option.TwoDimensionCodes:
                    printer.Write(Tests.TwoDimensionCodes(e));
                    break;

                case Option.TextStyles:
                    printer.Write(Tests.TextStyles(e));
                    break;

                case Option.FullReceipt:
                    printer.Write(Tests.Receipt(e));
                    break;

                case Option.Images:
                    printer.Write(Tests.Images(e, false));
                    break;

                case Option.LegacyImages:
                    printer.Write(Tests.Images(e, true));
                    break;

                case Option.LargeByteArrays:
                    try
                    {
                        printer.Write(Tests.TestLargeByteArrays(e));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(
                            $"Aborting print due to test failure. Exception: {e?.Message}, Stack Trace: {e?.GetBaseException()?.StackTrace}");
                    }

                    break;

                case Option.CashDrawerPin2:
                    printer.Write(Tests.CashDrawerOpenPin2(e));
                    break;

                case Option.CashDrawerPin5:
                    printer.Write(Tests.CashDrawerOpenPin5(e));
                    break;

                default:
                    Console.WriteLine("Invalid entry.");
                    break;
                }

                Setup(monitor);
                printer?.Write(e.PrintLine($"== [ End {testCases[enumChoice]} ] =="));
                printer?.Write(e.PartialCutAfterFeed(5));

                // TODO: write a sanitation check.
                // TODO: make DPI to inch conversion function
                // TODO: full cuts and reverse feeding not implemented on epson...  should throw exception?
                // TODO: make an input loop that lets you execute each test separately.
                // TODO: also make an automatic runner that runs all tests (command line).
                //Thread.Sleep(1000);
            }
        }
Пример #13
0
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to the ESCPOS_NET Test Application!");
            Console.Write("Would you like to see all debug messages? (y/n): ");
            var response = Console.ReadLine().Trim().ToLowerInvariant();
            var logLevel = LogLevel.Information;

            if (response.Length >= 1 && response[0] == 'y')
            {
                Console.WriteLine("Debugging enabled!");
                logLevel = LogLevel.Trace;
            }
            var factory = LoggerFactory.Create(b => b.AddConsole().SetMinimumLevel(logLevel));
            var logger  = factory.CreateLogger <Program>();

            ESCPOS_NET.Logging.Logger = logger;

            Console.WriteLine("1 ) Test Serial Port");
            Console.WriteLine("2 ) Test Network Printer");
            Console.Write("Choice: ");
            string comPort = "";
            string baudRate;
            string ip;
            string networkPort;

            response = Console.ReadLine();
            var valid = new List <string> {
                "1", "2"
            };

            if (!valid.Contains(response))
            {
                response = "1";
            }

            int choice = int.Parse(response);

            if (choice == 1)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    while (!comPort.StartsWith("COM"))
                    {
                        Console.Write("COM Port (enter for default COM5): ");
                        comPort = Console.ReadLine();
                        if (string.IsNullOrWhiteSpace(comPort))
                        {
                            comPort = "COM5";
                        }
                    }
                    Console.Write("Baud Rate (enter for default 115200): ");
                    baudRate = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(baudRate))
                    {
                        baudRate = "115200";
                    }
                    printer = new SerialPrinter(portName: comPort, baudRate: 115200);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Console.Write("File / virtual com path (eg. /dev/usb/lp0): ");
                    comPort = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(comPort))
                    {
                        comPort = "/dev/usb/lp0";
                    }
                    printer = new FilePrinter(filePath: comPort, false);
                }
            }
            else if (choice == 2)
            {
                Console.Write("IP Address (eg. 192.168.1.240): ");
                ip = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(ip))
                {
                    ip = "192.168.254.202";
                }
                Console.Write("TCP Port (enter for default 9100): ");
                networkPort = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(networkPort))
                {
                    networkPort = "9100";
                }
                printer = new NetworkPrinter(ipAddress: ip, port: int.Parse(networkPort), reconnectOnTimeout: true);
            }

            bool monitor = false;

            Thread.Sleep(500);
            Console.Write("Turn on Live Status Back Monitoring? (y/n): ");
            response = Console.ReadLine().Trim().ToLowerInvariant();
            if (response.Length >= 1 && response[0] == 'y')
            {
                monitor = true;
            }

            e = new EPSON();
            var testCases = new Dictionary <Option, string>()
            {
                { Option.SingleLinePrinting, "Single Line Printing" },
                { Option.MultiLinePrinting, "Multi-line Printing" },
                { Option.LineSpacing, "Line Spacing" },
                { Option.BarcodeStyles, "Barcode Styles" },
                { Option.BarcodeTypes, "Barcode Types" },
                { Option.TwoDimensionCodes, "2D Codes" },
                { Option.TextStyles, "Text Styles" },
                { Option.FullReceipt, "Full Receipt" },
                { Option.CodePages, "Code Pages (Euro, Katakana, Etc)" },
                { Option.Images, "Images" },
                { Option.LegacyImages, "Legacy Images" },
                { Option.LargeByteArrays, "Large Byte Arrays" },
                { Option.CashDrawerPin2, "Cash Drawer Pin2" },
                { Option.CashDrawerPin5, "Cash Drawer Pin5" },
                { Option.Exit, "Exit" }
            };

            while (true)
            {
                foreach (var item in testCases)
                {
                    Console.WriteLine($"{(int)item.Key} : {item.Value}");
                }
                Console.Write("Execute Test: ");

                if (!int.TryParse(Console.ReadLine(), out choice) || !Enum.IsDefined(typeof(Option), choice))
                {
                    Console.WriteLine("Invalid entry. Please try again.");
                    continue;
                }

                var enumChoice = (Option)choice;
                if (enumChoice == Option.Exit)
                {
                    return;
                }

                Console.Clear();

                if (monitor)
                {
                    printer.StartMonitoring();
                }
                Setup(monitor);

                printer?.Write(e.PrintLine($"== [ Start {testCases[enumChoice]} ] =="));

                switch (enumChoice)
                {
                case Option.SingleLinePrinting:
                    printer.Write(Tests.SingleLinePrinting(e));
                    break;

                case Option.MultiLinePrinting:
                    printer.Write(Tests.MultiLinePrinting(e));
                    break;

                case Option.LineSpacing:
                    printer.Write(Tests.LineSpacing(e));
                    break;

                case Option.BarcodeStyles:
                    printer.Write(Tests.BarcodeStyles(e));
                    break;

                case Option.BarcodeTypes:
                    printer.Write(Tests.BarcodeTypes(e));
                    break;

                case Option.TwoDimensionCodes:
                    printer.Write(Tests.TwoDimensionCodes(e));
                    break;

                case Option.TextStyles:
                    printer.Write(Tests.TextStyles(e));
                    break;

                case Option.FullReceipt:
                    printer.Write(Tests.Receipt(e));
                    break;

                case Option.Images:
                    printer.Write(Tests.Images(e, false));
                    break;

                case Option.LegacyImages:
                    printer.Write(Tests.Images(e, true));
                    break;

                case Option.LargeByteArrays:
                    try
                    {
                        printer.Write(Tests.TestLargeByteArrays(e));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Aborting print due to test failure. Exception: {e?.Message}, Stack Trace: {e?.GetBaseException()?.StackTrace}");
                    }
                    break;

                case Option.CashDrawerPin2:
                    printer.Write(Tests.CashDrawerOpenPin2(e));
                    break;

                case Option.CashDrawerPin5:
                    printer.Write(Tests.CashDrawerOpenPin5(e));
                    break;

                default:
                    Console.WriteLine("Invalid entry.");
                    break;
                }

                Setup(monitor);
                printer?.Write(e.PrintLine($"== [ End {testCases[enumChoice]} ] =="));
                printer?.Write(e.PartialCutAfterFeed(5));

                // TODO: also make an automatic runner that runs all tests (command line).
            }
        }
Пример #14
0
        static void Main(string[] args)
        {
            Console.WriteLine("ESCPOS_NET Test Application...");
            Console.WriteLine("1 ) Test Serial Port");
            Console.WriteLine("2 ) Test Network Printer");
            Console.Write("Choice: ");
            string comPort = "";
            string baudRate;
            string ip;
            string networkPort;
            var    response = Console.ReadLine();
            var    valid    = new List <string> {
                "1", "2"
            };

            if (!valid.Contains(response))
            {
                response = "1";
            }
            int choice = int.Parse(response);

            if (choice == 1)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    while (!comPort.StartsWith("COM"))
                    {
                        Console.Write("COM Port (eg. COM20): ");
                        comPort = Console.ReadLine();
                        if (string.IsNullOrWhiteSpace(comPort))
                        {
                            comPort = "COM20";
                        }
                    }
                    Console.Write("Baud Rate (eg. 115200): ");
                    baudRate = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(baudRate))
                    {
                        baudRate = "115200";
                    }
                    printer = new SerialPrinter(comPort, int.Parse(baudRate));
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Console.Write("File / virtual com path (eg. /dev/usb/lp0): ");
                    comPort = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(comPort))
                    {
                        comPort = "/dev/usb/lp0";
                    }
                    printer = new FilePrinter(comPort);
                }
            }
            else if (choice == 2)
            {
                Console.Write("IP Address (eg. 192.168.1.240): ");
                ip = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(ip))
                {
                    ip = "192.168.1.240";
                }
                Console.Write("TCP Port (eg. 9000): ");
                networkPort = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(networkPort))
                {
                    networkPort = "9000";
                }
                printer = new NetworkPrinter(ip, int.Parse(networkPort));
            }

            bool monitor = false;

            Console.Write("Turn on Live Status Back Monitoring? (y/n): ");
            response = Console.ReadLine().Trim().ToLowerInvariant();
            if (response.Length >= 1 && response[0] == 'y')
            {
                monitor = true;
            }

            e = new EPSON();
            List <string> testCases = new List <string>()
            {
                "Printing",
                "Line Spacing",
                "Barcode Styles",
                "Text Styles",
                "Full Receipt"
            };

            while (true)
            {
                int i = 0;
                foreach (var item in testCases)
                {
                    i += 1;
                    Console.WriteLine($"{i} : {item}");
                }
                Console.WriteLine("99 : Exit");
                Console.Write("Execute Test: ");

                try
                {
                    choice = Convert.ToInt32(Console.ReadLine());
                    if (choice != 99 && (choice < 1 || choice > testCases.Count))
                    {
                        throw new InvalidOperationException();
                    }
                }
                catch
                {
                    Console.WriteLine("Invalid entry. Please try again.");
                    continue;
                }

                if (choice == 99)
                {
                    return;
                }

                Console.Clear();

                if (monitor)
                {
                    printer.StartMonitoring();
                }
                Setup();
                printer.Write(e.PrintLine($"== [ Start {testCases[choice - 1]} ] =="));

                switch (choice)
                {
                case 1:
                    printer.Write(Tests.Printing(e));
                    break;

                case 2:
                    printer.Write(Tests.LineSpacing(e));
                    break;

                case 3:
                    printer.Write(Tests.BarcodeStyles(e));
                    break;

                case 4:
                    printer.Write(Tests.TextStyles(e));
                    break;

                case 5:
                    printer.Write(Tests.Receipt(e));
                    break;

                default:
                    Console.WriteLine("Invalid entry.");
                    break;
                }

                Setup();
                printer.Write(e.PrintLine($"== [ End {testCases[choice - 1]} ] =="));
                printer.Write(e.PartialCutAfterFeed(5));

                //TestCutter();
                //TestMultiLineWrite();
                //TestHEBReceipt();
                // TODO: write a sanitation check.
                // TODO: make DPI to inch conversion function
                // TODO: full cuts and reverse feeding not implemented on epson...  should throw exception?
                // TODO: make an input loop that lets you execute each test separately.
                // TODO: also make an automatic runner that runs all tests (command line).
                //Thread.Sleep(1000);
            }
        }
Пример #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("ESCPOS_NET Test Application...");
            Console.WriteLine("1 ) Test Serial Port");
            Console.WriteLine("2 ) Test Network Printer");
            Console.Write("Choice: ");
            string comPort = "";
            string baudRate;
            string ip;
            string networkPort;
            var    response = Console.ReadLine();
            var    valid    = new List <string> {
                "1", "2"
            };

            if (!valid.Contains(response))
            {
                response = "1";
            }

            int choice = int.Parse(response);

            if (choice == 1)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    while (!comPort.StartsWith("COM"))
                    {
                        Console.Write("COM Port (eg. COM5): ");
                        comPort = Console.ReadLine();
                        if (string.IsNullOrWhiteSpace(comPort))
                        {
                            comPort = "COM5";
                        }
                    }
                    Console.Write("Baud Rate (eg. 115200): ");
                    baudRate = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(baudRate))
                    {
                        baudRate = "115200";
                    }
                    printer = new SerialPrinter(portName: comPort, baudRate: int.Parse(baudRate));
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Console.Write("File / virtual com path (eg. /dev/usb/lp0): ");
                    comPort = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(comPort))
                    {
                        comPort = "/dev/usb/lp0";
                    }
                    printer = new FilePrinter(filePath: comPort, false);
                }
            }
            else if (choice == 2)
            {
                Console.Write("IP Address (eg. 192.168.1.240): ");
                ip = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(ip))
                {
                    ip = "192.168.1.240";
                }
                Console.Write("TCP Port (eg. 9000): ");
                networkPort = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(networkPort))
                {
                    networkPort = "9000";
                }
                printer = new NetworkPrinter(ipAddress: ip, port: int.Parse(networkPort), reconnectOnTimeout: true);
            }

            bool monitor = false;

            Console.Write("Turn on Live Status Back Monitoring? (y/n): ");
            response = Console.ReadLine().Trim().ToLowerInvariant();
            if (response.Length >= 1 && response[0] == 'y')
            {
                monitor = true;
            }

            e = new EPSON();
            var testCases = new Dictionary <Option, string>()
            {
                { Option.Printing, "Printing" },
                { Option.LineSpacing, "Line Spacing" },
                { Option.BarcodeStyles, "Barcode Styles" },
                { Option.BarcodeTypes, "Barcode Types" },
                { Option.TwoDimensionCodes, "2D Codes" },
                { Option.TextStyles, "Text Styles" },
                { Option.FullReceipt, "Full Receipt" },
                { Option.CodePages, "Code Pages (Euro, Katakana, Etc)" },
                { Option.Images, "Images" },
                { Option.LegacyImages, "Legacy Images" },
                { Option.LargeByteArrays, "Large Byte Arrays" },
                { Option.CashDrawerPin2, "Cash Drawer Pin2" },
                { Option.CashDrawerPin5, "Cash Drawer Pin5" },
                { Option.Exit, "Exit" }
            };

            while (true)
            {
                foreach (var item in testCases)
                {
                    Console.WriteLine($"{(int)item.Key} : {item.Value}");
                }
                Console.Write("Execute Test: ");

                if (!int.TryParse(Console.ReadLine(), out choice) || !Enum.IsDefined(typeof(Option), choice))
                {
                    Console.WriteLine("Invalid entry. Please try again.");
                    continue;
                }

                var enumChoice = (Option)choice;
                if (enumChoice == Option.Exit)
                {
                    return;
                }

                Console.Clear();

                if (monitor)
                {
                    printer.StartMonitoring();
                }
                Setup(monitor);

                printer?.Write(e.PrintLine($"== [ Start {testCases[enumChoice]} ] =="));

                switch (enumChoice)
                {
                case Option.Printing:
                    printer.Write(Tests.Printing(e));
                    break;

                case Option.LineSpacing:
                    printer.Write(Tests.LineSpacing(e));
                    break;

                case Option.BarcodeStyles:
                    printer.Write(Tests.BarcodeStyles(e));
                    break;

                case Option.BarcodeTypes:
                    printer.Write(Tests.BarcodeTypes(e));
                    break;

                case Option.TwoDimensionCodes:
                    printer.Write(Tests.TwoDimensionCodes(e));
                    break;

                case Option.TextStyles:
                    printer.Write(Tests.TextStyles(e));
                    break;

                case Option.FullReceipt:
                    printer.Write(Tests.Receipt(e));
                    break;

                case Option.CodePages:
                    var codePage = CodePage.PC437_USA_STANDARD_EUROPE_DEFAULT;
                    Console.WriteLine("To run this test, you must select the index of a code page to print.");
                    Console.WriteLine("The default CodePage is typically CodePage 0 (USA/International).");
                    Console.WriteLine("Press enter to see the list of Code Pages.");
                    Console.ReadLine();
                    List <object> codePages = new List <object>();
                    foreach (var value in Enum.GetValues(typeof(CodePage)))
                    {
                        codePages.Add(value);
                    }
                    for (int i = 0; i < codePages.Count; i++)
                    {
                        Console.WriteLine(i.ToString() + ": " + codePages[i] + "  (Page " + ((int)codePages[i]) + ")");
                    }
                    Console.Write("Index for test Code Page (NOT Page #): ");
                    var page = Console.ReadLine();
                    try
                    {
                        codePage = (CodePage)codePages[int.Parse(page)];
                    }
                    catch
                    {
                        Console.WriteLine("Invalid code page selected, defaulting to CodePage 0.");
                    }

                    printer.Write(Tests.CodePages(e, codePage));
                    break;

                case Option.Images:
                    printer.Write(Tests.Images(e, false));
                    break;

                case Option.LegacyImages:
                    printer.Write(Tests.Images(e, true));
                    break;

                case Option.LargeByteArrays:
                    try
                    {
                        printer.Write(Tests.TestLargeByteArrays(e));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Aborting print due to test failure. Exception: {e?.Message}, Stack Trace: {e?.GetBaseException()?.StackTrace}");
                    }
                    break;

                case Option.CashDrawerPin2:
                    printer.Write(Tests.CashDrawerOpenPin2(e));
                    break;

                case Option.CashDrawerPin5:
                    printer.Write(Tests.CashDrawerOpenPin5(e));
                    break;

                default:
                    Console.WriteLine("Invalid entry.");
                    break;
                }

                Setup(monitor);
                printer?.Write(e.PrintLine($"== [ End {testCases[enumChoice]} ] =="));
                printer?.Write(e.PartialCutAfterFeed(5));

                // TODO: also make an automatic runner that runs all tests (command line).
            }
        }