첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

728x90
반응형

▶ DataReceivedEventArgs.cs

using System;

namespace TestProject
{
    /// <summary>
    /// 데이터 수신시 이벤트 인자
    /// </summary>
    public class DataReceivedEventArgs : EventArgs
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 데이터 - Data

        /// <summary>
        /// 데이터
        /// </summary>
        public string Data { get; set; }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - DataReceivedEventArgs(data)

        /// <summary>
        /// 생성자
        /// </summary>
        /// <param name="data">데이터</param>
        public DataReceivedEventArgs(string data)
        {
            Data = data;
        }

        #endregion
    }
}

 

▶ PrinterHelper.cs

using System;
using System.Diagnostics;
using System.IO.Ports;
using System.Management;
using System.Text;
using System.Text.RegularExpressions;

namespace TestProject
{
    /// <summary>
    /// 프린터 헬퍼
    /// </summary>
    /// <remarks>
    /// 유진시스텍 YJ-730T 키오스크 프린터
    /// </remarks>
    public static class PrinterHelper
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Event
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Public

        #region 데이터 수신시 - DataReceived

        /// <summary>
        /// 데이터 수신시
        /// </summary>
        public static event EventHandler<DataReceivedEventArgs> DataReceived;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// 직렬 포트
        /// </summary>
        private static SerialPort _serialPort = new SerialPort();

        /// <summary>
        /// 프린터 COM 포트
        /// </summary>
        private static readonly string _printerCOMPort = "2";

        /// <summary>
        /// 매장명
        /// </summary>
        private static readonly string _storeName = "수원역점";

        /// <summary>
        /// 주문 번호
        /// </summary>
        private static readonly string _orderNumber = "주문번호";

        /// <summary>
        /// 영수증 제목
        /// </summary>
        private static readonly string _receiptTItle = "영수증 (고객용)";

        /// <summary>
        /// 감사말
        /// </summary>
        private static readonly string _thankYou = "감사합니다.";

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Public
        ////////////////////////////////////////////////////////////////////// Function

        #region 연결 여부 구하기 - IsConnected()

        /// <summary>
        /// 연결 여부 구하기
        /// </summary>
        /// <returns>연결 여부</returns>
        public static bool IsConnected()
        {
            bool isConnected = false;

            string query = "SELECT * FROM Win32_PnPEntity WHERE ClassGuid = '{4d36e978-e325-11ce-bfc1-08002be10318}'";

            try
            {
                using(ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("root\\CIMV2", query))
                {
                    foreach(ManagementObject managementObject in managementObjectSearcher.Get())
                    {
                        string port = Regex.Replace(managementObject["Name"].ToString(), "[^0-9]", "");

                        if(port.Equals(_printerCOMPort))
                        {
                            isConnected = true;

                            break;
                        }
                    }
                }
            }
            catch(Exception exception)
            {
                Debug.WriteLine(exception.ToString());
            }

            return isConnected;
        }

        #endregion
        #region 열기 - Open()

        /// <summary>
        /// 열기
        /// </summary>
        /// <returns>처리 결과</returns>
        public static bool Open()
        {
            try
            {
                if(_serialPort != null)
                {
                    _serialPort.Close();
                }

                _serialPort = new SerialPort();

                _serialPort.PortName  = $"COM{_printerCOMPort}";
                _serialPort.BaudRate  = 9600;
                _serialPort.Parity    = Parity.None;
                _serialPort.DataBits  = 8;
                _serialPort.StopBits  = StopBits.One;
                _serialPort.Handshake = Handshake.XOnXOff;

                _serialPort.DataReceived += serialPort_DataReceived;

                _serialPort.Open();

                Debug.WriteLine($"OPEN : {_serialPort.PortName} {_serialPort.IsOpen}");
            }
            catch(Exception exception)
            {
                Debug.WriteLine(exception.ToString());
            }

            return _serialPort.IsOpen;
        }

        #endregion
        #region 상태 요청하기 - RequestStatus()

        /// <summary>
        /// 상태 요청하기
        /// </summary>
        public static void RequestStatus()
        {
            try
            {
                Debug.WriteLine("REQUEST STATUS");

                byte[] commandByteArray = new byte[2] { 0x1B, 0x07 };

                SendCommand(commandByteArray);
            }
            catch(Exception exception)
            {
                Debug.WriteLine(exception.ToString());
            }
        }

        #endregion
        #region 닫기 - Close()

        /// <summary>
        /// 닫기
        /// </summary>
        public static void Close()
        {
            _serialPort.Close();

            Debug.WriteLine($"CLOSE : {_serialPort.PortName} {_serialPort.IsOpen}");
        }

        #endregion

        #region 주문서 인쇄하기 - PrintOrderSheet(orderNumber)

        /// <summary>
        /// 주문서 인쇄하기
        /// </summary>
        /// <param name="orderNumber">주문 번호</param>
        public static void PrintOrderSheet(string orderNumber)
        {
            try
            {
                Debug.WriteLine($"PRINT ORDER SHEET : ORDER NUMBER = {orderNumber}");

                // Center Alignment
                SendCommand(new byte[] { 0x1B, 0x61, 0x01 });

                byte fontSize1 = ((byte)0xF0 & ((byte)0x00 << 4) | ((byte)0x0F & (byte)(0x00)));
                byte fontSize2 = ((byte)0xF0 & ((byte)0x01 << 4) | ((byte)0x0F & (byte)(0x01)));

                SendCommand(new byte[] { 0x1D, 0x21, fontSize1 });

                byte[] commandByteArray = Encoding.Default.GetBytes($"{_storeName}\n{DateTime.Now:yyyy-MM-dd HH:mm:ss}");

                SendCommand(commandByteArray); // Write Buffer

                SendCommand(new byte[] { 0x1B, 0x64, 0x02 }); // Print & n Line Feed

                SendCommand(new byte[] { 0x1D, 0x21, fontSize2 });

                commandByteArray = Encoding.Default.GetBytes($"[{_orderNumber} : {orderNumber}]");

                SendCommand(commandByteArray); // Write Buffer

                SendCommand(new byte[] { 0x1B, 0x64, 0x02 }); // Print & n Line Feed

                SendCommand(new byte[] { 0x1D, 0x21, fontSize1 });

                commandByteArray = Encoding.Default.GetBytes($"{_thankYou}\n");

                SendCommand(commandByteArray); // Write Buffer

                SendCommand(new byte[] { 0x1B, 0x64, 0x06 }); // Print & n Line Feed

              //SendCommand(new byte[] { 0x1B, 0x69 }); // Partial Cut
                SendCommand(new byte[] { 0x1B, 0x6D }); // Full Cut
            }
            catch(Exception exception)
            {
                Debug.WriteLine(exception.ToString());
            }
        }

        #endregion
        #region 영수증 인쇄하기 - PrintReceipt(storeInformation, orderNumberInformation, orderItemInformation, paymentInformation)

        /// <summary>
        /// 영수증 인쇄하기
        /// </summary>
        /// <param name="storeInformation">매장 정보</param>
        /// <param name="orderNumberInformation">주문 번호 정보</param>
        /// <param name="orderItemInformation">주문 항목 정보</param>
        /// <param name="paymentInformation">결제 정보</param>
        public static void PrintReceipt(string storeInformation, string orderNumberInformation, string orderItemInformation, string paymentInformation)
        {
            try
            {
                Debug.WriteLine($"PRINT RECEIPT : {orderNumberInformation}");

                byte fontSize1 = ((byte)0xF0 & ((byte)0x00 << 4) | ((byte)0x0F & (byte)(0x00)));
                byte fontSize2 = ((byte)0xF0 & ((byte)0x01 << 4) | ((byte)0x0F & (byte)(0x01)));

                SendCommand(new byte[] { 0x1B, 0x61, 0x00 }); // Left Alignment
                SendCommand(new byte[] { 0x1D, 0x21, fontSize1 });

                byte[] commandByteArray = Encoding.Default.GetBytes(storeInformation);

                SendCommand(commandByteArray); // Write Buffer

                SendCommand(new byte[] { 0x1B, 0x64, 0x01 }); // Print & n Line Feed

                SendCommand(new byte[] { 0x1B, 0x61, 0x01 }); // Center Alignment

                SendCommand(new byte[] { 0x1D, 0x21, fontSize2 });

                commandByteArray = Encoding.Default.GetBytes(orderNumberInformation);

                SendCommand(commandByteArray); // Write Buffer

                SendCommand(new byte[] { 0x1B, 0x64, 0x01 }); // Print & n Line Feed

                SendCommand(new byte[] { 0x1B, 0x61, 0x00 }); // Left Alignment

                SendCommand(new byte[] { 0x1D, 0x21, fontSize1 });

                commandByteArray = Encoding.Default.GetBytes(orderItemInformation);

                SendCommand(commandByteArray); // Write Buffer

                commandByteArray = Encoding.Default.GetBytes(_receiptTItle.PadLeft(26, ' '));

                SendCommand(commandByteArray); // Write Buffer

                SendCommand(new byte[] { 0x1B, 0x64, 0x00 }); // Print & n Line Feed

                SendCommand(new byte[] { 0x1B, 0x61, 0x00 }); // Left Alignment

                commandByteArray = Encoding.Default.GetBytes(paymentInformation);

                SendCommand(commandByteArray); // Write Buffer

                SendCommand(new byte[] { 0x1B, 0x64, 0x01 }); // Print & n Line Feed

                SendCommand(new byte[] { 0x1B, 0x61, 0x01 }); // Center Alignment

                commandByteArray = Encoding.Default.GetBytes(_thankYou);

                SendCommand(commandByteArray); // Write Buffer

                SendCommand(new byte[] { 0x1B, 0x64, 0x06 }); // Print & n Line Feed

                //SendCommand(new byte[] { 0x1B, 0x69 }); // Partial Cut

                SendCommand(new byte[] { 0x1B, 0x6D }); // Full Cut
            }
            catch(Exception exception)
            {
                Debug.WriteLine(exception.ToString());
            }
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////// Private
        ////////////////////////////////////////////////////////////////////// Event

        #region 직렬 포트 데이터 수신시 처리하기 - serialPort_DataReceived(sender, e)

        /// <summary>
        /// 직렬 포트 데이터 수신시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private static void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                int byteCountToRead = _serialPort.BytesToRead;

                if(byteCountToRead > 0)
                {
                    byte[] bufferByteArray = new byte[byteCountToRead];

                    _serialPort.Read(bufferByteArray, 0, byteCountToRead);

                    if(DataReceived != null)
                    {
                        Debug.WriteLine($"SERIAL PORT DATA RECEIVED : [{BitConverter.ToString(bufferByteArray)}]");

                        string argument = string.Empty;

                        byte flagByte = byteCountToRead == 2 ? bufferByteArray[1] : bufferByteArray[0];

                        switch(flagByte)
                        {
                            case 0x41 : // Paper Empty

                                argument = "Paper Empty";

                                break;

                            case 0x42 : // Caver Open

                                argument = "Caver Open";

                                break;

                            case 0x50 : // Roll Paper Empty
                            case 0x21 : // Roll Paper Empty

                                argument = "Roll Paper Empty";

                                break;

                            case 0x44 : // Head TM Over

                                argument = "Head TM Over";

                                break;

                            case 0x40 : // OK

                                break;
                        }

                        if(!string.IsNullOrEmpty(argument))
                        {
                            DataReceived(sender, new DataReceivedEventArgs(argument));
                        }
                    }
                }
            }
            catch(Exception exception)
            {
                Debug.WriteLine(exception.ToString());
            }
        }

        #endregion

        ////////////////////////////////////////////////////////////////////// Function

        #region 명령 보내기 - SendCommand(commandByteArray)

        /// <summary>
        /// 명령 보내기
        /// </summary>
        /// <param name="commandByteArray">명령 바이트 배열</param>
        private static void SendCommand(byte[] commandByteArray)
        {
            try
            {
                if(!_serialPort.IsOpen)
                {
                    PrinterHelper.Open();
                }

                if(_serialPort.IsOpen)
                {
                    _serialPort.Write(commandByteArray, 0, commandByteArray.Length);

                    Debug.WriteLine($"SEND COMMAND : [{BitConverter.ToString(commandByteArray)}]");
                }
            }
            catch(Exception exception)
            {
                Debug.WriteLine(exception.ToString());
            }
        }

        #endregion
    }
}
728x90
반응형
Posted by 사용자 icodebroker

댓글을 달아 주세요