Scanner.cs 4.65 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace BarcodeScannerClient
{
    public class BarCodeScanner
    {
        private SerialPort serialport = new SerialPort();
        private string port = "COM1";
        public string Port
        {
            get
            {
                return this.port;
            }
            set
            {
                this.port = value;
            }
        }


        public BarCodeScanner()
        {
            this.serialport.DataReceived += new SerialDataReceivedEventHandler(serialport_DataReceived);
        }
        public void Listen(string port)
        {
            this.port = port;
            Listen();
        }

        public void Listen()
        {
            try
            {
                if (this.serialport.IsOpen)
                    this.serialport.Close();
                this.serialport.PortName = this.port;
                this.serialport.Open();

                buffertimer.Elapsed += new System.Timers.ElapsedEventHandler(buffertimer_Elapsed);
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Cannot open barcode scanner on port" + this.serialport);
            }
        }

        void buffertimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            buffertimer.Enabled = false;

            Console.WriteLine(this.buffer);
            // If input is not regular card flush it!
            /*
            if (!buffer.StartsWith("C") && !buffer.StartsWith("R")) buffer = "";

            // if input is ready send it
            if (buffer.EndsWith("E") || buffer.EndsWith("E\r"))
            {
                // Trim white space away
                if (buffer.EndsWith("E\r"))
                    buffer = buffer.Trim();

                onBarcodeReceived(buffer);
                buffer = "";
            }
             */
            onBarcodeReceived(buffer.Trim());
            buffer = "";
        }


        public void Close()
        {
            try
            {
                this.serialport.Close();
            }
            catch (Exception e)
            {
            }
        }
        public enum BarcodeType { Card, Receipt };
        private string buffer;
        System.Timers.Timer buffertimer = new System.Timers.Timer(500);


        void serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            // Add new data to buffer
            this.buffer += serialport.ReadExisting();
            buffertimer.Start();
        }

        private void onBarcodeReceived(string text)
        {
            if (BarcodeReceived == null) return;
            text = text.TrimStart(new char[]{'0'});
            BarcodeReceived(text);
            //int data = 0 ;
            /*
            try
            {
                data = Convert.ToInt32(text.Substring(1, text.Length - 2));
            }
            catch
            {
                Console.WriteLine("Error in barcode parser! :" + text + ":");
            }
            if (text.StartsWith("C"))
            {
                BarcodeReceived(data, BarcodeType.Card);
            }
            else if (text.StartsWith("R"))
            {
                BarcodeReceived(data, BarcodeType.Receipt);
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Unknown barcode!");
            }
            */


        }
        //public delegate void Barcode (int data, BarcodeType type);
        public delegate void Barcode(string data);
        public event Barcode BarcodeReceived;

        public static int CalculateEanChecksum(string code)
        {
            if (code == null || code.Length != 12)
                throw new ArgumentException("Code length should be 12, i.e. excluding the checksum digit");

            int sum = 0;
            for (int i = 0; i < 12; i++)
            {
                int v;
                if (!int.TryParse(code[i].ToString(), out v))
                    throw new ArgumentException("Invalid character encountered in specified code.");
                sum += (i % 2 == 0 ? v : v * 3);
            }
            int check = 10 - (sum % 10);
            return check % 10;
        }

        private bool CheckEanCode(string code)
        {
            if (code == null || code.Length != 13)
                return false;

            int res;
            foreach (char c in code)
                if (!int.TryParse(c.ToString(), out res))
                    return false;

            char check = (char)('0' + CalculateEanChecksum(code.Substring(0, 12)));
            return code[12] == check;
        }

    }
}