using System;
using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

using SmartX;
using INT51DB.DialogForms;

namespace INT51DB.Forms
{
    public partial class FormMain : Form
    {
        #region Field
        private SmartSplash SmartSplashProgramLoad;
        public bool IsCommunicationLogOpen;
        private int CommunicationCheckCount;
        public bool IsBootingComplete;
        public int TestLogIndex;

        // 로그온 색상
        public Color ColorLogOff;
        public Color ColorLogOn;

        // 파일 위치
        private string m_PathLaunchFolder;              // 프로그램 실행 폴더
        private string m_PathDataBackupFolder;          // 데이터 백업 폴더
        private string m_PathSystemFileFolder;          // 시스템 파일 폴더

        // 시스템 상태
        private SystemStatus m_CurrentSystemStatus;

        // System Configuration
        public SystemConfigurationItem SystemConfig;
        // 현재 선택 된 품목
        public ProductItem CurrentProductItem;
        // JudgmentSet
        public JudgmentSetItem CurrentJudgmentSetItem;
        // 중량 조정 설정값
        public CalibrationItem CurrentCalibrationItem;
        // 중량 데이터
        public WeightData CurrentWeightData;
        // 시스템파라미터1
        public SystemParameter1 CurrentSystemParameter1;
        // 시스템파라미터2
        public SystemParameter2 CurrentSystemParameter2;
        // 시스템파라미터3
        public SystemParameter3 CurrentSystemParameter3;
        // 시스템파라미터4
        public SystemParameter4 CurrentSystemParameter4;

        // Form
        public FormMainDisplay ChildFormMainDisplay;
        public FormMenu ChildFormMenu;

        // IO Test Input 데이터 취합
        private Collection<string> CollectionIOTest_InputData;
        // 판정설정 그래프 데이터
        private Collection<int> CollectionGraphData;                            
        #endregion

        #region Constructor
        public FormMain()
        {
            InitializeComponent();

            // 프로그램 로딩 이미지
            this.SmartSplashProgramLoad = new SmartX.SmartSplash();
            this.SmartSplashProgramLoad.CenterPosition = true;
            this.SmartSplashProgramLoad.AnimationInterval = 100;
            this.SmartSplashProgramLoad.LoadingImagePathname = "SmartLoading3";
            this.SmartSplashProgramLoad.Start();
        } 
        #endregion

        #region Property
        public string PathLaunchFolder
        {
            get { return this.m_PathLaunchFolder; }
            set { this.m_PathLaunchFolder = value; }
        }
        public string PathDataBackupFolder
        {
            get { return this.m_PathDataBackupFolder; }
            set { this.m_PathDataBackupFolder = value; }
        }
        public string PathSystemFileFolder
        {
            get { return this.m_PathSystemFileFolder; }
            set { this.m_PathSystemFileFolder = value; }
        }

        public SystemStatus CurrentSystemStatus
        {
            get { return this.m_CurrentSystemStatus; }
            private set { this.m_CurrentSystemStatus = value; }
        } 
        #endregion

        #region Method
        private void DefaultSetting()
        {
            this.IsCommunicationLogOpen = false;
            this.CommunicationCheckCount = 0;
            this.IsBootingComplete = false;
            this.TestLogIndex = 0;

            this.ColorLogOff = Color.Red;
            this.ColorLogOn = Color.Lime;

            this.PathLaunchFolder = "SD Card\\";
            this.PathSystemFileFolder = this.PathLaunchFolder + "SystemFile\\";
            this.PathDataBackupFolder = this.PathLaunchFolder + "DataBackup\\";

            this.CollectionIOTest_InputData = new Collection<string>();
            this.CollectionIOTest_InputData.Clear();
            for (int i = 0; i < 8; i++)
                this.CollectionIOTest_InputData.Add("0");

            this.CollectionGraphData = new Collection<int>();
            this.CollectionGraphData.Clear();
            for (int i = 0; i < 300; i++)
                this.CollectionGraphData.Add(0);

            this.SystemConfig = new SystemConfigurationItem();
            this.CurrentProductItem = new ProductItem();
            this.CurrentJudgmentSetItem = new JudgmentSetItem();
            this.CurrentCalibrationItem = new CalibrationItem();
            this.CurrentWeightData = new WeightData();
            this.CurrentSystemStatus = new SystemStatus();
            this.CurrentSystemParameter1 = new SystemParameter1();
            this.CurrentSystemParameter2 = new SystemParameter2();
            this.CurrentSystemParameter3 = new SystemParameter3();
            this.CurrentSystemParameter4 = new SystemParameter4();

            // SystemFile 폴더 생성
            if (Directory.Exists(this.PathSystemFileFolder) == false)
                Directory.CreateDirectory(this.PathSystemFileFolder);

            // DataBackup 폴더 생성
            if (Directory.Exists(this.PathDataBackupFolder) == false)
                Directory.CreateDirectory(this.PathDataBackupFolder);
        }

        private void CreateForm()
        {
            this.ChildFormMainDisplay = new FormMainDisplay(this);
            this.ChildFormMenu = new FormMenu(this);

            this.smartForm.MainForm = this;

            this.smartForm.AddChildForm(this.ChildFormMainDisplay);
            this.smartForm.AddChildForm(this.ChildFormMenu);
        }

        public void TransferProductParameter(int productNumber)
        {
            string value = "";

            StringBuilder sb = new StringBuilder();
            ProductItem pItem = new ProductItem();
            JudgmentSetItem jItem = new JudgmentSetItem();

            this.LoadProductFile(ref pItem, productNumber - 1);
            this.LoadJudgmentSetFile(ref jItem, productNumber - 1);

            sb.Append(Helper.StringZeroFillDigits7(pItem.UnderRange));
            sb.Append(Helper.StringZeroFillDigits7(pItem.OverRange));
            sb.Append(Helper.StringZeroFillDigits7(pItem.TareRange));
            value = Helper.DoubleToString(jItem.DynamicCorrection, 6);
            value = value.Replace(".", "");
            sb.Append(Helper.StringZeroFillDigits7(value));
            sb.Append(Helper.StringZeroFillDigits4(jItem.Filter.ToString()));
            sb.Append(Helper.StringZeroFillDigits4(jItem.UpDelayTime.ToString()));
            sb.Append(Helper.StringZeroFillDigits4(jItem.DownDelayTime.ToString()));
            sb.Append(Helper.StringZeroFillDigits4(jItem.JudgmentCount.ToString()));
            sb.Append(Helper.StringZeroFillDigits4(jItem.FeedSpeed.ToString()));
            sb.Append(Helper.StringZeroFillDigits4(jItem.Sorter1Mode.ToString()));
            sb.Append(Helper.StringZeroFillDigits4(jItem.Sorter1DelayTime.ToString()));
            sb.Append(Helper.StringZeroFillDigits4(jItem.Sorter1RunTime.ToString()));
            sb.Append(Helper.StringZeroFillDigits4(jItem.Sorter2Mode.ToString()));
            sb.Append(Helper.StringZeroFillDigits4(jItem.Sorter2DelayTime.ToString()));
            sb.Append(Helper.StringZeroFillDigits4(jItem.Sorter2RunTime.ToString()));
            sb.Append(Helper.StringZeroFillDigits4(jItem.JudgmentDelayTime.ToString()));
            sb.Append(Helper.StringZeroFillDigits4("0000"));
            sb.Append(Helper.StringZeroFillDigits4("0000"));
            sb.Append(Helper.StringZeroFillDigits4("0000"));
            sb.Append(Helper.StringZeroFillDigits4(pItem.Number.ToString()));

            this.TransferDataStream(CommunicationCommand.Write, CommunicationID.MainBoard, CommunicationAddress._9013_ParameterProduct, sb.ToString());
        }

        private void ConverterAlarm(ref WeightData data, string alarm)
        {
            string sValue1 = "", sValue2 = "", sValue3 = "";

            if (alarm.Length != 3)
                return;

            sValue1 = Convert.ToString(Convert.ToInt16(alarm.Substring(0, 1), 16), 2).PadLeft((4 <= 1) ? 1 : 4, '0');
            sValue2 = Convert.ToString(Convert.ToInt16(alarm.Substring(1, 1), 16), 2).PadLeft((4 <= 1) ? 1 : 4, '0');
            sValue3 = Convert.ToString(Convert.ToInt16(alarm.Substring(2, 1), 16), 2).PadLeft((4 <= 1) ? 1 : 4, '0');

            // 휠 끼임 에러(Torque)
            if (sValue3[3] == '0')
                data.IsServoTorqueError = false;
            else
                data.IsServoTorqueError = true;

            // 진입센서2 넘어짐 감지 에러 
            if (sValue2[0] == '0')
                data.IsEntrySensor2Error = false;
            else
                data.IsEntrySensor2Error = true;
            // 배출센서 Full 에러
            if (sValue2[1] == '0')
                data.IsDrainSensorError = false;
            else
                data.IsDrainSensorError = true;
            // 진입센서1 Empt 에러
            if (sValue2[2] == '0')
                data.IsEntrySensor1Error = false;
            else
                data.IsEntrySensor1Error = true;
            // 인버터 에러
            if (sValue2[3] == '0')
                data.IsInverterError = false;
            else
                data.IsInverterError = true;

            // 입력센서 에러
            if (sValue1[3] == '0')
                data.IsEntrySensorError = false;
            else
                data.IsEntrySensorError = true;

            // 셀 에러
            if (sValue1[2] == '0')
                data.IsLoadCellError = false;
            else
                data.IsLoadCellError = true;

            // 서보 알람
            if (sValue1[1] == '0')
                data.IsServoAlarm = false;
            else
                data.IsServoAlarm = true;

            // 서보온
            if (sValue1[0] == '0')
                data.IsServoOff = false;
            else
                data.IsServoOff = true;
        }

        /// <summary>
        /// Set Mode
        /// </summary>
        /// <param name="mode"></param>
        public void SetDisplayMode(DataStore.DisplayMode mode)
        {
            if (this.CurrentSystemStatus.CurrentMode == mode)
                return;
            else
                this.CurrentSystemStatus.CurrentMode = mode;

            switch (mode)
            {
                case DataStore.DisplayMode.Normal:
                    this.TransferData(CommunicationCommand.ModeNormal, CommunicationID.MainBoard);
                    break;
                case DataStore.DisplayMode.Menu:
                    this.TransferData(CommunicationCommand.ModeMenu, CommunicationID.MainBoard);
                    break;
                case DataStore.DisplayMode.Calibration:
                    this.TransferData(CommunicationCommand.ModeCalibration, CommunicationID.MainBoard);
                    break;
                case DataStore.DisplayMode.SystemSetting:
                    this.TransferData(CommunicationCommand.ModeJudgment, CommunicationID.MainBoard);
                    break;
                case DataStore.DisplayMode.IOTest:
                    this.TransferData(CommunicationCommand.ModeIOTest, CommunicationID.MainBoard);
                    break;
                case DataStore.DisplayMode.Bypass:
                    this.TransferData(CommunicationCommand.ModeBypass, CommunicationID.MainBoard);
                    break;
                case DataStore.DisplayMode.EquipmentTest:
                    this.TransferData(CommunicationCommand.ModeEquipmentTest, CommunicationID.MainBoard);
                    break;
                case DataStore.DisplayMode.SorterTest:
                    this.TransferData(CommunicationCommand.ModeRejectorTest, CommunicationID.MainBoard);
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// Set User
        /// </summary>
        /// <param name="user"></param>
        public void SetUser(DataStore.UserGroup user)
        {
            if (this.CurrentSystemStatus.CurrentUser.Group != user)
                this.CurrentSystemStatus.CurrentUser.Group = user;
        }

        #region Uart Communication
        private void OpenSmartUartLink()
        {
            string fullPath = "";
            DateTime dt = DateTime.Now;

            try
            {
                if (this.smartSerialPort2.IsOpen == false)
                    this.smartSerialPort2.Open();
            }
            catch
            {
            }

            #region Test 용 통신 로그
            fullPath = this.PathDataBackupFolder + "Communicationlog.txt";
            this.smartFileCommunicationLog.FilePathName = fullPath;
            this.smartFileCommunicationLog.Open();
            this.IsCommunicationLogOpen = true;
            #endregion

            #region Error Check 용 통신 로그
            fullPath = this.PathDataBackupFolder + string.Format("{0:yyMMdd}_", dt) + this.SystemConfig.EquipmentID + "_Checklog.txt";
            this.smartFileCheckLog.FilePathName = fullPath;
            // CheckLog
            //this.smartFileCheckLog.Open();
            //this.IsErrorLogOpen = true;
            #endregion
        }
        public void CloseSmartUartLink()
        {
            this.smartSerialPort2.Close();
        }
                
        private bool SizeCheck(string cmd, string strTemp)
        {
            bool ret = false;
            string dataSize = "";
            int size = 0;

            if (strTemp == null || strTemp.Length == 0)
            {
                ret = false;
                return ret;
            }

            try
            {
                if (cmd == "P")
                    dataSize = strTemp.Substring(14, strTemp.Length - 16);
                else // "S"
                    dataSize = strTemp.Substring(10, strTemp.Length - 12);

                size = int.Parse(strTemp.Substring(6, 4).Trim());
            }
            catch
            {
                ret = false;
                return ret;
            }

            if (dataSize.Length == size)
                ret = true;
            else
                ret = false;

            return ret;
        }
        private bool ChksumCheck(string strTemp)
        {
            bool ret = false;
            string chkSum = "", dataChksum = "";

            if (strTemp == null || strTemp.Length == 0)
                ret = false;
            else
            {
                chkSum = strTemp.Substring(strTemp.Length - 2, 2);
                dataChksum = this.Checksumcalculator(strTemp.Substring(0, strTemp.Length - 2));

                if (chkSum == dataChksum)
                    ret = true;
                else
                    ret = false;
            }

            return ret;
        }
        private string Checksumcalculator(string strTemp)
        {
            string chkSum = "";
            byte[] temp;
            int value = 0, first = 0, second = 0;
            char char1, char2;

            if (strTemp == null || strTemp.Length == 0)
                chkSum = "cc";
            else
            {
                temp = new UTF8Encoding().GetBytes(strTemp);

                for (int i = 0; i < temp.Length; i++)
                    value += temp[i];

                first = (value & 0x00f0) >> 4;
                if (first > 9)
                    char1 = (char)(first + 0x37);
                else
                    char1 = (char)(first + 0x30);

                second = value & 0x000f;
                if (second > 9)
                    char2 = (char)(second + 0x37);
                else
                    char2 = (char)(second + 0x30);

                chkSum = char1.ToString() + char2.ToString();
            }

            return chkSum;
        }

        public int TransferData(string command, string id)
        {
            int ret = 0;
            string chkSum = "cc";
            StringBuilder sb = new StringBuilder();

            sb.Append(command);
            sb.Append(id);

            chkSum = this.Checksumcalculator(sb.ToString());

            sb.Append(chkSum);

            if (this.smartSerialPort2.IsOpen == true)
                this.smartSerialPort2.WriteFrame(sb.ToString(), SmartSerialPort.CODETYPES.ASCIICODE);

            // 통신 확인 로그
            if (this.IsCommunicationLogOpen == true)
                this.smartFileCommunicationLog.WriteString(string.Format("Send ({0:yyyy-MM-dd HH:mm:ss}): {1}", DateTime.Now, sb.ToString()));

            return ret;
        }
        public int TransferDataStream(string command, string id, string address, string data)
        {
            int ret = 0;
            string chkSum = "cc";
            StringBuilder sb = new StringBuilder();

            sb.Append(command);
            sb.Append(id);
            sb.Append(Helper.StringZeroFillDigits4(data.Length.ToString()));
            sb.Append(address);
            sb.Append(data);

            chkSum = this.Checksumcalculator(sb.ToString());

            sb.Append(chkSum);

            if (this.smartSerialPort2.IsOpen == true)
                this.smartSerialPort2.WriteFrame(sb.ToString(), SmartSerialPort.CODETYPES.ASCIICODE);

            // 통신 확인 로그
            if (this.IsCommunicationLogOpen == true)
                this.smartFileCommunicationLog.WriteString(string.Format("Send ({0:yyyy-MM-dd HH:mm:ss}): {1}", DateTime.Now, sb.ToString()));

            return ret;
        }
        private void ReceiveData()
        {
            int ret = 0;
            string strTemp = "";
            byte[] readByte;
            SmartSerialPort.FRAMEDATAREADSTATUS receiveDataState = SmartSerialPort.FRAMEDATAREADSTATUS.EMPTY;

            try
            {
                receiveDataState = this.smartSerialPort2.ReadQueue(out readByte);
                strTemp = Encoding.Default.GetString(readByte, 0, readByte.Length);
            }
            catch
            {
                return;
            }

            if ((receiveDataState == SmartSerialPort.FRAMEDATAREADSTATUS.EMPTY) || (receiveDataState == SmartSerialPort.FRAMEDATAREADSTATUS.FAILDATA))
            {
                return;
            }

            try
            {
                switch (strTemp[0])
                {
                    case 'C':
                        if ((ret = this.ReceiveCommandC(strTemp)) != 0)
                            return;
                        break;
                    case 'P':
                        if ((ret = this.ReceiveCommandP(strTemp)) != 0)
                            return;
                        break;
                    case 'S':
                        if ((ret = this.ReceiveCommandS(strTemp)) != 0)
                            return;
                        break;
                    default:
                        break;
                }
            }
            catch
            {
            }
        }

        private int ReceiveCommandC(string strTemp)
        {
            int ret = 0;
            string cmd = "";

            if (this.ChksumCheck(strTemp) == false)
            {
                // 로그
                if (this.IsCommunicationLogOpen == true)
                    this.smartFileCommunicationLog.WriteString(string.Format("Receive ({0:yyyy-MM-dd HH:mm:ss}): {1} : Receive Command Data CHKSUM Error", DateTime.Now, strTemp));
                return ret = -1;
            }

            // 로그
            if (this.IsCommunicationLogOpen == true)
                this.smartFileCommunicationLog.WriteString(string.Format("Receive ({0:yyyy-MM-dd HH:mm:ss}): {1}", DateTime.Now, strTemp));

            cmd = strTemp.Substring(0, 3);

            switch (cmd)
            {
                case "CI0":
                    #region Main Board Booted
                    if (this.CurrentSystemStatus.Equipment == DataStore.EquipmentStatus.Start)
                    {
                        this.CurrentSystemStatus.Equipment = DataStore.EquipmentStatus.Stop;

                        // 생산속도 Clear
                        this.CurrentWeightData.ProductionSpeed = 0;
                        this.CurrentWeightData.IsStart = false;

                        // 정지 시간 저장
                        this.CurrentWeightData.StopTime = DateTime.Now;
                        this.SaveCounterFile(this.CurrentWeightData, this.SystemConfig.ProductNumber - 1);

                        this.ChildFormMainDisplay.UpdateEquipmentStatusDisplay(this.CurrentSystemStatus.Equipment);
                    }
                    // Read SystemParameter1
                    this.TransferDataStream(CommunicationCommand.Read, CommunicationID.MainBoard, CommunicationAddress._9501_SystemParameterRead1, ""); 
                    #endregion
                    break;
                case "CBI":
                    #region 공장초기화완료
                    this.ChildFormMenu.CenterEquipInitialize.UpdateDisplayMainBoardInitialization();
                    #endregion
                    break;
                case "CBS":
                    #region 운전
                    this.CurrentSystemStatus.Equipment = DataStore.EquipmentStatus.Start;

                    // 운전시 중량 0 으로 Clear
                    this.CurrentWeightData.Weight = 0.0;

                    // 운전 시간 저장
                    if (this.CurrentWeightData.TotalCount == 0)
                    {
                        this.CurrentWeightData.StartTime = DateTime.Now;
                        this.SaveCounterFile(this.CurrentWeightData, this.SystemConfig.ProductNumber - 1);
                    }

                    if (this.CurrentSystemStatus.CurrentDisplay == DataStore.DisplayStore.MainDisplay)
                        this.ChildFormMainDisplay.UpdateEquipmentStatusDisplay(this.CurrentSystemStatus.Equipment);
                    else
                        this.ChildFormMenu.UpdateEquipmentStatusDisplay(this.CurrentSystemStatus.Equipment);
                    #endregion
                    break;
                case "CBT":
                    #region 정지
                    this.CurrentSystemStatus.Equipment = DataStore.EquipmentStatus.Stop;

                    // 생산속도 Clear
                    this.CurrentWeightData.ProductionSpeed = 0;
                    this.CurrentWeightData.IsStart = false;

                    // 정지 시간 저장
                    this.CurrentWeightData.StopTime = DateTime.Now;
                    this.SaveCounterFile(this.CurrentWeightData, this.SystemConfig.ProductNumber - 1);

                    if (this.CurrentSystemStatus.CurrentDisplay == DataStore.DisplayStore.MainDisplay)
                        this.ChildFormMainDisplay.UpdateEquipmentStatusDisplay(this.CurrentSystemStatus.Equipment);
                    else
                        this.ChildFormMenu.UpdateEquipmentStatusDisplay(this.CurrentSystemStatus.Equipment); 
                    #endregion
                    break;
                case "CBE":
                    #region 소거

                    #endregion
                    break;
                case "CBZ":
                    #region 영점

                    #endregion
                    break;
                case "Csc":
                    #region 중량조정모드

                    #endregion
                    break;
                case "Csn":
                    #region 노멀모드
                    switch (this.CurrentSystemStatus.CurrentDisplay)
                    {
                        case DataStore.DisplayStore.MainDisplay:
                            break;
                        case DataStore.DisplayStore.BasicDataBackup:
                            break;
                        case DataStore.DisplayStore.BasicDataStatistics:
                            break;
                        case DataStore.DisplayStore.BasicHelp:
                            break;
                        case DataStore.DisplayStore.BasicProduct:
                            break;
                        case DataStore.DisplayStore.BasicTime:
                            break;
                        case DataStore.DisplayStore.ConfiCommunication:
                            break;
                        case DataStore.DisplayStore.ConfiHelp:
                            break;
                        case DataStore.DisplayStore.ConfiOption:
                            break;
                        case DataStore.DisplayStore.EquipHelp:
                            break;
                        case DataStore.DisplayStore.EquipInitialize:
                            break;
                        case DataStore.DisplayStore.EquipUpdate:
                            break;
                        case DataStore.DisplayStore.EquipFuctionSetting:
                            break;
                        case DataStore.DisplayStore.EquipUser:
                            break;
                        case DataStore.DisplayStore.EquipTest:
                            break;
                        case DataStore.DisplayStore.InforAS:
                            break;
                        case DataStore.DisplayStore.InforHelp:
                            break;
                        case DataStore.DisplayStore.InforSystem:
                            this.TransferDataStream(CommunicationCommand.Read, CommunicationID.MainBoard, CommunicationAddress.ProgramVersion, "");
                            break;
                        case DataStore.DisplayStore.SystemAutoZero:
                            break;
                        case DataStore.DisplayStore.SystemCalibration:
                            break;
                        case DataStore.DisplayStore.SystemHelp:
                            break;
                        case DataStore.DisplayStore.SystemIOTest:
                            break;
                        case DataStore.DisplayStore.SystemJudgmentSetting:
                            break;
                        case DataStore.DisplayStore.SystemExternalOutput:
                            break;
                        case DataStore.DisplayStore.SystemSorterSetting:
                            break;
                        default:
                            break;
                    } 
                    #endregion
                    break;
                case "Csg":
                    #region 판정설정모드

                    #endregion
                    break;
                case "Cst":
                    #region IO테스트모드

                    #endregion
                    break;
                case "Csb":
                    #region 바이패스모드

                    #endregion
                    break;
                case "Csy":
                    #region 장비테스트모드

                    #endregion
                    break;
                case "Csm":
                    #region 메뉴모드

                    #endregion
                    break;
                default:
                    break;
            }

            return ret;
        }
        private int ReceiveCommandP(string strTemp)
        {
            int ret = 0;
            string cmd = "", address = "", lane = "", receiveData = "";

            // SIZE 확인
            if (this.SizeCheck("P", strTemp) == false)
            {
                // 로그
                if (this.IsCommunicationLogOpen == true)
                    this.smartFileCommunicationLog.WriteString(string.Format("Receive ({0:yyyy-MM-dd HH:mm:ss}): {1} : Receive Stream Data SIZE Error", DateTime.Now, strTemp));
                return ret = -1;
            }
            // CHKSUM 확인
            if (this.ChksumCheck(strTemp) == false)
            {
                // 로그
                if (this.IsCommunicationLogOpen == true)
                    this.smartFileCommunicationLog.WriteString(string.Format("Receive ({0:yyyy-MM-dd HH:mm:ss}): {1} : Receive Stream Data CHKSUM Error", DateTime.Now, strTemp));
                return ret = -1;
            }

            // 로그
            if (this.IsCommunicationLogOpen == true)
                this.smartFileCommunicationLog.WriteString(string.Format("Receive ({0:yyyy-MM-dd HH:mm:ss}): {1}", DateTime.Now, strTemp));

            cmd = strTemp.Substring(0, 3);
            lane = strTemp.Substring(5, 1);
            address = strTemp.Substring(10, 4);
            receiveData = strTemp.Substring(14, strTemp.Length - 16);

            switch (cmd)
            {
                case "PR0":
                    if ((ret = this.ReceiveCommandPR0(lane, address, receiveData)) != 0)
                        return ret = -1;
                    break;
                case "PW0":
                    if ((ret = this.ReceiveCommandPW0(lane, address, receiveData)) != 0)
                        return ret = -1;
                    break;
                case "PB0":
                    if ((ret = this.ReceiveCommandPB0(lane, address, receiveData)) != 0)
                        return ret = -1;
                    break;
                default:
                    break;
            }

            return ret;
        }
        private int ReceiveCommandS(string strTemp)
        {
            int ret = 0;
            string cmd = "", lane = "", receiveData = "", transferCount = "";

            // SIZE 확인
            if (this.SizeCheck("S", strTemp) == false)
            {
                // 로그
                if (this.IsCommunicationLogOpen == true)
                    this.smartFileCommunicationLog.WriteString(string.Format("Receive ({0:yyyy-MM-dd HH:mm:ss}): {1} : Receive Stream Data SIZE Error", DateTime.Now, strTemp));
                return ret = -1;
            }
            // CHKSUM 확인
            if (this.ChksumCheck(strTemp) == false)
            {
                // 로그
                if (this.IsCommunicationLogOpen == true)
                    this.smartFileCommunicationLog.WriteString(string.Format("Receive ({0:yyyy-MM-dd HH:mm:ss}): {1} : Receive Stream Data CHKSUM Error", DateTime.Now, strTemp));
                return ret = -1;
            }

            // 로그
            if (this.IsCommunicationLogOpen == true)
                this.smartFileCommunicationLog.WriteString(string.Format("Receive ({0:yyyy-MM-dd HH:mm:ss}): {1}", DateTime.Now, strTemp));

            cmd = strTemp.Substring(0, 3);
            transferCount = strTemp.Substring(3, 2);
            lane = strTemp.Substring(5, 1);
            receiveData = strTemp.Substring(10, strTemp.Length - 12);

            switch (cmd)
            {
                case "SN0":
                    if ((ret = this.ReceiveCommandSN0(lane, receiveData)) != 0)
                        return ret;
                    break;
                case "SR0":
                    if ((ret = this.ReceiveCommandSR0(lane, receiveData)) != 0)
                        return ret;
                    break;
                case "SC0":
                    if ((ret = this.ReceiveCommandSC0(lane, receiveData)) != 0)
                        return ret;
                    break;
                case "ST0":
                    if ((ret = this.ReceiveCommandST0(lane, receiveData)) != 0)
                        return ret;
                    break;
                case "SF0":
                    if ((ret = this.ReceiveCommandSF0(lane, receiveData)) != 0)
                        return ret;
                    break;
                case "SG0":
                    if ((ret = this.ReceiveCommandSG0(lane, receiveData)) != 0)
                        return ret;
                    break;
                default:
                    break;
            }

            // ex
            #region ex
            if (cmd == "SG0")
            {
                byte[] a = new UTF8Encoding().GetBytes(strTemp.Substring(0, strTemp.Length - 2));
                int j = 0, first, second;
                char char1, char2;
                string value1 = "";
                for (int i = 0; i < a.Length; i++)
                {
                    j += a[i];
                }

                first = (j & 0x00f0) >> 4;
                if (first > 9)
                    char1 = (char)(first + 0x37);
                else
                    char1 = (char)(first + 0x30);

                second = j & 0x000f;
                if (second > 9)
                    char2 = (char)(second + 0x37);
                else
                    char2 = (char)(second + 0x30);

                value1 = char1.ToString() + char2.ToString();
                this.ChildFormMenu.CenterSystemJudgmentSetting.UpdateChecksumDisplay(strTemp.Substring(strTemp.Length - 2, 2), value1);
            }
            #endregion

            return ret;
        }

        // 파라미터 읽기 응답
        private int ReceiveCommandPR0(string lane, string address, string receiveData)
        {
            int ret = 0, iValue = 0;
            string sValue = "";

            try
            {
                switch (address)
                {
                    case "1501":
                        #region Value Assign
                        this.SystemConfig.MainBoardVersion = receiveData.Substring(0, 4);
                        #endregion
                        this.ChildFormMenu.CenterInforSystemInformation.UpdateMainBoardVersionDisplay(this.SystemConfig.MainBoardVersion);
                        break;
                    case "2001":
                        #region Value Assign
                        iValue = int.Parse(receiveData);
                        if (iValue <= 0 || iValue > 1000)
                            return ret = -1;

                        this.SystemConfig.ProductNumber = iValue;

                        #endregion

                        // 최초에 부팅이 완료 되었는지 확인
                        if (this.IsBootingComplete == false)
                            this.IsBootingComplete = true;

                        this.SaveSystemConfigurationFile(this.SystemConfig);

                        this.LoadProductFile(ref this.CurrentProductItem, this.SystemConfig.ProductNumber - 1);
                        this.LoadCounterFile(ref this.CurrentWeightData, this.SystemConfig.ProductNumber - 1);
                        this.LoadJudgmentSetFile(ref this.CurrentJudgmentSetItem, this.SystemConfig.ProductNumber - 1);

                        // 생산속도 Clear
                        this.CurrentWeightData.ProductionSpeed = 0;
                        this.CurrentWeightData.IsStart = false;

                        if (this.CurrentSystemStatus.CurrentDisplay == DataStore.DisplayStore.MainDisplay)
                            this.ChildFormMainDisplay.UpdateCurrentProductDisplay(this.CurrentSystemStatus.Equipment, this.CurrentProductItem, this.CurrentWeightData);
                        else
                            this.ChildFormMenu.CenterSystemJudgmentSetting.UpdateCurrentProductDisplay(this.CurrentSystemStatus.Equipment, this.CurrentProductItem);
                        break;
                    case "3601":
                        #region Value Assign
                        this.CurrentCalibrationItem.Constant = receiveData.Substring(0, 7).Trim();
                        #endregion
                        if (this.CurrentSystemStatus.CurrentDisplay == DataStore.DisplayStore.SystemCalibration)
                            this.ChildFormMenu.CenterSystemCalibration.UpdateCalibrationItemDisplay(this.CurrentSystemStatus.Equipment, this.CurrentCalibrationItem);
                        else if (this.CurrentSystemStatus.CurrentDisplay == DataStore.DisplayStore.SystemJudgmentSetting)
                            this.ChildFormMenu.CenterSystemJudgmentSetting.UpdateConstantDisplay(this.CurrentSystemStatus.Equipment, this.CurrentCalibrationItem);
                        break;
                    case "3901":
                        #region Value Assign
                        this.CurrentCalibrationItem.MaxWeight = receiveData.Substring(0, 7).Trim();
                        this.CurrentCalibrationItem.BalanceWeight = receiveData.Substring(7, 7).Trim();
                        this.CurrentCalibrationItem.Digit = receiveData.Substring(14, 7).Trim();
                        this.CurrentCalibrationItem.Constant = receiveData.Substring(21, 7).Trim();
                        #endregion
                        this.ChildFormMenu.CenterSystemCalibration.UpdateCalibrationItemDisplay(this.CurrentSystemStatus.Equipment, this.CurrentCalibrationItem);
                        break;
                    case "4901":
                        #region Value Assign
                        this.CurrentSystemParameter4.AutoZero1Time = receiveData.Substring(0, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero1Range = receiveData.Substring(4, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero1Variate = receiveData.Substring(8, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero1Mode = receiveData.Substring(12, 4).Trim();
                        #endregion
                        if (this.CurrentSystemStatus.CurrentDisplay == DataStore.DisplayStore.SystemAutoZero)
                            this.ChildFormMenu.CenterSystemAutoZero.UpdateZero1ParameterDisplay(this.CurrentSystemParameter4);
                        break;
                    case "4902":
                        #region Value Assign
                        this.CurrentSystemParameter4.AutoZero2Mode = receiveData.Substring(0, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero2Time = receiveData.Substring(4, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero2Range = receiveData.Substring(8, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero2Variate = receiveData.Substring(12, 4).Trim();
                        #endregion
                        this.ChildFormMenu.CenterSystemAutoZero.UpdateZero2ParameterDisplay(this.CurrentSystemParameter4);
                        break;
                    case "5302":
                        #region Value Assign
                        #endregion
                        break;
                    case "6901":
                        #region Value Assign
                        #endregion
                        break;
                    case "9501":
                        #region Value Assign
                        this.CurrentSystemParameter1.Serial1Mode = receiveData.Substring(0, 4).Trim();
                        this.CurrentSystemParameter1.Serial1BaudRate = receiveData.Substring(4, 4).Trim();
                        this.CurrentSystemParameter1.BuzzerOnTime = receiveData.Substring(8, 4).Trim();
                        this.CurrentSystemParameter1.RelayOnTime = receiveData.Substring(12, 4).Trim();
                        this.CurrentSystemParameter1.Chattering = receiveData.Substring(16, 4).Trim();
                        this.CurrentSystemParameter1.SorterDoubleEntry = receiveData.Substring(20, 4).Trim();
                        this.CurrentSystemParameter1.SorterExternalNgInput = receiveData.Substring(24, 4).Trim();
                        this.CurrentSystemParameter1.StopWeighing = receiveData.Substring(28, 4).Trim();
                        this.CurrentSystemParameter1.ExternalOperation = receiveData.Substring(32, 4).Trim();
                        this.CurrentSystemParameter1.InitialDrive = receiveData.Substring(36, 4).Trim();
                        this.CurrentSystemParameter1.PressureSensing = receiveData.Substring(40, 4).Trim();
                        this.CurrentSystemParameter1.StackSensing = receiveData.Substring(44, 4).Trim();
                        this.CurrentSystemParameter1.SorterDetecting = receiveData.Substring(48, 4).Trim();
                        this.CurrentSystemParameter1.OptionBoard = receiveData.Substring(52, 4).Trim();
                        this.CurrentSystemParameter1.PassAlarmCount = receiveData.Substring(56, 4).Trim();
                        this.CurrentSystemParameter1.DrainConveyorDelayTime = receiveData.Substring(60, 4).Trim();
                        this.CurrentSystemParameter1.DrainConveyorRunTime = receiveData.Substring(64, 4).Trim();
                        this.CurrentSystemParameter1.Dummy4 = receiveData.Substring(68, 4).Trim();
                        this.CurrentSystemParameter1.Dummy5 = receiveData.Substring(72, 4).Trim();
                        this.CurrentSystemParameter1.Dummy6 = receiveData.Substring(76, 4).Trim();
                        #endregion
                        // Read SystemParameter2
                        this.TransferDataStream(CommunicationCommand.Read, CommunicationID.MainBoard, CommunicationAddress._9502_SystemParameterRead2, "");
                        break;
                    case "9502":
                        #region Value Assign
                        this.CurrentSystemParameter2.OPT1SamplingCount = receiveData.Substring(0, 4).Trim();
                        this.CurrentSystemParameter2.OPT1DelayCount = receiveData.Substring(4, 4).Trim();
                        this.CurrentSystemParameter2.OPT1PulseWidth = receiveData.Substring(8, 4).Trim();
                        this.CurrentSystemParameter2.OPT1IsWeightSetting = receiveData.Substring(12, 4).Trim();
                        this.CurrentSystemParameter2.OPT1OverRange = receiveData.Substring(16, 7).Trim();
                        this.CurrentSystemParameter2.OPT1UnderRange = receiveData.Substring(23, 7).Trim();
                        this.CurrentSystemParameter2.OPT1Port = receiveData.Substring(30, 4).Trim();
                        this.CurrentSystemParameter2.OPT2Port = receiveData.Substring(34, 4).Trim();
                        this.CurrentSystemParameter2.OPT2DelayTime = receiveData.Substring(38, 4).Trim();
                        this.CurrentSystemParameter2.OPt2RunTime = receiveData.Substring(42, 4).Trim();
                        this.CurrentSystemParameter2.Dummy1 = receiveData.Substring(46, 7).Trim();
                        this.CurrentSystemParameter2.Dummy2 = receiveData.Substring(53, 7).Trim();
                        this.CurrentSystemParameter2.Dummy3 = receiveData.Substring(60, 4).Trim();
                        this.CurrentSystemParameter2.Dummy4 = receiveData.Substring(64, 4).Trim();
                        this.CurrentSystemParameter2.Dummy5 = receiveData.Substring(68, 4).Trim();
                        this.CurrentSystemParameter2.Dummy6 = receiveData.Substring(72, 4).Trim();
                        this.CurrentSystemParameter2.Dummy6 = receiveData.Substring(76, 4).Trim();
                        #endregion
                        // Read SystemParameter3
                        this.TransferDataStream(CommunicationCommand.Read, CommunicationID.MainBoard, CommunicationAddress._9503_SystemParameterRead3, "");
                        break;
                    case "9503":
                        #region Value Assign
                        this.CurrentSystemParameter3.ExternalOut1Mode = receiveData.Substring(0, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut1DelayTime = receiveData.Substring(4, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut1RunTime = receiveData.Substring(8, 4).Trim();

                        this.CurrentSystemParameter3.ExternalOut2Mode = receiveData.Substring(12, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut2DelayTime = receiveData.Substring(16, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut2RunTime = receiveData.Substring(20, 4).Trim();
                        
                        this.CurrentSystemParameter3.ExternalOut3Mode = receiveData.Substring(24, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut3DelayTime = receiveData.Substring(28, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut3RunTime = receiveData.Substring(32, 4).Trim();

                        this.CurrentSystemParameter3.ExternalOut4Mode = receiveData.Substring(36, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut4DelayTime = receiveData.Substring(40, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut4RunTime = receiveData.Substring(44, 4).Trim();

                        this.CurrentSystemParameter3.ExternalOut9Mode = receiveData.Substring(48, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut9DelayTime = receiveData.Substring(52, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut9RunTime = receiveData.Substring(56, 4).Trim();

                        this.CurrentSystemParameter3.ExternalOut10Mode = receiveData.Substring(60, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut10DelayTime = receiveData.Substring(64, 4).Trim();
                        this.CurrentSystemParameter3.ExternalOut10RunTime = receiveData.Substring(68, 4).Trim();

                        this.CurrentSystemParameter3.Dummy1 = receiveData.Substring(72, 4).Trim();
                        this.CurrentSystemParameter3.Dummy2 = receiveData.Substring(76, 4).Trim();
                        #endregion
                        // Read SystemParameter4
                        this.TransferDataStream(CommunicationCommand.Read, CommunicationID.MainBoard, CommunicationAddress._9504_SystemParameterRead4, "");
                        break;
                    case "9504":
                        #region Value Assign
                        this.CurrentSystemParameter4.AutoZero1Time = receiveData.Substring(0, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero1Range = receiveData.Substring(4, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero1Variate = receiveData.Substring(8, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero1Mode = receiveData.Substring(12, 4).Trim();

                        this.CurrentSystemParameter4.AutoZero2Mode = receiveData.Substring(16, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero2Time = receiveData.Substring(20, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero2Range = receiveData.Substring(24, 4).Trim();
                        this.CurrentSystemParameter4.AutoZero2Variate = receiveData.Substring(28, 4).Trim();

                        this.CurrentSystemParameter4.Dummy1 = receiveData.Substring(32, 4).Trim();
                        this.CurrentSystemParameter4.Dummy2 = receiveData.Substring(36, 4).Trim();
                        this.CurrentSystemParameter4.Dummy3 = receiveData.Substring(40, 4).Trim();
                        this.CurrentSystemParameter4.Dummy4 = receiveData.Substring(44, 4).Trim();
                        this.CurrentSystemParameter4.Dummy5 = receiveData.Substring(48, 4).Trim();
                        this.CurrentSystemParameter4.Dummy6 = receiveData.Substring(52, 4).Trim();
                        #endregion
                        this.TransferProductParameter(this.SystemConfig.ProductNumber);
                        break;
                    default:
                        break;
                }
            }
            catch
            {
                ret = -1;
            }

            return ret;
        }
        // 파라미터 쓰기 응답
        private int ReceiveCommandPW0(string lane, string address, string receiveData)
        {
            int ret = 0;
            DataStore.ResponseData response = DataStore.ResponseData.NAK;

            try
            {
                if (receiveData == "0")
                    response = DataStore.ResponseData.NAK;
                else
                    response = DataStore.ResponseData.ACK;

                switch (address)
                {
                    case "4004":
                        if (response == DataStore.ResponseData.ACK)
                            this.TransferDataStream(CommunicationCommand.Read, CommunicationID.MainBoard, CommunicationAddress.ParameterRead4901, "");
                        break;
                    case "4005":
                        if (response == DataStore.ResponseData.ACK)
                            this.TransferDataStream(CommunicationCommand.Read, CommunicationID.MainBoard, CommunicationAddress.ParameterRead4902, "");
                        break;
                    case "9006":
                        if (response == DataStore.ResponseData.ACK)
                            this.TransferProductParameter(this.SystemConfig.ProductNumber); 
                        break;
                    case "9013":
                        if (response == DataStore.ResponseData.ACK)
                            this.TransferDataStream(CommunicationCommand.Read, CommunicationID.MainBoard, CommunicationAddress.ProductNumber, "");
                        break;
                    default:
                        break;
                }
            }
            catch
            {
                ret = -1;
            }

            return ret;
        }
        // Bypass to motor
        private int ReceiveCommandPB0(string lane, string address, string receiveData)
        {
            int ret = 0;
            DataStore.ResponseData response = DataStore.ResponseData.NAK;

            try
            {
                if (receiveData == "0000")
                    response = DataStore.ResponseData.NAK;
                else
                    response = DataStore.ResponseData.ACK;

                switch (address)
                {
                    case "1101":
                        break;
                    case "1102":
                        break;
                    case "1103":
                        break;
                    default:
                        break;
                }
            }
            catch
            {
                ret = -1;
            }

            return ret;
        }

        // 정지시 중량
        private int ReceiveCommandSN0(string lane, string receiveData)
        {
            int ret = 0;

            try
            {
                switch (lane)
                {
                    case "A":
                        #region Value Assign

                        if (this.CurrentSystemStatus.Equipment == DataStore.EquipmentStatus.Stop)
                        {
                            this.CurrentWeightData.Status = Helper.StringToWeightStatus(receiveData.Substring(0, 2));
                            this.ConverterAlarm(ref this.CurrentWeightData, receiveData.Substring(2, 3));
                            this.CurrentWeightData.Weight = Helper.StringToWeight(receiveData.Substring(5, 5), this.SystemConfig.DecimalPlaces);
                            this.CurrentWeightData.ADCValue = receiveData.Substring(10, 5);
                        }
                        else
                        {
                            this.CurrentWeightData.Status = Helper.StringToWeightStatus(receiveData.Substring(0, 2));
                            this.ConverterAlarm(ref this.CurrentWeightData, receiveData.Substring(2, 3));
                        }

                        #endregion
                        if (this.CurrentSystemStatus.CurrentDisplay == DataStore.DisplayStore.MainDisplay)
                            this.ChildFormMainDisplay.UpdateStopWeightDisplay(this.CurrentSystemStatus.Equipment, this.CurrentWeightData);
                        break;
                    default:
                        break;
                }
            }
            catch
            {
                ret = -1;
            }

            return ret;
        }
        // 운전시 중량
        private int ReceiveCommandSR0(string lane, string receiveData)
        {
            int ret = 0;

            try
            {
                switch (lane)
                {
                    case "A":
                        #region Value Assign
                        this.CurrentWeightData.JudgmentStatus = Helper.StringToJudgmentStatus(receiveData.Substring(0, 2));
                        this.ConverterAlarm(ref this.CurrentWeightData, receiveData.Substring(2, 3));
                        this.CurrentWeightData.Weight = Helper.StringToWeight(receiveData.Substring(5, 5), this.SystemConfig.DecimalPlaces);
                        this.CurrentWeightData.WeightString = receiveData.Substring(5, 5);
                        this.CurrentWeightData.ADCValue = receiveData.Substring(10, 5);
                        this.CurrentWeightData.ProductionSpeed = int.Parse(receiveData.Substring(15, 4).Trim());
                        this.CurrentWeightData.PassAlarmCount = receiveData.Substring(19, 4).Trim();

                        this.CurrentWeightData.WeightSum(this.CurrentWeightData.JudgmentStatus);
                        #endregion

                        #region 통신
                        // 통신 COM3
                        if (this.SystemConfig.COM3Mode != 0)
                        {
                            #region COM3
                            switch (this.SystemConfig.COM3Mode)
                            {
                                case 1:
                                    this.TransferSerialCOM3(this.Transfer_1_STD1(this.SystemConfig, this.CurrentWeightData, this.CurrentProductItem));
                                    break;
                                default:
                                    break;
                            }
                            #endregion
                        }
                        // 통신 COM4
                        if (this.SystemConfig.COM4Mode != 0)
                        {
                            #region COM4
                            switch (this.SystemConfig.COM4Mode)
                            {
                                case 1:
                                    this.TransferSerialCOM4(this.Transfer_1_STD1(this.SystemConfig, this.CurrentWeightData, this.CurrentProductItem));
                                    break;
                                default:
                                    break;
                            }
                            #endregion
                        }
                        #endregion

                        if (this.CurrentSystemStatus.CurrentDisplay == DataStore.DisplayStore.MainDisplay)
                        {
                            this.ChildFormMainDisplay.UpdateStartWeightDisplay(this.CurrentSystemStatus.Equipment, this.CurrentWeightData);

                            if (this.CurrentWeightData.JudgmentStatus != DataStore.JudgmentStatus.Empty)
                                this.DataBackup(this.CurrentWeightData);
                            
                            // 표준분포
                            this.CurrentWeightData.SetNormalDistribution(this.CurrentProductItem.CollectionNormalDistributionRange, this.CurrentWeightData.WeightString);
                        }
                        break;
                    default:
                        break;
                }
            }
            catch
            {
                ret = -1;
            }

            return ret;
        }
        // 중량조정시 중량
        private int ReceiveCommandSC0(string lane, string receiveData)
        {
            int ret = 0;

            switch (lane)
            {
                case "A":
                    #region Value Assign
                    this.CurrentWeightData.Status = Helper.StringToWeightStatus(receiveData.Substring(0, 2));
                    this.ConverterAlarm(ref this.CurrentWeightData, receiveData.Substring(2, 3));
                    this.CurrentWeightData.Weight = Helper.StringToWeight(receiveData.Substring(5, 5), this.SystemConfig.DecimalPlaces);
                    this.CurrentWeightData.ADCValue = receiveData.Substring(10, 5);
                    #endregion
                    this.ChildFormMenu.CenterSystemCalibration.UpdateWeightDisplay(this.CurrentSystemStatus.Equipment, this.CurrentWeightData);
                    break;
                default:
                    break;
            }

            return ret;
        }
        // IO테스트-IN
        private int ReceiveCommandST0(string lane, string receiveData)
        {
            int ret = 0;

            switch (lane)
            {
                case "0":
                    #region Value Assign
                    for (int i = 0; i < 8; i++)
                        this.CollectionIOTest_InputData[i] = receiveData.Substring(i, 1);
                    #endregion
                    if (this.CurrentSystemStatus.CurrentMode == DataStore.DisplayMode.IOTest)
                        this.ChildFormMenu.CenterSystemIOTest.UpdateInputRead(this.CollectionIOTest_InputData);
                    break;
                default:
                    break;
            }

            return ret;
        }
        // 판정설정시 중량 - 정지
        private int ReceiveCommandSF0(string lane, string receiveData)
        {
            int ret = 0;

            switch (lane)
            {
                case "A":
                    #region Value Assign
                    this.CurrentWeightData.Status = Helper.StringToWeightStatus(receiveData.Substring(0, 2));
                    this.ConverterAlarm(ref this.CurrentWeightData, receiveData.Substring(2, 3));
                    this.CurrentWeightData.Weight = Helper.StringToWeight(receiveData.Substring(5, 5), this.SystemConfig.DecimalPlaces);
                    this.CurrentWeightData.ADCValue = receiveData.Substring(10, 5);
                    #endregion
                    this.ChildFormMenu.CenterSystemJudgmentSetting.UpdateStopWeightDisplay(this.CurrentSystemStatus.Equipment, this.CurrentWeightData);
                    break;
                default:
                    break;
            }

            return ret;
        }
        // 판정설정 그래프
        private int ReceiveCommandSG0(string lane, string receiveData)
        {
            int ret = 0, temp = 15;

            switch (lane)
            {
                case "A":
                    #region Value Assign
                    this.CurrentWeightData.Status = Helper.StringToWeightStatus(receiveData.Substring(0, 2));
                    this.ConverterAlarm(ref this.CurrentWeightData, receiveData.Substring(2, 3));
                    this.CurrentWeightData.Weight = Helper.StringToWeight(receiveData.Substring(5, 5), this.SystemConfig.DecimalPlaces);
                    this.CurrentWeightData.ADCValue = receiveData.Substring(10, 5);

                    for (int i = 0; i < this.CollectionGraphData.Count; i++)
                    {
                        this.CollectionGraphData[i] = int.Parse(receiveData.Substring(temp, 5));
                        temp += 5;
                    }
                    #endregion
                    this.ChildFormMenu.CenterSystemJudgmentSetting.UpdateGraphDataDisplay(this.CurrentSystemStatus.Equipment, this.CurrentWeightData, this.CollectionGraphData);
                    break;
                default:
                    break;
            }

            return ret;
        }
        #endregion

        #region Communication protocol
        public string PadLeft(int length, string sValue)
        {
            string temp;

            temp = sValue.PadLeft(length, ' ');

            return temp;
        }

        private string Transfer_1_STD1(SystemConfigurationItem system, WeightData weight, ProductItem product)
        {
            StringBuilder sb = new StringBuilder();

            if (weight.JudgmentStatus == DataStore.JudgmentStatus.Empty)
                return "";

            sb.Append((char)0x02);
            sb.Append(string.Format("IN{0:000}", system.EquipmentID));
            sb.Append(string.Format("{0:0000}", product.Number));

            sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces(product.UnderRange, this.SystemConfig.DecimalPlaces)));
            sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces(product.PassRange, this.SystemConfig.DecimalPlaces)));
            sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces(product.OverRange, this.SystemConfig.DecimalPlaces)));

            switch (weight.JudgmentStatus)
            {
                case DataStore.JudgmentStatus.Empty:
                    break;
                case DataStore.JudgmentStatus.Under:
                    sb.Append("U");
                    break;
                case DataStore.JudgmentStatus.Pass:
                    sb.Append("P");
                    break;
                case DataStore.JudgmentStatus.Over:
                    sb.Append("O");
                    break;
                case DataStore.JudgmentStatus.Double:
                    sb.Append("D");
                    break;
                case DataStore.JudgmentStatus.Metal:
                    sb.Append("M");
                    break;
                case DataStore.JudgmentStatus.ExNg:
                    sb.Append("E");
                    break;
                default:
                    sb.Append("E");
                    break;
            }

            double weightWithoutSign = weight.Weight;
            if (weight.Weight <= 0.0)
            {
                sb.Append("-");
                weightWithoutSign = weightWithoutSign * -1.0;
            }
            else
            {
                sb.Append(" ");
            }

            sb.Append(this.PadLeft(6, Helper.DoubleToString(weightWithoutSign, this.SystemConfig.DecimalPlaces)));
            sb.Append((char)0x03);

            return sb.ToString();
        }
        private string Transfer_2_Remote(WeightData weight, ProductItem product)
        {
            StringBuilder sb = new StringBuilder();

            if (weight.JudgmentStatus == DataStore.JudgmentStatus.Empty)
                return "";

            sb.Append((char)0x02);
            sb.Append("01");

            switch (weight.JudgmentStatus)
            {
                case DataStore.JudgmentStatus.Empty:
                    break;
                case DataStore.JudgmentStatus.Under:
                    sb.Append("U");
                    break;
                case DataStore.JudgmentStatus.Pass:
                    sb.Append("P");
                    break;
                case DataStore.JudgmentStatus.Over:
                    sb.Append("O");
                    break;
                case DataStore.JudgmentStatus.Double:
                    sb.Append("D");
                    break;
                case DataStore.JudgmentStatus.Metal:
                    sb.Append("M");
                    break;
                case DataStore.JudgmentStatus.ExNg:
                    sb.Append("E");
                    break;
                default:
                    sb.Append(" ");
                    break;
            }

            sb.Append(this.PadLeft(6, Helper.DoubleToString(weight.Weight, this.SystemConfig.DecimalPlaces)));
            sb.Append((char)0x03);

            return sb.ToString();
        }
        private string Transfer_3_Print(WeightData weight, ProductItem product)
        {
            string sValue = "";
            StringBuilder sb = new StringBuilder();

            if (weight.JudgmentStatus == DataStore.JudgmentStatus.Empty)
                return "";

            sb.Append(Helper.StringZeroFillDigits4(product.Number.ToString()));
            sb.Append(string.Format("{0,8}", weight.JudgmentStatus));

            sb.Append(this.PadLeft(10, Helper.DoubleToString(weight.Weight, this.SystemConfig.DecimalPlaces)));

            sValue = weight.TotalCount.ToString();
            sb.Append(sValue.PadLeft(10, ' '));

            return sb.ToString();
        }
        private string Transfer_4_STD2(SystemConfigurationItem system, WeightData weight, ProductItem product)
        {
            StringBuilder sb = new StringBuilder();

            if (weight.JudgmentStatus == DataStore.JudgmentStatus.Empty)
                return "";

            sb.Append((char)0x02);
            sb.Append(string.Format("IN{0:000}", system.EquipmentID));
            sb.Append(string.Format("{0:0000}", product.Number));

            sb.Append(this.PadLeft(6, Helper.StringToDecimalPlaces(product.UnderRange, this.SystemConfig.DecimalPlaces)));
            sb.Append(this.PadLeft(6, Helper.StringToDecimalPlaces(product.PassRange, this.SystemConfig.DecimalPlaces)));
            sb.Append(this.PadLeft(6, Helper.StringToDecimalPlaces(product.OverRange, this.SystemConfig.DecimalPlaces)));

            sb.Append(this.PadLeft(7, weight.UnderCount.ToString()));
            sb.Append(this.PadLeft(7, weight.PassCount.ToString()));
            sb.Append(this.PadLeft(7, weight.OverCount.ToString()));
            sb.Append(this.PadLeft(7, weight.ExNGCount.ToString()));
            sb.Append(this.PadLeft(7, weight.TotalCount.ToString()));

            switch (weight.JudgmentStatus)
            {
                case DataStore.JudgmentStatus.Empty:
                    break;
                case DataStore.JudgmentStatus.Under:
                    sb.Append("U");
                    break;
                case DataStore.JudgmentStatus.Pass:
                    sb.Append("P");
                    break;
                case DataStore.JudgmentStatus.Over:
                    sb.Append("O");
                    break;
                case DataStore.JudgmentStatus.Double:
                    sb.Append("D");
                    break;
                case DataStore.JudgmentStatus.Metal:
                    sb.Append("M");
                    break;
                case DataStore.JudgmentStatus.ExNg:
                    sb.Append("E");
                    break;
                default:
                    sb.Append("E");
                    break;
            }

            double weightWithoutSign = weight.Weight;
            if (weight.Weight <= 0.0)
            {
                sb.Append("-");
                weightWithoutSign = weightWithoutSign * -1.0;
            }
            else
            {
                sb.Append(" ");
            }

            sb.Append(this.PadLeft(6, Helper.DoubleToString(weightWithoutSign, this.SystemConfig.DecimalPlaces)));
            sb.Append((char)0x03);

            return sb.ToString();
        }
        #endregion

        #region Serial COM3
        public void OpenSerialCOM3()
        {
            if (this.SystemConfig.COM3Mode == 0)
                return;

            if (this.smartSerialPort3.IsOpen == true)
                this.smartSerialPort3.Close();

            switch (this.SystemConfig.COM3BaudRate)
            {
                case 0:
                    this.smartSerialPort3.Baud_Rate = SmartSerialPort.BAUDRATE._9600bps;
                    break;
                case 1:
                    this.smartSerialPort3.Baud_Rate = SmartSerialPort.BAUDRATE._19200bps;
                    break;
                case 2:
                    this.smartSerialPort3.Baud_Rate = SmartSerialPort.BAUDRATE._38400bps;
                    break;
                case 3:
                    this.smartSerialPort3.Baud_Rate = SmartSerialPort.BAUDRATE._57600bps;
                    break;
                case 4:
                    this.smartSerialPort3.Baud_Rate = SmartSerialPort.BAUDRATE._115200bps;
                    break;
                default:
                    this.smartSerialPort3.Baud_Rate = SmartSerialPort.BAUDRATE._9600bps;
                    break;
            }

            this.smartSerialPort3.Open();
        }
        public void CloseSerialCOM3()
        {
            this.smartSerialPort3.Close();
        }
        public bool CheckOpenCOM3()
        {
            if (this.smartSerialPort3.IsOpen == true)
                return true;
            else
                return false;
        }
        public void TransferDirectSerialCOM3(string strTemp)
        {
            this.smartSerialPort3.WriteNoneFrame(strTemp, SmartSerialPort.CODETYPES.ASCIICODE);
        }
        public void TransferDirectSerialCOM3(byte[] buffer)
        {
            this.smartSerialPort3.WriteNoneFrame(buffer);
        }
        public void TransferDirectSerialCOM3RawData(string strTemp)
        {
            this.smartSerialPort3.RawSerialPort.Write(strTemp);
        }
        public void TransferDirectSerialCOM3RawData(byte[] buffer)
        {
            this.smartSerialPort3.RawSerialPort.Write(buffer, 0, buffer.Length);
        }
        public void TransferSerialCOM3(string strTemp)
        {
            if (this.smartSerialPort3.IsOpen == true)
                this.smartSerialPort3.WriteNoneFrame(strTemp, SmartSerialPort.CODETYPES.ASCIICODE);
        }
        public void TransferSerialCOM3(byte[] buffer)
        {
            if (this.smartSerialPort3.IsOpen == true)
                this.smartSerialPort3.WriteNoneFrame(buffer);
        }
        public void TransferSerialCOM3RawData(byte[] buffer)
        {
            if (this.smartSerialPort3.IsOpen == true)
                //RawSerialPort 기능을 사용하여 데이터를 전송
                this.smartSerialPort3.RawSerialPort.Write(buffer, 0, buffer.Length);
        }
        public void ReceiveSerialCOM3()
        {
            int ret = 0;
            string strTemp = "";
            byte[] readByte;

            SmartSerialPort.FRAMEDATAREADSTATUS receiveDataState = SmartSerialPort.FRAMEDATAREADSTATUS.EMPTY;

            try
            {
                receiveDataState = this.smartSerialPort3.ReadQueue(out readByte);
                strTemp = Encoding.Default.GetString(readByte, 0, readByte.Length);
            }
            catch
            {
                return;
            }

            if ((receiveDataState == SmartSerialPort.FRAMEDATAREADSTATUS.EMPTY) || (receiveDataState == SmartSerialPort.FRAMEDATAREADSTATUS.FAILDATA))
                return;
        }

        public void ChangeSerialCOM3FrameSeparateType(DataStore.SeparateType type)
        {
            // 통신 포트 설정
            if (this.smartSerialPort3.IsOpen == true)
                this.smartSerialPort3.Close();

            if (type == DataStore.SeparateType.ETXONLY)
            {
                this.smartSerialPort3.FrameSeparationType = SmartSerialPort.FRAMESEPARATIONTYPES.ETXONLY;

                byte[] etxCodes = new byte[2];
                etxCodes[0] = 13;
                etxCodes[1] = 10;
                this.smartSerialPort3.ETXCodes = etxCodes;
            }
            else if (type == DataStore.SeparateType.STXANDETX)
            {
                this.smartSerialPort3.FrameSeparationType = SmartSerialPort.FRAMESEPARATIONTYPES.STXANDETX;

                this.smartSerialPort3.STXCode = 2;
                this.smartSerialPort3.ETXCode = 3;
            }
            else if (type == DataStore.SeparateType.NONEFRAME_READTIMEOUT)
            {
                this.smartSerialPort3.FrameSeparationType = SmartSerialPort.FRAMESEPARATIONTYPES.NONEFRAME_READTIMEOUT;
                this.smartSerialPort3.ReadTimeout = 300;
            }
            else
            {
                this.smartSerialPort3.FrameSeparationType = SmartSerialPort.FRAMESEPARATIONTYPES.STXONLY;
                this.smartSerialPort3.STXCode = 2;
            }

            this.smartSerialPort3.Open();
        }
        public void ChangeSerialCOM3ReceiveDetect(SmartSerialPort.RECEIVEDETECTTYPE detectType)
        {
            this.smartSerialPort3.ReceiveDetect = detectType;
        }
        public void ChangeSerialCOM3FrameBufferSize(uint size)
        {
            this.smartSerialPort3.FrameBufferSize = size;
        }
        #endregion
        #region Serial COM4
        public void OpenSerialCOM4()
        {
            if (this.SystemConfig.COM4Mode == 0)
                return;

            if (this.smartSerialPort4.IsOpen == true)
                this.smartSerialPort4.Close();

            switch (this.SystemConfig.COM4BaudRate)
            {
                case 0:
                    this.smartSerialPort4.Baud_Rate = SmartSerialPort.BAUDRATE._9600bps;
                    break;
                case 1:
                    this.smartSerialPort4.Baud_Rate = SmartSerialPort.BAUDRATE._19200bps;
                    break;
                case 2:
                    this.smartSerialPort4.Baud_Rate = SmartSerialPort.BAUDRATE._38400bps;
                    break;
                case 3:
                    this.smartSerialPort4.Baud_Rate = SmartSerialPort.BAUDRATE._57600bps;
                    break;
                case 4:
                    this.smartSerialPort4.Baud_Rate = SmartSerialPort.BAUDRATE._115200bps;
                    break;
                default:
                    this.smartSerialPort4.Baud_Rate = SmartSerialPort.BAUDRATE._9600bps;
                    break;
            }

            this.smartSerialPort4.Open();
        }
        public void CloseSerialCOM4()
        {
            this.smartSerialPort4.Close();
        }
        public bool CheckOpenCOM4()
        {
            if (this.smartSerialPort4.IsOpen == true)
                return true;
            else
                return false;
        }
        public void TransferDirectSerialCOM4(string strTemp)
        {
            this.smartSerialPort4.WriteNoneFrame(strTemp, SmartSerialPort.CODETYPES.ASCIICODE);
        }
        public void TransferDirectSerialCOM4(byte[] buffer)
        {
            this.smartSerialPort4.WriteNoneFrame(buffer);
        }
        public void TransferSerialCOM4(string strTemp)
        {
            if (this.smartSerialPort4.IsOpen == true)
                this.smartSerialPort4.WriteNoneFrame(strTemp, SmartSerialPort.CODETYPES.ASCIICODE);
        }
        public void TransferSerialCOM4(byte[] buffer)
        {
            if (this.smartSerialPort4.IsOpen == true)
                this.smartSerialPort4.WriteNoneFrame(buffer);
        }
        public void ChangeSerialCOM4FrameSeparateType(DataStore.SeparateType type)
        {
            // 통신 포트 설정
            if (this.smartSerialPort4.IsOpen == true)
                this.smartSerialPort4.Close();

            if (type == DataStore.SeparateType.ETXONLY)
            {
                this.smartSerialPort4.FrameSeparationType = SmartSerialPort.FRAMESEPARATIONTYPES.ETXONLY;

                byte[] etxCodes = new byte[2];
                etxCodes[0] = 13;
                etxCodes[1] = 10;
                this.smartSerialPort4.ETXCodes = etxCodes;
            }
            else if (type == DataStore.SeparateType.STXANDETX)
            {
                this.smartSerialPort4.FrameSeparationType = SmartSerialPort.FRAMESEPARATIONTYPES.STXANDETX;

                this.smartSerialPort4.STXCode = 2;
                this.smartSerialPort4.ETXCode = 3;
            }
            else if (type == DataStore.SeparateType.NONEFRAME_READTIMEOUT)
            {
                this.smartSerialPort4.FrameSeparationType = SmartSerialPort.FRAMESEPARATIONTYPES.NONEFRAME_READTIMEOUT;
                this.smartSerialPort4.ReadTimeout = 300;
            }
            else
            {
                this.smartSerialPort4.FrameSeparationType = SmartSerialPort.FRAMESEPARATIONTYPES.STXONLY;
                this.smartSerialPort4.STXCode = 2;
            }

            this.smartSerialPort4.Open();
        }
        #endregion

        #region Data Backup
        private void RemoveUsbBackupFile()
        {
            bool directoryCheck = false;

            try
            {
                string dday = string.Format("{0:yyyyMMdd}", DateTime.Now.AddDays(-180)) + ".csv";

                DirectoryInfo dir = new DirectoryInfo(this.PathDataBackupFolder);

                directoryCheck = dir.Exists;
                // 폴더 체크
                if (directoryCheck == false)
                    dir.Create();

                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo subfile in files)
                {
                    if (subfile.Name.StartsWith("20"))  // 날짜 비교하여 180일 지난화일은 삭제함 
                    {
                        if (subfile.Name.CompareTo(dday) < 0)
                        {
                            subfile.Delete();
                        }
                    }
                }
            }
            catch
            {

            }

        }
        private void DataBackup(WeightData item)
        {
            bool fileCheck = false, directoryCheck = false;
            string fullFilePath = "";
            StreamWriter sw;
            DateTime time = DateTime.Now;

            this.RemoveUsbBackupFile();

            if (this.SystemConfig.IsDataBackup == true)
            {
                fullFilePath = string.Format("{0}{1:yyyyMMdd}_{2}_{3}.csv", this.PathDataBackupFolder, DateTime.Now, this.SystemConfig.UsbID, this.CurrentProductItem.Name);

                DirectoryInfo di = new DirectoryInfo(this.PathDataBackupFolder);
                directoryCheck = di.Exists;
                // 폴더 체크
                if (directoryCheck == false)
                    di.Create();
                // 파일 체크
                FileInfo fileInfo = new FileInfo(fullFilePath);
                fileCheck = fileInfo.Exists;

                sw = new StreamWriter(fullFilePath, true, Encoding.Default);

                if (fileCheck == false)
                {
                    sw.Write("Date");
                    sw.Write(",");
                    sw.Write("Time");
                    sw.Write(",");
                    sw.Write("P_No");
                    sw.Write(",");
                    sw.Write("Name");
                    sw.Write(",");
                    sw.Write("Lot");
                    sw.Write(",");
                    sw.Write("Weight");
                    sw.Write(",");
                    sw.Write("Grade");
                    sw.WriteLine();
                }

                sw.Write(string.Format("{0:yyyy-MM-dd}", time));
                sw.Write(",");
                sw.Write(string.Format("{0:HH:mm:ss}", time));
                sw.Write(",");
                sw.Write(this.CurrentProductItem.Number);
                sw.Write(",");
                sw.Write(this.CurrentProductItem.Name);
                sw.Write(",");
                sw.Write(this.CurrentProductItem.LotNo);
                sw.Write(",");
                sw.Write(Helper.DoubleToString(item.Weight, this.SystemConfig.DecimalPlaces));
                sw.Write(",");
                sw.Write(item.JudgmentStatus);
                sw.WriteLine();

                sw.Close();
            }
        }
        #endregion

        #region SystemConfiguration File
        private void CreateSystemConfigurationFile()
        {
            StructSystemConfigurationItem structItem;

            this.SystemConfig.Initialization();

            structItem.IsDataBackup = this.SystemConfig.IsDataBackup;

            structItem.EquipmentID = this.SystemConfig.EquipmentID;
            structItem.DecimalPlaces = this.SystemConfig.DecimalPlaces;
            structItem.ProductNumber = this.SystemConfig.ProductNumber;
            structItem.UsbID = this.SystemConfig.UsbID;
            structItem.COM3BaudRate = this.SystemConfig.COM3BaudRate;
            structItem.COM3Mode = this.SystemConfig.COM3Mode;
            structItem.COM4BaudRate = this.SystemConfig.COM4BaudRate;
            structItem.COM4Mode = this.SystemConfig.COM4Mode;

            structItem.SerialNumber = this.SystemConfig.SerialNumber;
            structItem.Language = this.SystemConfig.Language;
            structItem.Unit = this.SystemConfig.Unit;

            structItem.DummyBool1 = false;
            structItem.DummyBool2 = false;
            structItem.DummyBool3 = false;
            structItem.DummyBool4 = false;
            structItem.DummyBool5 = false;
            structItem.DummyInt1 = 0;
            structItem.DummyInt2 = 0;
            structItem.DummyInt3 = 0;
            structItem.DummyInt4 = 0;
            structItem.DummyInt5 = 0;
            structItem.DummyString1 = "";
            structItem.DummyString2 = "";
            structItem.DummyString3 = "";
            structItem.DummyString4 = "";
            structItem.DummyString5 = "";

            this.smartFileIO.WriteStructure(structItem, 0);
        }
        public void SaveSystemConfigurationFile(SystemConfigurationItem item)
        {
            string fullFilePath = "";
            bool fileCheck = false;
            StructSystemConfigurationItem structItem;

            fullFilePath = this.PathSystemFileFolder + "system.cfg";
            this.smartFileIO.FilePathName = fullFilePath;

            FileInfo fileInfo = new FileInfo(fullFilePath);
            fileCheck = fileInfo.Exists;

            if (fileCheck == true)
                this.smartFileIO.Open();
            else
            {
                this.smartFileIO.Open();

                this.CreateSystemConfigurationFile();
            }

            structItem.IsDataBackup = item.IsDataBackup;

            structItem.EquipmentID = item.EquipmentID;
            structItem.DecimalPlaces = item.DecimalPlaces;
            structItem.ProductNumber = item.ProductNumber;
            structItem.UsbID = item.UsbID;
            structItem.COM3BaudRate = item.COM3BaudRate;
            structItem.COM3Mode = item.COM3Mode;
            structItem.COM4BaudRate = item.COM4BaudRate;
            structItem.COM4Mode = item.COM4Mode;

            structItem.SerialNumber = item.SerialNumber;
            structItem.Language = item.Language;
            structItem.Unit = item.Unit;

            structItem.DummyBool1 = false;
            structItem.DummyBool2 = false;
            structItem.DummyBool3 = false;
            structItem.DummyBool4 = false;
            structItem.DummyBool5 = false;

            structItem.DummyInt1 = 0;
            structItem.DummyInt2 = 0;
            structItem.DummyInt3 = 0;
            structItem.DummyInt4 = 0;
            structItem.DummyInt5 = 0;

            structItem.DummyString1 = "";
            structItem.DummyString2 = "";
            structItem.DummyString3 = "";
            structItem.DummyString4 = "";
            structItem.DummyString5 = "";

            this.smartFileIO.WriteStructure(structItem, 0);
            this.smartFileIO.Close();
        }
        public void LoadSystemConfigurationFile()
        {
            string fullFilePath = "";
            bool fileCheck = false;
            StructSystemConfigurationItem structItem;

            fullFilePath = this.PathSystemFileFolder + "system.cfg";
            this.smartFileIO.FilePathName = fullFilePath;

            FileInfo fileInfo = new FileInfo(fullFilePath);
            fileCheck = fileInfo.Exists;

            if (fileCheck == true)
                this.smartFileIO.Open();
            else
            {
                this.smartFileIO.Open();

                this.CreateSystemConfigurationFile();
            }

            try
            {
                structItem = (StructSystemConfigurationItem)this.smartFileIO.ReadStructure(0, typeof(StructSystemConfigurationItem));

                this.SystemConfig.IsDataBackup = structItem.IsDataBackup;

                this.SystemConfig.EquipmentID = structItem.EquipmentID;
                this.SystemConfig.DecimalPlaces = structItem.DecimalPlaces;
                this.SystemConfig.ProductNumber = structItem.ProductNumber;
                this.SystemConfig.UsbID = structItem.UsbID;              
                this.SystemConfig.COM3BaudRate = structItem.COM3BaudRate;
                this.SystemConfig.COM3Mode = structItem.COM3Mode;
                this.SystemConfig.COM4BaudRate = structItem.COM4BaudRate;
                this.SystemConfig.COM4Mode = structItem.COM4Mode;

                this.SystemConfig.SerialNumber = structItem.SerialNumber;
                this.SystemConfig.Language = structItem.Language;
                this.SystemConfig.Unit = structItem.Unit;
            }
            catch
            {
                DialogFormMessage myMsg = new DialogFormMessage(17, this.SystemConfig.Language);
                myMsg.ShowDialog();

                this.smartFileIO.Close();
            }

            this.smartFileIO.Close();
        }
        #endregion

        #region Product File
        private void CreateProductFile()
        {
            StructProductItem structItem;

            this.CurrentProductItem.Initialization();

            for (int i = 0; i < 1000; i++)
            {
                structItem.Number = i + 1;
                structItem.Name = string.Format("Product {0}", i + 1);
                structItem.LotNo = string.Format("Lot {0}", i + 1);
                structItem.PassRange = this.CurrentProductItem.PassRange;
                structItem.OverRange = this.CurrentProductItem.OverRange;
                structItem.UnderRange = this.CurrentProductItem.UnderRange;
                structItem.TareRange = this.CurrentProductItem.TareRange;
                structItem.DummyString1 = "";
                structItem.DummyString2 = "";
                structItem.DummyString3 = "";
                structItem.DummyString4 = "";

                this.smartFileIO.WriteStructure_Begin(structItem, i);
            }
            this.smartFileIO.WriteStructure_End();
        }
        public void SaveProductFile(ProductItem item, int index)
        {
            bool fileCheck = false;
            string fullFilePath = "";
            StructProductItem structItem;

            fullFilePath = this.PathSystemFileFolder + "ProductItem.int";
            this.smartFileIO.FilePathName = fullFilePath;

            FileInfo fileInfo = new FileInfo(fullFilePath);
            fileCheck = fileInfo.Exists;

            if (fileCheck == true)
                this.smartFileIO.Open();
            else
            {
                this.smartFileIO.Open();
                this.CreateProductFile();
            }

            structItem.Number = item.Number;
            structItem.Name = item.Name;
            structItem.LotNo = item.LotNo;
            structItem.OverRange = item.OverRange;
            structItem.PassRange = item.PassRange;
            structItem.UnderRange = item.UnderRange;
            structItem.TareRange = item.TareRange;
            structItem.DummyString1 = "";
            structItem.DummyString2 = "";
            structItem.DummyString3 = "";
            structItem.DummyString4 = "";

            this.smartFileIO.WriteStructure_Begin(structItem, index);
            this.smartFileIO.WriteStructure_End();

            this.smartFileIO.Close();
        }
        public void LoadProductFile(ref ProductItem item, int index)
        {
            bool fileCheck = false;
            string fullFilePath = "";
            StructProductItem structItem;

            fullFilePath = this.PathSystemFileFolder + "ProductItem.int";
            this.smartFileIO.FilePathName = fullFilePath;

            FileInfo fileInfo = new FileInfo(fullFilePath);
            fileCheck = fileInfo.Exists;

            if (fileCheck == true)
                this.smartFileIO.Open();
            else
            {
                this.smartFileIO.Open();

                this.CreateProductFile();
            }

            try
            {
                if (this.smartFileIO.ReadStructureAllBuffer() == true)
                {
                    structItem = (StructProductItem)this.smartFileIO.ReadStructureBuffer(typeof(StructProductItem), index);

                    item.Number = structItem.Number;
                    item.Name = structItem.Name;
                    item.LotNo = structItem.LotNo;
                    item.PassRange = structItem.PassRange;
                    item.OverRange = structItem.OverRange;
                    item.UnderRange = structItem.UnderRange;
                    item.TareRange = structItem.TareRange;
                }
            }
            catch
            {
                DialogFormMessage myMsg = new DialogFormMessage(17, this.SystemConfig.Language);
                myMsg.ShowDialog();

                this.smartFileIO.Close();
            }

            this.smartFileIO.Close();
        }
        public void LoadProductName(ref Collection<string> values)
        {
            string fullFilePath = "";
            StructProductItem structItem;

            values.Clear();

            fullFilePath = this.PathSystemFileFolder + "ProductItem.int";
            this.smartFileIO.FilePathName = fullFilePath;

            this.smartFileIO.Open();

            if (this.smartFileIO.ReadStructureAllBuffer() == true)
            {
                for (int i = 0; i < 1000; i++)
                {
                    structItem = (StructProductItem)this.smartFileIO.ReadStructureBuffer(typeof(StructProductItem), i);

                    values.Add(structItem.Name);
                }
            }

            this.smartFileIO.Close();
        }
        #endregion

        #region JudgmentSet File
        private void CreateJudgmentSetFile()
        {
            StructJudgmentSetItem structItem;

            this.CurrentJudgmentSetItem.Initialization();

            for (int i = 0; i < 1000; i++)
            {
                structItem.Filter = this.CurrentJudgmentSetItem.Filter;
                structItem.DownDelayTime = this.CurrentJudgmentSetItem.DownDelayTime;
                structItem.JudgmentDelayTime = this.CurrentJudgmentSetItem.JudgmentDelayTime;
                structItem.UpDelayTime = this.CurrentJudgmentSetItem.UpDelayTime;
                structItem.JudgmentCount = this.CurrentJudgmentSetItem.JudgmentCount;
                structItem.FeedSpeed = this.CurrentJudgmentSetItem.FeedSpeed;
                structItem.DynamicCorrection = this.CurrentJudgmentSetItem.DynamicCorrection;

                structItem.Sorter1Mode = this.CurrentJudgmentSetItem.Sorter1Mode;
                structItem.Sorter1DelayTime = this.CurrentJudgmentSetItem.Sorter1DelayTime;
                structItem.Sorter1RunTime = this.CurrentJudgmentSetItem.Sorter1RunTime;
                structItem.Sorter2Mode = this.CurrentJudgmentSetItem.Sorter2Mode;
                structItem.Sorter2DelayTime = this.CurrentJudgmentSetItem.Sorter2DelayTime;
                structItem.Sorter2RunTime = this.CurrentJudgmentSetItem.Sorter2RunTime;

                structItem.DummyInt1 = 0;
                structItem.DummyInt2 = 0;
                structItem.DummyInt3 = 0;
                structItem.DummyInt4 = 0;
                structItem.DummyInt5 = 0;
                structItem.DummyString1 = "";
                structItem.DummyString2 = "";
                structItem.DummyString3 = "";
                structItem.DummyString4 = "";
                structItem.DummyString5 = "";

                this.smartFileIO.WriteStructure_Begin(structItem, i);
            }
            this.smartFileIO.WriteStructure_End();
        }
        public void SaveJudgmentSetFile(JudgmentSetItem item, int index)
        {
            bool fileCheck = false;
            string fullFilePath = "";
            StructJudgmentSetItem structItem;

            fullFilePath = this.PathSystemFileFolder + "JudgmentSetItem.int";
            this.smartFileIO.FilePathName = fullFilePath;

            FileInfo fileInfo = new FileInfo(fullFilePath);
            fileCheck = fileInfo.Exists;

            if (fileCheck == true)
                this.smartFileIO.Open();
            else
            {
                this.smartFileIO.Open();
                this.CreateJudgmentSetFile();
            }

            structItem.Filter = item.Filter;
            structItem.DownDelayTime = item.DownDelayTime;
            structItem.JudgmentDelayTime = item.JudgmentDelayTime;
            structItem.UpDelayTime = item.UpDelayTime;
            structItem.JudgmentCount = item.JudgmentCount;
            structItem.FeedSpeed = item.FeedSpeed;
            structItem.DynamicCorrection = item.DynamicCorrection;

            structItem.Sorter1Mode = item.Sorter1Mode;
            structItem.Sorter1DelayTime = item.Sorter1DelayTime;
            structItem.Sorter1RunTime = item.Sorter1RunTime;
            structItem.Sorter2Mode = item.Sorter2Mode;
            structItem.Sorter2DelayTime = item.Sorter2DelayTime;
            structItem.Sorter2RunTime = item.Sorter2RunTime;

            structItem.DummyInt1 = 0;
            structItem.DummyInt2 = 0;
            structItem.DummyInt3 = 0;
            structItem.DummyInt4 = 0;
            structItem.DummyInt5 = 0;
            structItem.DummyString1 = "";
            structItem.DummyString2 = "";
            structItem.DummyString3 = "";
            structItem.DummyString4 = "";
            structItem.DummyString5 = "";

            this.smartFileIO.WriteStructure_Begin(structItem, index);
            this.smartFileIO.WriteStructure_End();

            this.smartFileIO.Close();
        }
        public void LoadJudgmentSetFile(ref JudgmentSetItem item, int index)
        {
            bool fileCheck = false;
            string fullFilePath = "";
            StructJudgmentSetItem structItem;

            fullFilePath = this.PathSystemFileFolder + "JudgmentSetItem.int";
            this.smartFileIO.FilePathName = fullFilePath;

            FileInfo fileInfo = new FileInfo(fullFilePath);
            fileCheck = fileInfo.Exists;

            if (fileCheck == true)
                this.smartFileIO.Open();
            else
            {
                this.smartFileIO.Open();
                this.CreateJudgmentSetFile();
            }

            try
            {
                if (this.smartFileIO.ReadStructureAllBuffer() == true)
                {
                    structItem = (StructJudgmentSetItem)this.smartFileIO.ReadStructureBuffer(typeof(StructJudgmentSetItem), index);

                    item.Filter = structItem.Filter;
                    item.DownDelayTime = structItem.DownDelayTime;
                    item.JudgmentDelayTime = structItem.JudgmentDelayTime;
                    item.UpDelayTime = structItem.UpDelayTime;
                    item.JudgmentCount = structItem.JudgmentCount;
                    item.FeedSpeed = structItem.FeedSpeed;
                    item.DynamicCorrection = structItem.DynamicCorrection;

                    item.Sorter1Mode = structItem.Sorter1Mode;
                    item.Sorter1DelayTime = structItem.Sorter1DelayTime;
                    item.Sorter1RunTime = structItem.Sorter1RunTime;
                    item.Sorter2Mode = structItem.Sorter2Mode;
                    item.Sorter2DelayTime = structItem.Sorter2DelayTime;
                    item.Sorter2RunTime = structItem.Sorter2RunTime;
                }
            }
            catch
            {
                DialogFormMessage myMsg = new DialogFormMessage(17, this.SystemConfig.Language);
                myMsg.ShowDialog();

                this.smartFileIO.Close();
            }
            this.smartFileIO.Close();
        }
        #endregion

        #region Counter File
        private void CreateCounterFile()
        {
            StructCounterItem structItem;
            WeightData item = new WeightData();
            item.ClearCount();

            for (int i = 0; i < 1000; i++)
            {
                structItem.OverCount = item.OverCount;
                structItem.OverSumWeight = item.OverSumWeight;
                structItem.PassCount = item.PassCount;
                structItem.PassSumWeight = item.PassSumWeight;
                structItem.UnderCount = item.UnderCount;
                structItem.UnderSumWeight = item.UnderSumWeight;
                structItem.ExNGCount = item.ExNGCount;

                structItem.NormalDistribution1 = item.CollectionNormalDistributionCount[0];
                structItem.NormalDistribution2 = item.CollectionNormalDistributionCount[1];
                structItem.NormalDistribution3 = item.CollectionNormalDistributionCount[2];
                structItem.NormalDistribution4 = item.CollectionNormalDistributionCount[3];
                structItem.NormalDistribution5 = item.CollectionNormalDistributionCount[4];
                structItem.NormalDistribution6 = item.CollectionNormalDistributionCount[5];
                structItem.NormalDistribution7 = item.CollectionNormalDistributionCount[6];
                structItem.NormalDistribution8 = item.CollectionNormalDistributionCount[7];
                structItem.NormalDistribution9 = item.CollectionNormalDistributionCount[8];
                structItem.NormalDistribution10 = item.CollectionNormalDistributionCount[9];

                structItem.StartTime = item.StartTime;
                structItem.StopTime = item.StopTime;

                structItem.DummyInt1 = 0;
                structItem.DummyInt2 = 0;
                structItem.DummyInt3 = 0;
                structItem.DummyInt4 = 0;
                structItem.DummyInt5 = 0;

                this.smartFileIO.WriteStructure_Begin(structItem, i);
            }
            this.smartFileIO.WriteStructure_End();
        }
        public void SaveCounterFile(WeightData item, int index)
        {
            string fullFilePath = "";
            bool fileCheck = false;
            StructCounterItem structItem;

            fullFilePath = this.PathSystemFileFolder + "counterItem.int";
            this.smartFileIO.FilePathName = fullFilePath;

            FileInfo fileInfo = new FileInfo(fullFilePath);
            fileCheck = fileInfo.Exists;

            if (fileCheck == true)
                this.smartFileIO.Open();
            else
            {
                this.smartFileIO.Open();

                this.CreateCounterFile();
            }

            structItem.OverCount = item.OverCount;
            structItem.OverSumWeight = item.OverSumWeight;
            structItem.PassCount = item.PassCount;
            structItem.PassSumWeight = item.PassSumWeight;
            structItem.UnderCount = item.UnderCount;
            structItem.UnderSumWeight = item.UnderSumWeight;
            structItem.ExNGCount = item.ExNGCount;

            structItem.NormalDistribution1 = item.CollectionNormalDistributionCount[0];
            structItem.NormalDistribution2 = item.CollectionNormalDistributionCount[1];
            structItem.NormalDistribution3 = item.CollectionNormalDistributionCount[2];
            structItem.NormalDistribution4 = item.CollectionNormalDistributionCount[3];
            structItem.NormalDistribution5 = item.CollectionNormalDistributionCount[4];
            structItem.NormalDistribution6 = item.CollectionNormalDistributionCount[5];
            structItem.NormalDistribution7 = item.CollectionNormalDistributionCount[6];
            structItem.NormalDistribution8 = item.CollectionNormalDistributionCount[7];
            structItem.NormalDistribution9 = item.CollectionNormalDistributionCount[8];
            structItem.NormalDistribution10 = item.CollectionNormalDistributionCount[9];

            structItem.StartTime = item.StartTime;
            structItem.StopTime = item.StopTime;

            structItem.DummyInt1 = 0;
            structItem.DummyInt2 = 0;
            structItem.DummyInt3 = 0;
            structItem.DummyInt4 = 0;
            structItem.DummyInt5 = 0;

            this.smartFileIO.WriteStructure_Begin(structItem, index);
            this.smartFileIO.WriteStructure_End();

            this.smartFileIO.Close();
        }
        public void LoadCounterFile(ref WeightData item, int index)
        {
            string fullFilePath = "";
            bool fileCheck = false;
            StructCounterItem structItem;

            fullFilePath = this.PathSystemFileFolder + "counterItem.int";
            this.smartFileIO.FilePathName = fullFilePath;

            FileInfo fileInfo = new FileInfo(fullFilePath);
            fileCheck = fileInfo.Exists;

            if (fileCheck == true)
                this.smartFileIO.Open();
            else
            {
                this.smartFileIO.Open();

                this.CreateCounterFile();
            }

            try
            {
                if (this.smartFileIO.ReadStructureAllBuffer() == true)
                {
                    structItem = (StructCounterItem)this.smartFileIO.ReadStructureBuffer(typeof(StructCounterItem), index);

                    item.UnderCount = structItem.UnderCount;
                    item.UnderSumWeight = structItem.UnderSumWeight;
                    item.PassCount = structItem.PassCount;
                    item.PassSumWeight = structItem.PassSumWeight;
                    item.OverCount = structItem.OverCount;
                    item.OverSumWeight = structItem.OverSumWeight;
                    item.ExNGCount = structItem.ExNGCount;

                    item.CollectionNormalDistributionCount[0] = structItem.NormalDistribution1;
                    item.CollectionNormalDistributionCount[1] = structItem.NormalDistribution2;
                    item.CollectionNormalDistributionCount[2] = structItem.NormalDistribution3;
                    item.CollectionNormalDistributionCount[3] = structItem.NormalDistribution4;
                    item.CollectionNormalDistributionCount[4] = structItem.NormalDistribution5;
                    item.CollectionNormalDistributionCount[5] = structItem.NormalDistribution6;
                    item.CollectionNormalDistributionCount[6] = structItem.NormalDistribution7;
                    item.CollectionNormalDistributionCount[7] = structItem.NormalDistribution8;
                    item.CollectionNormalDistributionCount[8] = structItem.NormalDistribution9;
                    item.CollectionNormalDistributionCount[9] = structItem.NormalDistribution10;

                    item.StartTime = structItem.StartTime;
                    item.StopTime = structItem.StopTime;
                }
            }
            catch
            {
                DialogFormMessage myMsg = new DialogFormMessage(17, this.SystemConfig.Language);
                myMsg.ShowDialog();

                this.smartFileIO.Close();
            }
            this.smartFileIO.Close();
        }
        #endregion

        #region UserGroupPassword File
        private void CreateUserGroupPasswordFile()
        {
            this.CurrentSystemStatus.CurrentUser.Initialization();

            this.smartFileIO.WriteString(this.CurrentSystemStatus.CurrentUser.Level1Password, (int)DataStore.UserPassword.f0_Level1);
            this.smartFileIO.WriteString(this.CurrentSystemStatus.CurrentUser.Level2Password, (int)DataStore.UserPassword.f1_Level2);
            this.smartFileIO.WriteString(this.CurrentSystemStatus.CurrentUser.Level3Password, (int)DataStore.UserPassword.f2_Level3);
        }
        public void SaveUserGroupPasswordFile(User item)
        {
            string fullFilePath = "";
            bool fileCheck = false;

            fullFilePath = this.PathSystemFileFolder + "UserGroupPassword.int";
            this.smartFileIO.FilePathName = fullFilePath;

            FileInfo fileInfo = new FileInfo(fullFilePath);
            fileCheck = fileInfo.Exists;

            if (fileCheck == true)
                this.smartFileIO.Open();
            else
            {
                this.smartFileIO.Open();

                this.CreateUserGroupPasswordFile();
            }

            this.smartFileIO.WriteString(this.CurrentSystemStatus.CurrentUser.Level1Password, (int)DataStore.UserPassword.f0_Level1);
            this.smartFileIO.WriteString(this.CurrentSystemStatus.CurrentUser.Level2Password, (int)DataStore.UserPassword.f1_Level2);
            this.smartFileIO.WriteString(this.CurrentSystemStatus.CurrentUser.Level3Password, (int)DataStore.UserPassword.f2_Level3);

            this.smartFileIO.Close();
        }
        private void LoadUserGroupPasswordFile()
        {
            string fullFilePath = "";
            bool fileCheck = false;

            fullFilePath = this.PathSystemFileFolder + "UserGroupPassword.int";
            this.smartFileIO.FilePathName = fullFilePath;

            FileInfo fileInfo = new FileInfo(fullFilePath);
            fileCheck = fileInfo.Exists;

            if (fileCheck == true)
                this.smartFileIO.Open();
            else
            {
                this.smartFileIO.Open();

                this.CreateUserGroupPasswordFile();
            }

            try
            {
                this.CurrentSystemStatus.CurrentUser.Level1Password = this.smartFileIO.ReadString((int)DataStore.UserPassword.f0_Level1);
                this.CurrentSystemStatus.CurrentUser.Level2Password = this.smartFileIO.ReadString((int)DataStore.UserPassword.f1_Level2);
                this.CurrentSystemStatus.CurrentUser.Level3Password = this.smartFileIO.ReadString((int)DataStore.UserPassword.f2_Level3);
            }
            catch
            {
                DialogFormMessage myMsg = new DialogFormMessage(17, this.SystemConfig.Language);
                myMsg.ShowDialog();

                this.smartFileIO.Close();
            }

            this.smartFileIO.Close();
        }
        #endregion

        public void TestLog()
        {
            string fullPath = "";
            fullPath = this.PathLaunchFolder + "TestLog.txt";

            this.smartFileTestLog.FilePathName = fullPath;

            this.smartFileTestLog.Open();

            for (int i = 0; i < 40; i++)
            {
                this.smartFileTestLog.WriteString("", i);
            }
        }
        #endregion

        #region Override Member
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // 변수 초기 셋팅
            this.DefaultSetting();
            //TestLog
            //this.TestLog();

            // SystemConfiguration 파일 읽기
            this.LoadSystemConfigurationFile();

            // Counter 파일 읽기
            this.LoadCounterFile(ref this.CurrentWeightData, this.SystemConfig.ProductNumber - 1);

            // 품목 파일 읽기
            this.LoadProductFile(ref this.CurrentProductItem, this.SystemConfig.ProductNumber - 1);

            // SystemParameter 파일 읽기
            this.LoadJudgmentSetFile(ref this.CurrentJudgmentSetItem, this.SystemConfig.ProductNumber - 1);

            // UserGroupPassword 파일 읽기
            this.LoadUserGroupPasswordFile();

            // 폼 생성
            this.CreateForm();


            this.SmartSplashProgramLoad.Finish();
            this.smartForm.Show((int)DataStore.FormStore.FormMainDisplay);

            // 메인 통신 OPEN
            this.OpenSmartUartLink();

            #region Communication
            // COM3 OPEN
            if (this.SystemConfig.COM3Mode != 0)
                this.OpenSerialCOM3();

            // COM4 OPEN
            if (this.SystemConfig.COM4Mode != 0)
                this.OpenSerialCOM4();
            #endregion

            // Read SystemParameter1
            this.TransferDataStream(CommunicationCommand.Read, CommunicationID.MainBoard, CommunicationAddress._9501_SystemParameterRead1, "");

            // Mouse On
            //this.smartForm.Mode = SmartForm.RUNMODE.DEVELOPER;
            //this.smartForm.MouseCursor = SmartForm.OnOff.ON;
        }
        #endregion

        #region Event Handler
        private void smartSerialPort2_OnReadQueueEvent()
        {
            this.ReceiveData();

            // 통신 확인
            if (this.CommunicationCheckCount / 3 == 1)
            {
                this.ChildFormMainDisplay.pictureBoxCommunicationStatus.Visible = true;
                this.CommunicationCheckCount = 0;
            }
            else
            {
                this.ChildFormMainDisplay.pictureBoxCommunicationStatus.Visible = false;
                this.CommunicationCheckCount += 1;
            }
        }
        #endregion
    }
}