Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing directly to a thermal printer using ESC/POS Commands executed in C# with an interface of TCP/IP

I was working on implementing ESC/POS(Epson Standard Code for Point of Sale) on a Kitchen printer(Aclas KP71M).
I have a user interface the the POS user enters its string in to the user interface and the strings entered by the user will be sent to the printer and the printer prints the data.
The printer interface with the host computer using Ethernet(100M) using TCP/IP connection.
I have managed to embed each of the necessary commands in to a C# method and I also take some sample code on server/client C# connection and tried to include that in to my connection.
The problem I am facing right now is that my code seems to start the connection but it freezes right away without doing nothing and stopped the connection.I would be very grateful if any one can correct me, or show me where the problem is, or give me some idea on how to proceed?
Here is the code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace ESC_POS
{
   public partial class Form1 : Form
   {
        public string tableNumber;
        public string itemOrdered;
        public string orderedQuantity;
        public string waiterName;
        public string orderDestination;
        public string orderNumber;

        const int MAX_CLIENTS = 10;

        public AsyncCallback pfnWorkerCallBack;
        private Socket m_mainSocket;
        private Socket[] m_workerSocket = new Socket[10];
        private int m_clientCount = 0;//Server declarations

        byte[] m_dataBuffer = new byte[10];
        IAsyncResult m_result;
        public AsyncCallback m_pfnCallBack;
        public Socket m_clientSocket;//Client declarations

        public Form1()
        {
            InitializeComponent();
            PC_IP.Text = GetIP();
            PRINTER_IP.Text = GetIP();
        }

        public void label1_Click(object sender, EventArgs e)
        {
        }

        public void Form1_Load(object sender, EventArgs e)
        {
        }   

        public void TableNumber_TextChanged(object sender, EventArgs e)
        {
            if (TableNumber.Text == "")
            {
                MessageBox.Show("Please enter the table number");
                return;
            }
            tableNumber = TableNumber.Text;
        }

        public void OrderedQuantitiy_TextChanged(object sender, EventArgs e)
        {
            if (OrderedQuantitiy.Text == "")
            {
                MessageBox.Show("Please enter the ordered quantity");
                return;
            }
            orderedQuantity = OrderedQuantitiy.Text;
        }

        public void WaiterName_TextChanged(object sender, EventArgs e)
        {
            if (WaiterName.Text == "")
            {
                MessageBox.Show("Please enter the waiter name");
                return;
            }
            waiterName = WaiterName.Text;
        }

        public void comboOrderDestination_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (ItemOrdered.Text == "")
            {
                MessageBox.Show("Please select the order destiination");
                return;
            }
            orderDestination = comboOrderDestination.SelectedText;
        }

        public void OrderNumber_TextChanged(object sender, EventArgs e)
        {
            if (OrderNumber.Text == "")
            {
                MessageBox.Show("Please enter the order number");
                return;
            }
            orderNumber = OrderNumber.Text;
        }

        public void PrintButton_Click(object sender, EventArgs e)
        {
            try
            {   
                string[] printData = new string[6];
                printData[0]=tableNumber ;
                printData[1]= itemOrdered;
                printData[2]= orderedQuantity;
                printData[3]= waiterName;
                printData[4]= orderDestination;
                printData[5]= orderNumber;
                string richTextMessage = "";
                PrinterCommands printCmd = new PrinterCommands();
                printCmd.initializePrinter();
                PrinterCommands print = new PrinterCommands();

                for (int i = 0; i < printData.Length; i++)
                {
                    richTextMessage = printData[i]+" ";
                    richTextMessage = print.LineFeed().ToString();
                }
                Object objData = richTextMessage;


                byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
                if (m_clientSocket != null)
                {
                    m_clientSocket.Send(byData);
                }
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        public void textBox1_TextChanged(object sender, EventArgs e)
        {
        }

        public void PC_PORT_TextChanged(object sender, EventArgs e)
        {
        }

        public void PRINTER_IP_TextChanged(object sender, EventArgs e)
        {
        }

        public void PRINTER_PORT_TextChanged(object sender, EventArgs e)
        {
        }

        public void Connect_toPC_Click(object sender, EventArgs e)
        {
            // See if we have text on the IP and Port text fields
            // See if we have text on the IP and Port text fields
            if (PRINTER_IP.Text == "" || PRINTER_PORT.Text == "")
            {
                MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");
                return;
            }
            try
            {
                UpdateControlsPrinter(false);
                // Create the socket instance
                m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Cet the remote IP address
                IPAddress ip = IPAddress.Parse(PRINTER_IP.Text);
                int iPortNo = System.Convert.ToInt16(PRINTER_PORT.Text);
                // Create the end point 
                IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
                // Connect to the remote host
                m_clientSocket.Connect(ipEnd);
                if (m_clientSocket.Connected)
                {

                    UpdateControlsPrinter(true);
                    //Wait for data asynchronously 
                    WaitForData();
                }
            }
            catch (SocketException se)
            {
                string str;
                str = "\nConnection failed, is the server running?\n" + se.Message;
                MessageBox.Show(str);
                UpdateControlsPrinter(false);
            }       
        }

        public void ItemOrdered_TextChanged_1(object sender, EventArgs e)
        {
            if (ItemOrdered.Text == "")
            {
                MessageBox.Show("Please enter the Item Ordered");
                return;
            }
        }

        public void Disconnect_toPC_Click(object sender, EventArgs e)
        {

            if (m_clientSocket != null)
            {
                m_clientSocket.Close();
                m_clientSocket = null;
             UpdateControlsPrinter(false);
            }
            Close();
        }

        public void Start_Listening_Click(object sender, EventArgs e)
        {
            try
            {
                // Check the port value
                if (PC_PORT.Text == "")
                {
                    MessageBox.Show("Please enter a Port Number");
                    return;
                }
                string portStr = PC_PORT.Text;
                int port = System.Convert.ToInt32(portStr);
                // Create the listening socket...
                m_mainSocket = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Stream,
                                          ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
                // Bind to local IP Address...
                m_mainSocket.Bind(ipLocal);
                // Start listening...
                m_mainSocket.Listen(4);
                // Create the call back for any client connections...
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

                UpdateControls(true);

            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        public void Stop_Listening_Click(object sender, EventArgs e)
        {
            CloseSockets();
            UpdateControls(false);
            Close();
        }

        String GetIP()
        {
            String strHostName = Dns.GetHostName();

            // Find host by name
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);

            // Grab the first IP addresses
            String IPStr = "";
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;
        }

        public void CloseSockets()
        {
            if (m_mainSocket != null)
            {
                m_mainSocket.Close();
            }
            for (int i = 0; i < m_clientCount; i++)
            {
                if (m_workerSocket[i] != null)
                {
                    m_workerSocket[i].Close();
                    m_workerSocket[i] = null;
                }
            }
        }

        public void WaitForData()
        {
            try
            {
                if (m_pfnCallBack == null)
                {
                    m_pfnCallBack = new AsyncCallback(OnDataReceived);
                }
                SocketPacket theSocPkt = new SocketPacket();
              //          theSocPkt.thisSocket = m_clientSocket;
                // Start listening to the data asynchronously
                m_result = m_clientSocket.BeginReceive(theSocPkt.dataBuffer,
                                                        0, theSocPkt.dataBuffer.Length,
                                                        SocketFlags.None,
                                                        m_pfnCallBack,
                                                        theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }

        public void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    // Specify the call back function which is to be 
                    // invoked when there is any write activity by the 
                    // connected client
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }
                SocketPacket theSocPkt = new SocketPacket();
                theSocPkt.m_currentSocket = soc;
                // Start receiving any data written by the connected client
                // asynchronously
                soc.BeginReceive(theSocPkt.dataBuffer, 0,
                                   theSocPkt.dataBuffer.Length,
                                   SocketFlags.None,
                                   pfnWorkerCallBack,
                                   theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        public class SocketPacket
        {
            public System.Net.Sockets.Socket m_currentSocket;
            public byte[] dataBuffer = new byte[1];
        }

        public void UpdateControlsPrinter(bool connected)
        {
            Connect_toPC.Enabled = !connected;
            Disconnect_toPC.Enabled = connected;
            string connectStatus = connected ? "Connected" : "Not Connected";
           // textBoxConnectStatus.Text = connectStatus;
        }

        public void UpdateControls(bool listening)
        {
            Start_Listening.Enabled = !listening;
            Stop_Listening.Enabled = listening;
        }

        public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState;

                int iRx = 0;
                // Complete the BeginReceive() asynchronous call by EndReceive() method
                // which will return the number of characters written to the stream 
                // by the client
                iRx = socketData.m_currentSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                int charLen = d.GetChars(socketData.dataBuffer,
                                         0, iRx, chars, 0);
                System.String szData = new System.String(chars);
              //  richTextBoxReceivedMsg.AppendText(szData);

                // Continue the waiting for data on the Socket
                WaitForData(socketData.m_currentSocket);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                // Here we complete/end the BeginAccept() asynchronous call
                // by calling EndAccept() - which returns the reference to
                // a new Socket object
                m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
                // Let the worker Socket do the further processing for the 
                // just connected client
                WaitForData(m_workerSocket[m_clientCount]);
                // Now increment the client count
                ++m_clientCount;
                // Display this client connection as a status message on the GUI    
                String str = String.Format("Client # {0} connected", m_clientCount);
               // textBoxMsg.Text = str;

                // Since the main Socket is now free, it can go back and wait for
                // other clients who are attempting to connect
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
    }
}
like image 465
Sisay Avatar asked Jul 20 '12 11:07

Sisay


1 Answers

Answering this question in case anyone else comes along with the same q. This is what worked for me:

Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSock.NoDelay = true;
IPAddress ip = IPAddress.Parse("192.168.0.18");
IPEndPoint remoteEP = new IPEndPoint(ip, 9100);
clientSock.Connect(remoteEP);
Encoding enc = Encoding.ASCII;

// Line feed hexadecimal values
byte[] bEsc = new byte[4];
bEsc[0] = 0x0A;
bEsc[1] = 0x0A;
bEsc[2] = 0x0A;
bEsc[3] = 0x0A;

// Send the bytes over 
clientSock.Send(bEsc);

// Sends an ESC/POS command to the printer to cut the paper
string output = Convert.ToChar(29) + "V" + Convert.ToChar(65) + Convert.ToChar(0);
char[] array = output.ToCharArray();
byte[] byData = enc.GetBytes(array);
clientSock.Send(byData);
clientSock.Close();
like image 143
Leonidas Avatar answered Sep 21 '22 23:09

Leonidas