<file_sep>﻿using Cognex.VisionPro;
using Cognex.VisionPro.ImageFile;
using Cognex.VisionPro.ToolBlock;
using System;

namespace VisionPro_Tut.Source
{
    public class ObjectManager
    {
        //variable
        public CogImageFileTool mIFTool;
        public CogToolBlock mToolBlockProcess;
        public CogToolBlock mToolBlockAcq;
        public ulong numPass;
        public ulong numFail;
        private bool bUseCamera;

        public ObjectManager()
        {
            mToolBlockProcess = new CogToolBlock();
            mToolBlockAcq = new CogToolBlock();
            mIFTool = new CogImageFileTool();
            

            numPass = 0;
            numFail = 0;
            bUseCamera = false;
        }


        public void InitObject(MyDefine Common)
        {
            Common.Print_Infor();
            numPass = Common.numOK;
            numFail = Common.numNG;
            bUseCamera = Common.use_camera;


            mToolBlockProcess = CogSerializer.LoadObjectFromFile(Common.file_toolblock_process) as CogToolBlock;
            ToolBlock_PrintInfor(mToolBlockProcess);

            if (bUseCamera)
            {
                try
                {
                    mToolBlockAcq = CogSerializer.LoadObjectFromFile(Common.file_toolblock_acq) as CogToolBlock;
                    mToolBlockAcq.Ran += MToolBlockAcq_Ran;
                    mToolBlockAcq.Changed += MToolBlockAcq_Changed;
                    mToolBlockAcq.Running += MToolBlockAcq_Running;
                    ToolBlock_PrintInfor(mToolBlockAcq);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception {0}", e.ToString());
                }
            }
            else
            {
                //init mIFTool to get Image from database
                mIFTool.Operator.Open(Common.file_image_database, CogImageFileModeConstants.Read);
            }

        }

        private void MToolBlockAcq_Running(object sender, EventArgs e)
        {
            Console.WriteLine("MToolBlockAcq_Running");
        }

        private void MToolBlockAcq_Changed(object sender, CogChangedEventArgs e)
        {
            Console.WriteLine("MToolBlockAcq_Changed");
        }

        private void MToolBlockAcq_Ran(object sender, EventArgs e)
        {
            Console.WriteLine("MToolBlockAcq_Ran");
            Console.WriteLine("Test step process when using camera 0 ....");
            var result = (CogImage8Grey)(mToolBlockAcq.Outputs["Image"].Value);
            Utils.Save_BitMap(result.ToBitmap());

        }

        public void ToolBlock_PrintInfor(CogToolBlock toolblock)
        {
            int numTools = toolblock.Tools.Count;
            Console.WriteLine($"-------------Toolblock {toolblock.Name} begin----------------");
            Console.WriteLine("-------------element");
            for (int i = 0; i < numTools; i++)
            {
                Console.WriteLine($"{toolblock.Tools[i].Name}");

                //cur record
                Cognex.VisionPro.ICogRecord tmpRecord = toolblock.Tools[i].CreateCurrentRecord();
                Console.WriteLine($"\ttmpRecord currentRecord = {tmpRecord.Annotation}");
                for (int j = 0; j < tmpRecord.SubRecords.Count; j++)
                {
                    Console.WriteLine($"\t\tj = {j}: {tmpRecord.SubRecords[j].Annotation}");
                }


                //lastest record
                tmpRecord = toolblock.Tools[i].CreateLastRunRecord();
                Console.WriteLine($"\ttmpRecord LastRecord = {tmpRecord.Annotation}");
                for (int j = 0; j < tmpRecord.SubRecords.Count; j++)
                {
                    Console.WriteLine($"\t\tj = {j}: {tmpRecord.SubRecords[j].Annotation}");
                }
            }

            Console.WriteLine("-------------input");
            int numInputs = toolblock.Inputs.Count;
            for (int i = 0; i < numInputs; i++)
            {
                Console.WriteLine($"{toolblock.Inputs[i].Name}");
            }

            Console.WriteLine("-------------output");
            int numOutputs = toolblock.Outputs.Count;
            for (int i = 0; i < numOutputs; i++)
            {
                Console.WriteLine($"{toolblock.Outputs[i].Name}");
            }

            Console.WriteLine($"-------------Toolblock {toolblock.Name} end----------------");
        }
        public void UpdateData(MyDefine Common)
        {
            mToolBlockProcess = CogSerializer.LoadObjectFromFile(Common.file_toolblock_process) as CogToolBlock;
            mIFTool.Operator.Open(Common.file_image_database, CogImageFileModeConstants.Read);
        }

        public void RunOnce()
        {
            // Get the next image
            if (!bUseCamera)
            {
                mIFTool.Run();
                mToolBlockProcess.Inputs["Image"].Value = mIFTool.OutputImage as CogImage8Grey;
            }
            else
            {
                //FIXME: check output image of mToolBockAcq
                mToolBlockAcq.Run();
                Console.WriteLine("Test step process when using camera 1....");
                mToolBlockProcess.Inputs["Image"].Value = mToolBlockAcq.Outputs["Image"].Value;
            }
            // Run the toolblock
            mToolBlockProcess.Run();
        }

        public void ReleaseObject()
        {
            if (mIFTool != null)
                mIFTool.Dispose();
            //FIXME: check here
            if (mToolBlockAcq != null)
                mToolBlockAcq.Dispose();
            if (mToolBlockProcess != null)
                mToolBlockProcess.Dispose();
        }

        ~ObjectManager()
        {
            //ReleaseObject();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;

namespace VisionPro_Tut.Source.Interface
{
    class MySerialPort
    {
        //data receive from server
        private string _data_receive = null;
        public string data_receive
        {
            get => _data_receive;
            set
            {
                _data_receive = value;
                OnNameChanged(value);
            }
        }



        //event
        private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage;
        public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage
        {
            add
            {
                _ReceiveMessage += value;
            }
            remove
            {
                _ReceiveMessage -= value;
            }
        }

        void OnNameChanged(string mess)
        {
            if (_ReceiveMessage != null)
            {
                _ReceiveMessage(this, new ReceivedMessageEventArgs(mess));
            }
        }

        private string com_name = "";
        private SerialPort serialPort = null;
        public List<string> list_comport;
        public bool is_success = false;
       


        public MySerialPort(SerialPortParam param)
        {
            Console.WriteLine("MySerialPort create");

            //Check comport is exist?
            list_comport = new List<string>();
            com_name = param.com_name;
            list_comport = Utils.Scan_Comport();
            if (!list_comport.Contains(param.com_name))
            {
                is_success = false;
                Console.WriteLine($"Could not find {param.com_name} in this PC");
                return;
            }
            
            //register event
            serialPort = new SerialPort();
            serialPort.PortName = param.com_name;
            serialPort.BaudRate = param.baudrate;
            serialPort.DataReceived += SerialPort_DataReceived;
            is_success = true;
        }

        ~MySerialPort()
        {
            if(is_success)
            {
                if (serialPort.IsOpen)
                    serialPort.Close();
            }
            Console.WriteLine("SerialPortManager destroy");
        }

        public bool Connect()
        {
            bool is_connect = true;
            if (!this.serialPort.IsOpen)
            {
                this.serialPort.Open();
                if (!this.serialPort.IsOpen)
                {
                    is_connect = false;
                }
            }

            Console.WriteLine($"Connect = {is_connect}");
            return is_connect;
        }

        public bool Disconnect()
        {
            bool is_disconnect = true;
            if (this.serialPort.IsOpen)
            {
                this.serialPort.Close();
                if (this.serialPort.IsOpen)
                {
                    is_disconnect = false;
                }
            }
            Console.WriteLine($"Disconnect = {is_disconnect}");
            return is_disconnect;
        }

        public bool SendMessage(string message)
        {
            if (!this.serialPort.IsOpen)
            {
                Console.WriteLine($"{com_name} is not open, try again");
                return false;
            }

            if (String.IsNullOrEmpty(message))
            {
                Console.WriteLine("data2send is empty/null, retry");
                return false;
            }

            this.serialPort.Write(message);
            return true;
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            this.data_receive = this.serialPort.ReadExisting();
            Console.WriteLine($"Data {com_name} received: {data_receive}");
        }
    }
}
<file_sep>﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VisionPro_Tut.Source
{
    class SaveLoadParameter
    {
        #region declare variable, object 

        #endregion

        public SaveLoadParameter()
        {
            Console.WriteLine("SaveLoadParameter create ...");

        }

        ~SaveLoadParameter()
        {
            Console.WriteLine("SaveLoadParameter destroy ...");
        }
        public void Inital_Parameter()
        {
            //Create camera basler
            /*CameraPrameter cam_basler = new CameraPrameter();
            cam_basler.Name = "Basler_10MP";
            cam_basler.Format = CameraPrameter.EFormatCamera.MONO;
            cam_basler.Is_support = true;
            cam_basler.Fps = 10;
            cam_basler.Roi = new OpenCvSharp.Rect(0, 0, 1920, 1080);
            cam_basler.Use_calib = false;
            cam_basler.Flip = CameraPrameter.EFlipFrame.Flip_None;


            //Creater COM port
            ComportParameter com_light_control = new ComportParameter();
            com_light_control.Name = "Light Controller";
            com_light_control.Port_name = "COM2";
            com_light_control.Baudrate = 9600;


            //Creater Socket-client
            SocketParameter socket_client = new SocketParameter();
            socket_client.Name = "Client connect to Jump-Sys";
            socket_client.Port = 8888;
            socket_client.Ip = "127.0.0.1";

            //Add to parameter_manager
            parameter_manager.list_cam.Add(cam_basler);
            parameter_manager.list_comport.Add(com_light_control);
            parameter_manager.list_socket_client.Add(socket_client);*/

        }


        public void Get_Parameter()
        {

        }

        public void Update_Parameter()
        {

        }

        
        public void Save_Parameter(MyDefine common)
        {
            // serialize JSON directly to a file
            Console.WriteLine(Utils.file_config);
            using (StreamWriter file = File.CreateText(Utils.file_config))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(file, common);
            }

            
        }

        public bool Load_Parameter(ref MyDefine common)
        {
            //common = new MyDefine();
            if (!File.Exists(Utils.file_config))
            {
                Console.WriteLine($"file {Utils.file_config} not found...");
                return false;
            }

            using (StreamReader file = File.OpenText(Utils.file_config))
            {
                JsonSerializer serializer = new JsonSerializer();
                common = (MyDefine)serializer.Deserialize(file, typeof(MyDefine));
            }
            //common.Print_Infor();
            Console.WriteLine($"file {Utils.file_config} load ok...");
            return true;
        }
    }
}
<file_sep>﻿using System;
using System.Threading;
using System.Windows.Forms;
using VisionPro_Tut.Source;
using VisionPro_Tut.Source.Interface;

namespace VisionPro_Tut
{
    public partial class MainWindow : Form
    {
        #region Declare_variable_object 
        MyDefine common = null;
        ObjectManager objectManager = null;
        SaveLoadParameter settingParam = null;

        MySerialPort serialPort = null;
        TcpChatClient chatClient = null;
        TcpChatServer chatServer = null;

        InterfaceManager interfaceManager = null;

        Thread thread_control_by_interface = null;
        bool run_thread = false;
        bool run_continue = false;
        #endregion

        //Consider code
        public MainWindow()
        {
            InitializeComponent();
            Initial();
            UpdateUI();
        }

        void Initial()
        {
            common = new MyDefine();
            settingParam = new SaveLoadParameter();
            bool isLoadSuccess = settingParam.Load_Parameter(ref common);

            objectManager = new ObjectManager();
            objectManager.InitObject(common);
            objectManager.mToolBlockProcess.Changed += mToolBlockProcess_Changed;
            objectManager.mToolBlockProcess.Running += mToolBlockProcess_Running;
            objectManager.mToolBlockProcess.Ran += mToolBlockProcess_Ran;
            objectManager.mToolBlockProcess.Inputs["FilterLowValue"].Value = common.blob_filter.area_low;
            objectManager.mToolBlockProcess.Inputs["FilterHighValue"].Value = common.blob_filter.area_high;


            interfaceManager = new InterfaceManager(common);
            //mode run
            switch (common.mode_run)
            {
                case Utils.MODE_RUN.Manual:
                    break;
                case Utils.MODE_RUN.SerialPort:
                case Utils.MODE_RUN.TCP_Client:
                case Utils.MODE_RUN.TCP_Server:
                    run_thread = true;
                    thread_control_by_interface = new Thread(new ThreadStart(Thread_Control_By_Interface));
                    thread_control_by_interface.Name = "Thread control by interface";
                    thread_control_by_interface.IsBackground = true;
                    thread_control_by_interface.Priority = ThreadPriority.AboveNormal;
                    thread_control_by_interface.Start();
                    break;
            }

            //care thread ui + thread process
            CheckForIllegalCrossThreadCalls = false;
        }
        void UpdateUI()
        {
            lb_Toolblock_Process.Text = common.file_toolblock_process;
            lb_Toolblock_AcqFifo.Text = common.file_toolblock_acq;
            lb_ImgDatabase.Text = common.file_image_database;
            cb_UseCamera.Checked = common.use_camera;
            //result
            nPass.Text = common.numOK.ToString();
            nFail.Text = common.numNG.ToString();

            //param
            tbAreaHighBlob.Text = common.blob_filter.area_high.ToString();
            tbAreaLowBlob.Text = common.blob_filter.area_low.ToString();

            //cb_Comport
            var list_com = Utils.Scan_Comport();
            for (int i = 0; i < list_com.Count; i++)
                cbb_Comport.Items.Add(list_com[i]);
            cbb_Comport.Text = common.serial_port.com_name;

            //tcp server
            tb_ServerIP.Text = common.tcp_server.ip;
            tb_ServerPort.Text = common.tcp_server.port.ToString();

            //tcp client
            tb_ClientIP.Text = common.tcp_client.ip;
            tb_ClientPort.Text = common.tcp_client.port.ToString();

            //cb_Baudrate binding with list baudrate
            var bindingBaudrate = new BindingSource();
            bindingBaudrate.DataSource = Utils.list_baudrate;
            cbb_Baudrate.DataSource = bindingBaudrate.DataSource;
            cbb_Baudrate.Text = common.serial_port.baudrate.ToString();

            //cb_Mode_Run
            var bindingModeRun = new BindingSource();
            bindingModeRun.DataSource = Enum.GetValues(typeof(Utils.MODE_RUN));
            cbb_ModeRun.DataSource = bindingModeRun.DataSource;
            cbb_ModeRun.Text = common.mode_run.ToString();

            

        }

        void UpdateParam()
        {
            common.file_image_database = lb_ImgDatabase.Text;
            common.file_toolblock_process = lb_Toolblock_Process.Text;
            common.file_toolblock_acq = lb_Toolblock_AcqFifo.Text;
            common.use_camera = cb_UseCamera.Checked;
            //param
            common.blob_filter.area_high = Double.Parse(tbAreaHighBlob.Text);
            common.blob_filter.area_low = Double.Parse(tbAreaLowBlob.Text);

            //serial port
            common.serial_port.com_name = cbb_Comport.Text;
            common.serial_port.baudrate = int.Parse(cbb_Baudrate.Text);

            //tcp server
            common.tcp_server.ip = tb_ServerIP.Text;
            common.tcp_server.port = int.Parse(tb_ServerPort.Text);

            //tcp client
            common.tcp_client.ip = tb_ClientIP.Text;
            common.tcp_client.port = int.Parse(tb_ClientPort.Text);

            //mode run
            Enum.TryParse<Utils.MODE_RUN>(cbb_ModeRun.SelectedValue.ToString(), out common.mode_run);

            //result
            common.numOK = objectManager.numPass;
            common.numNG = objectManager.numFail;

            common.Print_Infor();
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {
            this.timer_DateTime.Start();
        }

        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.timer_DateTime.Stop();
            this.interfaceManager.CloseInterface();
            this.run_thread = false;
            //this.thread_control_by_interface.Abort();

            //save param before close form
            UpdateParam();
            settingParam.Save_Parameter(common);
            objectManager.ReleaseObject();
        }


        #region Datetime_display
        private void timer_DateTime_Tick(object sender, EventArgs e)
        {
            this.lbDateTime.Text = DateTime.Now.ToString("ddd MM/dd/yyyy\nhh:mm::ss tt");
        }



        #endregion

        
    }
}
<file_sep>﻿using Cognex.VisionPro;
using Cognex.VisionPro.Blob;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using VisionPro_Tut.Source;
using VisionPro_Tut.Source.Interface;
using VisionPro_Tut.Windows;

namespace VisionPro_Tut
{
    public partial class MainWindow
    {
        #region CogToolBlock_event
        private void mToolBlockProcess_Changed(object sender, CogChangedEventArgs e)
        {
            // To see what has changed, look at the state flags that are contained in 
            // the CogChangedEventArgs object.  The StateFlags property is a bitfield,
            // where each bit represents a single element of the tool that may have changed.  If a bit
            // is asserted, that element in the tool has changed.  Multiple bits may be asserted
            // simultaneously.  To see what has changed, bitwise AND the StateFlags with the static
            // Sf**** members in the tool class.  If it returns a value greater than 0, then that
            // particular element has changed.  

            // In the example below, we are testing to see if the RunStatus property has changed
            // by bitwise AND'ing StateFlags with SfRunStatus.

            // Report error conditions, if any.
            Console.WriteLine("mToolBlockProcess_Changed");
            if ((e.StateFlags & CogBlobTool.SfRunStatus) > 0)
            {
                if (objectManager.mToolBlockProcess.RunStatus.Result == CogToolResultConstants.Error)
                    Console.WriteLine(objectManager.mToolBlockProcess.RunStatus.Message);
            }
        }

        private void mToolBlockProcess_Running(object sender, EventArgs e)
        {
            // Get input image.
            Console.WriteLine("mToolBlockProcess_Running");
        }


        string Blob_Packet(CogBlobResult blob)
        {
            return String.Format($"{objectManager.mToolBlockProcess.RunStatus.Result},ID={blob.ID},angle={blob.Angle},x={blob.CenterOfMassX},y={blob.CenterOfMassY}\r\n");
        }
        private void mToolBlockProcess_Ran(object sender, EventArgs e)
        {
            // This method executes each time the TB runs
            bool result = (bool)(objectManager.mToolBlockProcess.Outputs["InspectionPassed"].Value);
            if (result)
                objectManager.numPass++;
            else
                objectManager.numFail++;
            // Update the label with pass and fail
            nPass.Text = objectManager.numPass.ToString();
            nFail.Text = objectManager.numFail.ToString();

            CogBlobTool mBlobTool = objectManager.mToolBlockProcess.Tools["CogBlobTool1"] as CogBlobTool;

            //get result
            var blobResult = mBlobTool.Results;
            var all_blob = blobResult.GetBlobs();
            Console.WriteLine($"number blob detected = {all_blob.Count}");
            for (int i = 0; i < all_blob.Count; i++)
                interfaceManager.SendMessage(Blob_Packet(all_blob[i]));

            //var blobRunParam = mBlobTool.RunParams;

            //Assign picture to display
            ICogRecord temp = mBlobTool.CreateLastRunRecord();
            //temp = temp.SubRecords["BlobImage"];
            temp = temp.SubRecords["InputImage"];
            cogRecordDisplay1.Record = temp;
            cogRecordDisplay1.Fit(true);

            Display(result);
            Console.WriteLine("Ran done!, time processing = {0} ms", objectManager.mToolBlockProcess.RunStatus.TotalTime);
        }
        #endregion

        #region GUI_event
        static bool isPressRunContinue = false;
        static bool isPressClientConnect = false;
        static bool isPressServerListen = false;
        static bool isRunContinue = false;
        Thread thread_run_continue = null;
        private void btn_Click_Event(object sender, EventArgs e)
        {
            var curButton = sender as Button;
            Console.WriteLine($"btn_Click_Event name = {curButton.Name}");
            switch (curButton.Name)
            {
                case "btnRun":
                    objectManager.RunOnce();
                    break;
                case "btnRunContinue":
                    if(!isPressRunContinue)
                    {
                        
                        try
                        {
                            isRunContinue = true;
                            thread_run_continue = new Thread(new ThreadStart(Thread_Run_Continuously));
                            thread_run_continue.Name = "thread run continue";
                            thread_run_continue.IsBackground = true;
                            thread_run_continue.Start();

                        }
                        catch (ThreadStateException ee)
                        {
                            Console.WriteLine("Caught: {0}", ee.Message);
                        }

                    }
                    else
                    {
                        isRunContinue = false;
                        //thread_run_continue.Abort();
                        
                    }
                    isPressRunContinue = !isPressRunContinue;
                    break;
                case "btnSaveParam":
                    UpdateParam();
                    settingParam.Save_Parameter(common);
                    break;
                case "btnInitial":
                    UpdateToolBlock();
                    break;

                case "btn_ClientConnect":
                    {
                        
                        if (!isPressClientConnect)
                        {
                            if(chatClient.Connect())
                            {
                                isPressClientConnect = true;
                                btn_ClientConnect.Text = "Disconnect";
                            }
                        }
                        else
                        {
                            if(chatClient.DisConnect())
                            {
                                isPressClientConnect = false;
                                btn_ClientConnect.Text = "Connect";
                            }
                        }
                    }
                    
                    break;
                case "btn_ClientSend":
                    chatClient.SendMessage(tx_ClientData2Send.Text);
                    break;
                case "btn_ServerListen":
                    {

                        if (!isPressServerListen)
                        {
                            if (chatServer.Listen())
                            {
                                isPressServerListen = true;
                                btn_ServerListen.Text = "Stop";
                            }
                        }
                        else
                        {
                            if (chatServer.Stop())
                            {
                                isPressServerListen = false;
                                btn_ServerListen.Text = "Listen";
                            }
                        }
                    }
                    break;
                case "btn_ServerSend":
                    chatServer.SendMessage(tb_ServerData2Send.Text);
                    break;
            }
        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var strip_menu = sender as ToolStripMenuItem;
            Console.WriteLine("MenuItem click = {0}", strip_menu.Name);
            switch (strip_menu.Name)
            {
                case "load_ImageProcessItem":
                    ToolBlockWindow win2 = new ToolBlockWindow(objectManager, common.file_toolblock_process, Utils.TYPE_OF_TOOLBLOCK.ImageProcess);
                    if (win2.ShowDialog() == DialogResult.OK)
                    {
                        objectManager.mToolBlockProcess = win2.objectManager.mToolBlockProcess;
                        objectManager.ToolBlock_PrintInfor(objectManager.mToolBlockProcess);
                        Console.WriteLine("update done {0}", objectManager.mToolBlockProcess.Name);
                    }
                    win2.Dispose();
                    break;

                case "load_AcqFifoItem":
                    if(!common.use_camera)
                    {
                        System.Windows.Forms.MessageBox.Show("Warning","You not using camera, please recheck!", MessageBoxButtons.OK);
                        break;
                    }
                    ToolBlockWindow win3 = new ToolBlockWindow(objectManager, common.file_toolblock_acq, Utils.TYPE_OF_TOOLBLOCK.AcqFifo);
                    if (win3.ShowDialog() == DialogResult.OK)
                    {
                        objectManager.mToolBlockAcq = win3.objectManager.mToolBlockAcq;
                        objectManager.ToolBlock_PrintInfor(objectManager.mToolBlockAcq);
                        Console.WriteLine("update done {0}", objectManager.mToolBlockAcq.Name);
                    }
                    win3.Dispose();
                    break;

                default:
                    break;
            }
        }

        private void label_Click_Event(object sender, EventArgs e)
        {
            var curLabel = sender as Label;
            Console.WriteLine($"label_Click_Event name = {curLabel.Name}");

            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.CheckPathExists = true;
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;
            //openFileDialog1.ReadOnlyChecked = true,
            openFileDialog1.ShowReadOnly = true;

            switch (curLabel.Name)
            {
                case "lb_ImgDatabase":
                    openFileDialog1.InitialDirectory = Utils.path_load_img_database;
                    openFileDialog1.Title = "Browse Image Database Files";
                    openFileDialog1.DefaultExt = "idb";
                    openFileDialog1.Filter = "idb files (*.idb)|*.idb|All files (*.*)|*.*";
                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        lb_ImgDatabase.Text = openFileDialog1.FileName;
                        common.file_image_database = lb_ImgDatabase.Text;
                    }

                    break;
                case "lb_Toolblock":
                    openFileDialog1.InitialDirectory = Utils.path_load_vpp_file;
                    openFileDialog1.Title = "Browse Toolblock Files";
                    openFileDialog1.DefaultExt = "vpp";
                    openFileDialog1.Filter = "vpp files (*.vpp)|*.vpp|All files (*.*)|*.*";
                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        lb_Toolblock_Process.Text = openFileDialog1.FileName;
                        common.file_toolblock_process = lb_Toolblock_Process.Text;
                    }
                    break;
                case "lb_Toolblock_Process":
                    openFileDialog1.InitialDirectory = Utils.path_load_vpp_file;
                    openFileDialog1.Title = "Browse Toolblock_ImageProcess Files";
                    openFileDialog1.DefaultExt = "vpp";
                    openFileDialog1.Filter = "vpp files (*.vpp)|*.vpp|All files (*.*)|*.*";
                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        lb_Toolblock_Process.Text = openFileDialog1.FileName;
                        common.file_toolblock_process = lb_Toolblock_Process.Text;
                    }
                    break;                
                case "lb_Toolblock_AcqFifo":
                    openFileDialog1.InitialDirectory = Utils.path_load_vpp_file;
                    openFileDialog1.Title = "Browse Toolblock_Acq Files";
                    openFileDialog1.DefaultExt = "vpp";
                    openFileDialog1.Filter = "vpp files (*.vpp)|*.vpp|All files (*.*)|*.*";
                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        lb_Toolblock_AcqFifo.Text = openFileDialog1.FileName;
                        common.file_toolblock_acq = lb_Toolblock_AcqFifo.Text;
                    }
                    break;
                default:
                    break;
            }
        }


        protected override void Dispose(bool disposing)
        {
            // Disconnect the event handlers before closing the form
            objectManager.mToolBlockProcess.Ran -= new EventHandler(mToolBlockProcess_Ran);
            objectManager.mToolBlockProcess.Running -= new EventHandler(mToolBlockProcess_Running);
            objectManager.mToolBlockProcess.Changed -= new CogChangedEventHandler(mToolBlockProcess_Changed);

            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #endregion
    }
}
<file_sep>﻿using Cognex.VisionPro;
using Cognex.VisionPro.ToolBlock;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;

using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VisionPro_Tut.Source;

namespace VisionPro_Tut.Windows
{
    public partial class ToolBlockWindow : Form
    {

        #region declera variable, object
        private Utils.TYPE_OF_TOOLBLOCK type_of_block;
        public ObjectManager objectManager;
        public CogToolBlock toolblock;
        private string path_vpp_file;
        private ToolStripMenuItem saveAsToolStripMenuItem;
        private ToolStripMenuItem runToolStripMenuItem;
        #endregion


        public ToolBlockWindow()
        {
            Console.WriteLine("Tool block window default");
            InitializeComponent();
        }

        public ToolBlockWindow(ObjectManager objectManager, string path_vpp, Utils.TYPE_OF_TOOLBLOCK type_of_block)
        {
            Console.WriteLine("Tool block window create, path vpp_file = {0}, type_of_block = {1}", path_vpp, type_of_block);
            this.type_of_block = type_of_block;
            this.objectManager = objectManager;
            this.toolblock = new CogToolBlock();
            this.path_vpp_file = path_vpp;
            InitializeComponent();
        }

        

        private void MenuClick_Event(object sender, EventArgs e)
        {
            var menu_item = sender as ToolStripMenuItem;
            Console.WriteLine(menu_item.Text);
            switch (menu_item.Text)
            {
                case "Load":
                    break;
                case "Save":
                    Console.WriteLine($"Save file {this.path_vpp_file}");
                    switch (this.type_of_block)
                    {
                        case Utils.TYPE_OF_TOOLBLOCK.AcqFifo:
                            File.WriteAllBytes(this.path_vpp_file, Utils.Serialize(this.objectManager.mToolBlockAcq));
                            break;
                        case Utils.TYPE_OF_TOOLBLOCK.ImageProcess:
                            File.WriteAllBytes(this.path_vpp_file, Utils.Serialize(this.objectManager.mToolBlockProcess));
                            break;
                        case Utils.TYPE_OF_TOOLBLOCK.Other:
                            File.WriteAllBytes(this.path_vpp_file, Utils.Serialize(this.toolblock));
                            Console.WriteLine($"{this.path_vpp_file}-> {this.type_of_block}!");
                            break;
                    }
                    break;
                case "Save As":
                    SaveFileDialog saveToolBlock = new SaveFileDialog();
                    saveToolBlock.Filter = "ToolBlock |*.vpp|All File|*.*";
                    saveToolBlock.Title = "Save a Toolblock file";
                    saveToolBlock.RestoreDirectory = true;
                    saveToolBlock.ShowDialog();
                    if (saveToolBlock.FileName != null)
                    {
                        Console.WriteLine(saveToolBlock.FileName);
                        
                        switch (this.type_of_block)
                        {
                            case Utils.TYPE_OF_TOOLBLOCK.AcqFifo:
                                File.WriteAllBytes(saveToolBlock.FileName, Utils.Serialize(this.objectManager.mToolBlockAcq));
                                break;
                            case Utils.TYPE_OF_TOOLBLOCK.ImageProcess:
                                File.WriteAllBytes(saveToolBlock.FileName, Utils.Serialize(this.objectManager.mToolBlockProcess));
                                break;
                            case Utils.TYPE_OF_TOOLBLOCK.Other:
                                File.WriteAllBytes(saveToolBlock.FileName, Utils.Serialize(this.toolblock));
                                break;
                        }
                    }
                    break;
                case "OK":
                    switch (this.type_of_block)
                    {
                        case Utils.TYPE_OF_TOOLBLOCK.AcqFifo:
                        case Utils.TYPE_OF_TOOLBLOCK.ImageProcess:
                            Close();
                            DialogResult = DialogResult.OK;
                            break;
                        case Utils.TYPE_OF_TOOLBLOCK.Other:
                            Close();
                            break;
                    }
                    break;
                case "Run":
                    switch (this.type_of_block)
                    {
                        case Utils.TYPE_OF_TOOLBLOCK.AcqFifo:
                            this.objectManager.mToolBlockAcq.Run();
                            break;
                        case Utils.TYPE_OF_TOOLBLOCK.ImageProcess:
                            this.objectManager.RunOnce();
                            break;
                        case Utils.TYPE_OF_TOOLBLOCK.Other:
                            this.toolblock.Run();
                            break;
                    }
                    
                    break;
            }
        }

        private void ToolBlockWindow_Load(object sender, EventArgs e)
        {
            //Load Toolblock and show on window
            

            Console.WriteLine("ToolBlockWindow_Load");

            cogToolBlockEditV21.LocalDisplayVisible = false;

            switch (this.type_of_block)
            {
                case Utils.TYPE_OF_TOOLBLOCK.AcqFifo:
                    cogToolBlockEditV21.Subject = this.objectManager.mToolBlockAcq;
                    break;
                case Utils.TYPE_OF_TOOLBLOCK.ImageProcess:
                    cogToolBlockEditV21.Subject = this.objectManager.mToolBlockProcess;
                    break;
                case Utils.TYPE_OF_TOOLBLOCK.Other:
                    cogToolBlockEditV21.Subject = this.toolblock;
                    break;
            }

            cogToolBlockEditV21.SubjectChanged += new EventHandler(cogToolBlockEditV21_SubjectChanged);

        }

        private void ToolBlockWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Close and release resource
            Console.WriteLine("ToolBlockWindow_FormClosing");
        }

        void cogToolBlockEditV21_SubjectChanged(object sender, EventArgs e)
        {
            // The application is meant to be used with the TB.vpp so whenever the user changes the TB
            Console.WriteLine("cogToolBlockEditV21_SubjectChanged");
        }




        #region GUI
        private Cognex.VisionPro.ToolBlock.CogToolBlockEditV2 cogToolBlockEditV21;
        private Label lbStatus;
        private ToolStripMenuItem loadToolStripMenuItem;
        private ToolStripMenuItem saveToolStripMenuItem;
        private ToolStripMenuItem oKToolStripMenuItem;
        private MenuStrip menuStrip1;
        private System.ComponentModel.IContainer components = null;
        protected override void Dispose(bool disposing)
        {
            Console.WriteLine($"Dispose = {disposing}");

            cogToolBlockEditV21.SubjectChanged -= new EventHandler(cogToolBlockEditV21_SubjectChanged);
            if (disposing && (components != null))
            {
                components.Dispose();
                Console.WriteLine("components.Dispose();");
            }
            base.Dispose(disposing);

        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.cogToolBlockEditV21 = new Cognex.VisionPro.ToolBlock.CogToolBlockEditV2();
            this.lbStatus = new System.Windows.Forms.Label();
            this.loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.oKToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.runToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            ((System.ComponentModel.ISupportInitialize)(this.cogToolBlockEditV21)).BeginInit();
            this.menuStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // cogToolBlockEditV21
            // 
            this.cogToolBlockEditV21.AllowDrop = true;
            this.cogToolBlockEditV21.ContextMenuCustomizer = null;
            this.cogToolBlockEditV21.Location = new System.Drawing.Point(-3, 27);
            this.cogToolBlockEditV21.MinimumSize = new System.Drawing.Size(489, 0);
            this.cogToolBlockEditV21.Name = "cogToolBlockEditV21";
            this.cogToolBlockEditV21.ShowNodeToolTips = true;
            this.cogToolBlockEditV21.Size = new System.Drawing.Size(808, 410);
            this.cogToolBlockEditV21.SuspendElectricRuns = false;
            this.cogToolBlockEditV21.TabIndex = 0;
            // 
            // lbStatus
            // 
            this.lbStatus.Location = new System.Drawing.Point(3, 445);
            this.lbStatus.Name = "lbStatus";
            this.lbStatus.Size = new System.Drawing.Size(802, 23);
            this.lbStatus.TabIndex = 1;
            this.lbStatus.Text = "Status";
            // 
            // loadToolStripMenuItem
            // 
            this.loadToolStripMenuItem.Name = "loadToolStripMenuItem";
            this.loadToolStripMenuItem.Size = new System.Drawing.Size(45, 20);
            this.loadToolStripMenuItem.Text = "Load";
            this.loadToolStripMenuItem.Click += new System.EventHandler(this.MenuClick_Event);
            // 
            // saveToolStripMenuItem
            // 
            this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
            this.saveToolStripMenuItem.Size = new System.Drawing.Size(43, 20);
            this.saveToolStripMenuItem.Text = "Save";
            this.saveToolStripMenuItem.Click += new System.EventHandler(this.MenuClick_Event);
            // 
            // oKToolStripMenuItem
            // 
            this.oKToolStripMenuItem.Name = "oKToolStripMenuItem";
            this.oKToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
            this.oKToolStripMenuItem.Text = "OK";
            this.oKToolStripMenuItem.Click += new System.EventHandler(this.MenuClick_Event);
            // 
            // menuStrip1
            // 
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.loadToolStripMenuItem,
            this.saveToolStripMenuItem,
            this.saveAsToolStripMenuItem,
            this.runToolStripMenuItem,
            this.oKToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new System.Drawing.Size(807, 24);
            this.menuStrip1.TabIndex = 2;
            this.menuStrip1.Text = "menuStrip1";
            // 
            // runToolStripMenuItem
            // 
            this.runToolStripMenuItem.Name = "runToolStripMenuItem";
            this.runToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
            this.runToolStripMenuItem.Text = "Run";
            this.runToolStripMenuItem.Click += new System.EventHandler(this.MenuClick_Event);
            // 
            // saveAsToolStripMenuItem
            // 
            this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
            this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(59, 20);
            this.saveAsToolStripMenuItem.Text = "Save As";
            // 
            // ToolBlockWindow
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(807, 468);
            this.Controls.Add(this.lbStatus);
            this.Controls.Add(this.cogToolBlockEditV21);
            this.Controls.Add(this.menuStrip1);
            this.MainMenuStrip = this.menuStrip1;
            this.Name = "ToolBlockWindow";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ToolBlockWindow_FormClosing);
            this.Load += new System.EventHandler(this.ToolBlockWindow_Load);
            ((System.ComponentModel.ISupportInitialize)(this.cogToolBlockEditV21)).EndInit();
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        #endregion


    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace VisionPro_Tut.Source.Interface
{
    class ChatSession : TcpSession
    {
        //data receive from server
        private string _data_receive = null;
        public string data_receive
        {
            get => _data_receive;
            set
            {
                _data_receive = value;
                OnNameChanged(value);
            }
        }



        //event
        private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage;
        public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage
        {
            add
            {
                _ReceiveMessage += value;
            }
            remove
            {
                _ReceiveMessage -= value;
            }
        }

        void OnNameChanged(string mess)
        {
            if (_ReceiveMessage != null)
            {
                _ReceiveMessage(this, new ReceivedMessageEventArgs(mess));
            }
        }



        public ChatSession(TcpServer server) : base(server) { }

        protected override void OnConnected()
        {
            Console.WriteLine($"Chat TCP session with Id {Id} connected!");

            // Send invite message
            string message = "Hello from TCP chat! Please send a message or '!' to disconnect the client!";
            SendAsync(message);
        }

        protected override void OnDisconnected()
        {
            Console.WriteLine($"Chat TCP session with Id {Id} disconnected!");
        }

        protected override void OnReceived(byte[] buffer, long offset, long size)
        {
            string message = Encoding.UTF8.GetString(buffer, (int)offset, (int)size);
            Console.WriteLine("Incoming: " + message);

            // Multicast message to all connected sessions
            Server.Multicast(message);

            // If the buffer starts with '!' the disconnect the current session
            if (message == "!")
                Disconnect();

            data_receive = message;

        }

        protected override void OnError(SocketError error)
        {
            Console.WriteLine($"Chat TCP session caught an error with code {error}");
        }
    }

    class ChatServer : TcpServer
    {
        //data receive from server
        private string _data_receive = null;
        public string data_receive
        {
            get => _data_receive;
            set
            {
                _data_receive = value;
                OnNameChanged(value);
            }
        }



        //event
        private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage;
        public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage
        {
            add
            {
                _ReceiveMessage += value;
            }
            remove
            {
                _ReceiveMessage -= value;
            }
        }

        void OnNameChanged(string mess)
        {
            if (_ReceiveMessage != null)
            {
                _ReceiveMessage(this, new ReceivedMessageEventArgs(mess));
            }
        }

        public ChatServer(IPAddress address, int port) : base(address, port) 
        {
            
        }

        private void Chatss_ReceiveMessage(object sender, ReceivedMessageEventArgs e)
        {
            Console.WriteLine("%%%%%%%%%%%%%%" + e.Message);
            data_receive = e.Message;
        }

        protected override TcpSession CreateSession() 
        {
            ChatSession chatss =  new ChatSession(this);
            chatss.ReceiveMessage += Chatss_ReceiveMessage;
            return chatss; 
        }

        protected override void OnError(SocketError error)
        {
            Console.WriteLine($"Chat TCP server caught an error with code {error}");
        }
    }

    public class TcpChatServer
    {
        //data receive from server
        private string _data_receive = null;
        public string data_receive
        {
            get => _data_receive;
            set
            {
                _data_receive = value;
                OnNameChanged(value);
            }
        }



        //event
        private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage;
        public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage
        {
            add
            {
                _ReceiveMessage += value;
            }
            remove
            {
                _ReceiveMessage -= value;
            }
        }

        void OnNameChanged(string mess)
        {
            if (_ReceiveMessage != null)
            {
                _ReceiveMessage(this, new ReceivedMessageEventArgs(mess));
            }
        }

        //tcp chat server
        ChatServer server;


        public TcpChatServer(TCPParam param)
        {
            server = new ChatServer(IPAddress.Parse(param.ip), param.port);
            server.ReceiveMessage += Server_ReceiveMessage;
        }

        private void Server_ReceiveMessage(object sender, ReceivedMessageEventArgs e)
        {
            data_receive = e.Message;
        }

        ~TcpChatServer()
        {

        }


        public bool Listen()
        {
            // Start the server
            Console.Write("Server starting...");
            bool bStart = server.Start();
            Console.WriteLine("Done!");
            return bStart;
        }


        public bool Stop()
        {
            Console.Write("Server Stop...");
            bool bStop = server.Stop();
            Console.WriteLine("Done!");
            return bStop;
        }

        public bool SendMessage(string mess)
        {
            // Multicast admin message to all sessions
            bool bSend = server.Multicast(mess);
            return bSend;
        }


    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static VisionPro_Tut.Source.Utils;

namespace VisionPro_Tut.Source.Interface
{
    public class InterfaceManager
    {
        //data receive from server
        private string _data_receive = null;
        public string data_receive
        {
            get => _data_receive;
            set
            {
                _data_receive = value;
                OnNameChanged(value);
            }
        }



        //event
        private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage;
        public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage
        {
            add
            {
                _ReceiveMessage += value;
            }
            remove
            {
                _ReceiveMessage -= value;
            }
        }

        void OnNameChanged(string mess)
        {
            if (_ReceiveMessage != null)
            {
                _ReceiveMessage(this, new ReceivedMessageEventArgs(mess));
            }
        }

        //variable
        MySerialPort serialPort = null;
        TcpChatClient chatClient = null;
        TcpChatServer chatServer = null;

        
        MyDefine param;
        public string data_receiver;

        public InterfaceManager(MyDefine param)
        {
            
            this.param = param;
            
            //mode run
            switch (param.mode_run)
            {
                case MODE_RUN.Manual:
                    break;
                case MODE_RUN.SerialPort:
                    serialPort = new MySerialPort(param.serial_port);
                    serialPort.ReceiveMessage += Event_ReceiveMessage;
                    if (serialPort.is_success)
                    {
                        bool bConnectCOM = serialPort.Connect();
                        Console.WriteLine($"Comport {param.serial_port.com_name} connect ok");
                    }
                    break;
                case MODE_RUN.TCP_Client:
                    chatClient = new TcpChatClient(param.tcp_client);
                    chatClient.ReceiveMessage += Event_ReceiveMessage;
                    bool bClientConnect =  chatClient.Connect();
                    if(bClientConnect)
                    {
                        Console.WriteLine($"Client connected to {param.tcp_client.ip}:{param.tcp_client.port} ok");
                    }
                    break;
                case MODE_RUN.TCP_Server:
                    chatServer = new TcpChatServer(param.tcp_server);
                    chatServer.ReceiveMessage += Event_ReceiveMessage;
                    bool bServerListen = chatServer.Listen();
                    if (bServerListen)
                    {
                        Console.WriteLine($"Server listen in {param.tcp_server.ip}:{param.tcp_server.port} ok");
                    }
                    break;
            }
        }

        private void Event_ReceiveMessage(object sender, ReceivedMessageEventArgs e)
        {
            data_receive = e.Message;
            Console.WriteLine($"Interface data = {data_receive}");
        }

        public bool SendMessage(string mess)
        {
            switch (param.mode_run)
            {
                case MODE_RUN.Manual:
                    break;
                case MODE_RUN.SerialPort:
                    serialPort.SendMessage(mess);
                    break;
                case MODE_RUN.TCP_Client:
                    chatClient.SendMessage(mess);
                    break;
                case MODE_RUN.TCP_Server:
                    chatServer.SendMessage(mess);
                    break;
            }
            return true;
        }
        
        public void CloseInterface()
        {
            switch (param.mode_run)
            {
                case MODE_RUN.Manual:
                    break;
                case MODE_RUN.SerialPort:
                    if(serialPort != null)
                    {
                        bool ComportClose = serialPort.Disconnect();
                        Console.WriteLine($"Serialport close {param.serial_port.baudrate} ok");
                    }
                    break;
                case MODE_RUN.TCP_Client:
                    if (chatClient != null)
                    {

                        bool clientDisconnect = chatClient.DisConnect();
                        Console.WriteLine($"Client disconnect form {param.tcp_client.ip}:{param.tcp_client.port} ok");
                    }
                    break;
                case MODE_RUN.TCP_Server:
                    if (chatServer != null)
                    {
                        bool serverStop = chatServer.Stop();
                        Console.WriteLine($"Server close in {param.tcp_server.ip}:{param.tcp_server.port} ok");
                    }
                    break;
            }
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VisionPro_Tut.Source;
using static VisionPro_Tut.Source.Utils;
using System.Runtime.Serialization.Formatters.Binary;
using System.Drawing;
using System.Drawing.Imaging;

namespace VisionPro_Tut.Source
{
    public class ReceivedMessageEventArgs : EventArgs
    {
        public string Message { get; set; }
        public ReceivedMessageEventArgs(string name)
        {
            Message = name;
        }
    }

    public class Utils
    {
        public enum TYPE_OF_TOOLBLOCK
        {
            Other = 0,
            AcqFifo,
            ImageProcess
        }
        public enum MODE_RUN
        {
            Manual = 0,
            SerialPort,
            TCP_Client,
            TCP_Server
        }


        public const string TRIGGER = "TRIGGER";
        public const string RUNLOOP = "LOOP";

        public static readonly string workingDirectory = Environment.CurrentDirectory;                                      //C:\Users\Admin\Downloads\tuanken92\VisionPro_Tut\bin\Debug
        public static readonly string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;             //C:\Users\Admin\Downloads\tuanken92\VisionPro_Tut
        public static readonly string workspaceDirectory = Directory.GetParent(workingDirectory).Parent.Parent.FullName;     //C:\Users\Admin\Downloads\tuanken92

        public static readonly string file_config = String.Format($"{projectDirectory}\\Data\\config_param.json");
        public static readonly string path_load_img_database = @"C:\Program Files\Cognex\VisionPro\Images";
        public static readonly string path_load_vpp_file = @"C:\Users\Admin\Desktop\Vpp_file";
        public static readonly string path_save_images = String.Format("{0}\\Images", projectDirectory);

        public static readonly List<int> list_baudrate = new List<int>{ 9600, 14400, 19200, 38400, 57600, 115200, 128000, 256000 };

        public static List<string> Scan_Comport()
        {
            string[] ArrayComPortsNames = null;
            int index = -1;

            ArrayComPortsNames = SerialPort.GetPortNames();
            do
            {
                index += 1;
            }
            while (!(index == ArrayComPortsNames.GetUpperBound(0)));
            Array.Sort(ArrayComPortsNames);

            
            foreach (var com_name in ArrayComPortsNames)
                Console.WriteLine(com_name);

            return (new List<string>(ArrayComPortsNames));
        }

        public static byte[] Serialize(Object obj)
        {
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter binaryFomatter = new BinaryFormatter();
            binaryFomatter.Serialize(memoryStream, obj);
            return memoryStream.ToArray();
        }

        public static Object Deserialize(byte[] data)
        {
            MemoryStream stream = new MemoryStream(data);
            BinaryFormatter formatter = new BinaryFormatter();
            
            return formatter.Deserialize(stream);
        }

        public static bool CreateFolder(string path_folder)
        {
            bool result = Directory.Exists(path_folder);
            if (!result)
            {
                Directory.CreateDirectory(path_folder);
                result = Directory.Exists(path_folder);
            }
            return result;
        }
        public static string GenerateNameImage()
        {
            CreateFolder(path_save_images);
            return String.Format("{0}\\{1}.jpg", path_save_images, DateTime.Now.ToString("yyyyMMdd_hhmmss"));
        }

        public static void Save_BitMap(Bitmap bm)
        {
            string file_name = GenerateNameImage();
            bm.Save(file_name, ImageFormat.Jpeg);
            Console.WriteLine("Saved file {0}", file_name);
        }

    }

    public class BlobFilter
    {
        public double area_low;
        public double area_high;
        public BlobFilter()
        {
            area_low = 0;
            area_high = 0;
        }

        public void Print_Infor()
        {
            Console.WriteLine($"\tblob filter area low = {area_low}");
            Console.WriteLine($"\tblob filter area high = {area_high}");
        }
    }

    public class SerialPortParam
    {
        public string com_name;
        public int baudrate;

        public SerialPortParam()
        {
            com_name = "COM1";
            baudrate = 115200;
        }

        public void Print_Infor()
        {
            Console.WriteLine($"\tSerialport name = {com_name}");
            Console.WriteLine($"\tSerialport baudrate = {baudrate}");
        }

    }

    public class TCPParam
    {
        public string name;
        public string ip;
        public int port;

        public TCPParam()
        {
            ip = "127.0.0.1";
            port = 8686;
            name = null;
        }

        public TCPParam(string name, string ip, int port)
        {
            this.name = name;
            this.ip = ip;
            this.port = port;
        }

        public void Print_Infor()
        {
            Console.WriteLine($"\tTcp name = {name}");
            Console.WriteLine($"\tTcp address = {ip}:{port}");
        }

    }

    public class MyDefine
    {

        public bool use_camera = true;
        public string file_image_database = Environment.GetEnvironmentVariable("VPRO_ROOT") + @"\images\coins.idb";
        public string file_toolblock_process = Environment.GetEnvironmentVariable("VPRO_ROOT") + @"\samples\programming\toolblock\toolblockload\tb.vpp";
        public string file_toolblock_acq = String.Format($"{projectDirectory}\\Data\\TB_ac3800_10gm.vpp");

        public ulong numOK = 0;
        public ulong numNG = 0;
        public MODE_RUN mode_run = MODE_RUN.Manual;
        public BlobFilter blob_filter = new BlobFilter();
        public SerialPortParam serial_port = new SerialPortParam();
        public TCPParam tcp_client = new TCPParam("Client", "127.0.0.1", 5001);
        public TCPParam tcp_server = new TCPParam("Server", "127.0.0.1", 5002);

        public void Print_Infor()
        {
            Console.WriteLine("----MyDefine begin---");
            Console.WriteLine($"\tmode run = {mode_run}");
            Console.WriteLine($"\tuse_camera = {use_camera}");
            Console.WriteLine($"\tfile_image_database = {file_image_database}");
            Console.WriteLine($"\tfile_toolblock_process = {file_toolblock_process}");
            Console.WriteLine($"\tfile_toolblock_acq = {file_toolblock_acq}");
            Console.WriteLine($"\tnumber OK = {numOK}");
            Console.WriteLine($"\tnumber NG = {numNG}");
            blob_filter.Print_Infor();
            serial_port.Print_Infor();
            tcp_client.Print_Infor();
            tcp_server.Print_Infor();
            Console.WriteLine("----MyDefine end---");
        }
    }

    
}
<file_sep>﻿using Cognex.VisionPro;
using System;
using System.Drawing;
using System.Threading;
using VisionPro_Tut.Source;
using VisionPro_Tut.Source.Interface;

namespace VisionPro_Tut
{
    public partial class MainWindow
    {
        #region funtion process
        

        void Thread_Run_Continuously()
        {
            try
            {
                while (isRunContinue)
                {
                    Thread.Sleep(1000);

                    //TODO: care timeout processing
                    objectManager.RunOnce();

                }
                Console.WriteLine(Thread.CurrentThread.Name + "end");
            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine($"{Thread.CurrentThread.Name} exception: {e.ToString()}");
            }

        }
        void Thread_Control_By_Interface()
        {
            try
            {
                while (run_thread)
                {
                    Thread.Sleep(100);
                    if (interfaceManager.data_receive != null)
                    {
                        Console.WriteLine(interfaceManager.data_receive);
                        switch (interfaceManager.data_receive)
                        {
                            case Utils.TRIGGER:
                                run_continue = false;
                                objectManager.RunOnce();
                                break;
                            case Utils.RUNLOOP:
                                run_continue = true;
                                objectManager.RunOnce();
                                break;
                            default:
                                break;
                        }
                        interfaceManager.data_receive = null;
                    }
                }
            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine($"{Thread.CurrentThread.Name} exception: {e.ToString()}");
            }

        }


        void UpdateToolBlock()
        {
            objectManager.mToolBlockProcess.Inputs["FilterLowValue"].Value = common.blob_filter.area_low;
            objectManager.mToolBlockProcess.Inputs["FilterHighValue"].Value = common.blob_filter.area_high;


        }

        public void Display(bool result)
        {
            CogGraphicLabel cglCaption = new CogGraphicLabel();
            Font myFont = new Font("Comic Sans MS", 16, FontStyle.Bold);

            // Set it's text and alignment properties
            cglCaption.Text = result ? "PASS" : "FAIL";
            cglCaption.Color = result ? CogColorConstants.Green : CogColorConstants.Red;

            cglCaption.Alignment = CogGraphicLabelAlignmentConstants.BottomLeft;
            // .NET fonts are read only, so create a new font and then
            // push this font object onto the Font property of the label
            // myFont = new Font("Comic Sans MS", 18, FontStyle.Bold);                        

            cglCaption.Font = myFont;

            // Set its space to be '*' - anchored to the image
            cglCaption.SelectedSpaceName = "*";

            // Position the label over the CogDisplay
            cglCaption.X = 50;
            cglCaption.Y = 50;

            // Add the label to the CogDisplay
            cogRecordDisplay1.InteractiveGraphics.Add(cglCaption, cglCaption.Text, false);
            cglCaption.Dispose();
            myFont.Dispose();
        }

        #endregion
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace VisionPro_Tut.Source.Interface
{
    

    class ChatClient : TcpClient
    {
        private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage;
        public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage
        {
            add
            {
                _ReceiveMessage += value;
            }
            remove
            {
                _ReceiveMessage -= value;
            }
        }

        void OnNameChanged(string mess)
        {
            if (_ReceiveMessage != null)
            {
                _ReceiveMessage(this, new ReceivedMessageEventArgs(mess));
            }
        }

        private string _DataMessage;
        public string DataMessage
        {
            get => _DataMessage;
            set
            {
                _DataMessage = value;
                OnNameChanged(value);
            }
        }

        public ChatClient(string address, int port) : base(address, port) { }

        public void DisconnectAndStop()
        {
            _stop = true;
            DisconnectAsync();
            while (IsConnected)
                Thread.Yield();
        }

        protected override void OnConnected()
        {
            Console.WriteLine($"Chat TCP client connected a new session with Id {Id}");
        }

        protected override void OnDisconnected()
        {
            Console.WriteLine($"Chat TCP client disconnected a session with Id {Id}");

            // Wait for a while...
            Thread.Sleep(1000);

            // Try to connect again
            if (!_stop)
                ConnectAsync();
        }

        protected override void OnReceived(byte[] buffer, long offset, long size)
        {
            DataMessage = (Encoding.UTF8.GetString(buffer, (int)offset, (int)size));
            Console.WriteLine(DataMessage);
        }

        protected override void OnError(SocketError error)
        {
            Console.WriteLine($"Chat TCP client caught an error with code {error}");
        }

        private bool _stop = true;
    }

    public class TcpChatClient
    {
        //data receive from server
        private string _data_receive = null;
        public string data_receive
        {
            get => _data_receive;
            set
            {
                _data_receive = value;
                OnNameChanged(value);
            }
        }

        

        //event
        private event EventHandler<ReceivedMessageEventArgs> _ReceiveMessage;
        public event EventHandler<ReceivedMessageEventArgs> ReceiveMessage
        {
            add
            {
                _ReceiveMessage += value;
            }
            remove
            {
                _ReceiveMessage -= value;
            }
        }

        void OnNameChanged(string mess)
        {
            if (_ReceiveMessage != null)
            {
                _ReceiveMessage(this, new ReceivedMessageEventArgs(mess));
            }
        }

        //tcp chat client
        ChatClient client;
        public TcpChatClient(TCPParam param)
        {

            // Create a new TCP chat client
            client = new ChatClient(param.ip, param.port);
            client.ReceiveMessage += Client_ReceiveMessage;
        }

        private void Client_ReceiveMessage(object sender, ReceivedMessageEventArgs e)
        {
            Console.WriteLine("xxxx: " + e.Message);
            data_receive = e.Message;
        }

        ~TcpChatClient()
        {

        }


        public bool Connect()
        {
            // Connect the client
            Console.Write("Client connecting...");
            bool isConnect = client.ConnectAsync();
            Console.WriteLine("Done!");
            return isConnect;
        }

        public bool DisConnect()
        {
            // Disconnect the client
            Console.Write("Client disconnecting...");
            bool isDisConnect  = client.DisconnectAsync();
            Console.WriteLine("Done!");
            return isDisConnect;
        
        }


        public bool SendMessage(string mess)
        {
            // Send the entered text to the chat server
            bool isSend = client.SendAsync(mess);
            return isSend;
        }

       
    }

}
