美文网首页
VisionPro C# written job scripts

VisionPro C# written job scripts

作者: XBruce | 来源:发表于2021-09-29 21:42 被阅读0次

    The code has been added in the script, actually operating this content, then you need to complete the previous content: Write QV code to identify QuickBuild project, this article adds code in the job configuration, complete code as follows:

    using System;
    using System.Net;
    using System.Text;
    using System.Net.Sockets;
    using System.Threading;
    using System.Windows.Forms;
    using System.Collections.Generic;
    using Cognex.VisionPro;
    using Cognex.VisionPro.QuickBuild;
    
    
    public class UserScript : CogJobBaseScript
    {
      //The collection can be viewed in an array, the length of the collection can become, and its element is an object type.
      //Specify a collection of data types when the generic collection
      private object _lock=new object();
    
      //Define generic sets of NetworkStream
      private List<NetworkStream>_streams = new List<NetworkStream>();
    
      //Define TCPClient's generic collection
      private List<TcpClient>_clients = new List<TcpClient>();
    
      //Server-side monitor object
      private TcpListener _listener;
    
      //Connection thread
      private Thread _connectionThread;
    
      //Define THREAD generic collection
      private List<Thread> _threads=new List<Thread>();
    
      //Total data length
      private long _totalBytes;
    
      //Operation
      private CogJob MyJob;
    
    #region "When an Acq Fifo Has Been Constructed and Assigned To The Job"
      // This function is called when a new fifo is assigned to the job.  This usually
      // occurs when the "Initialize Acquisition" button is pressed on the image source
      // control.  This function is where you would perform custom setup associated
      // with the FIFO.
      public override void AcqFifoConstruction(Cognex.VisionPro.ICogAcqFifo fifo)
      {
      }
    #endregion
    
    #region "When an Acquisition is About To Be Started"
      // Called before an acquisition is started for manual and semi-automatic trigger
      // models.  If "Number of Software Acquisitions Pre-queued" is set to 1 in the
      // job configuration, then no acquisitions should be in progress when this
      // function is called.
      public override void PreAcquisition()
      {
        // To let the execution stop in this script when a debugger is attached, uncomment the following lines.
        // #if DEBUG
        // if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break();
        // #endif
    
      }
    #endregion
    
    #region "When an Acquisition Has Just Completed"
      // Called immediately after an acquisition has completed.
      // Return true if the image should be inspected.
      // Return false to skip the inspection and acquire another image.
      public override bool PostAcquisitionRefInfo(ref Cognex.VisionPro.ICogImage image,
                                                      Cognex.VisionPro.ICogAcqInfo info)
      {
        // To let the execution stop in this script when a debugger is attached, uncomment the following lines.
        // #if DEBUG
        // if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break();
        // #endif
    
        return true;
      }
    #endregion
    
    #region "When the Script is Initialized"
      //Perform any initialization required by your script here.
      public override void Initialize(CogJob jobParam)
      {
        //DO NOT REMOVE - Call the base class implementation first - DO NOT REMOVE
        base.Initialize(jobParam);
    
        //Copy the current job to myjob
        MyJob = jobParam;
    
        //Turn on thread
        StartThreading();
      }
    #endregion
    
      //Turn on the thread to implement the port listener of the server
      private void StartThreading()
      {
        try
        {
          _totalBytes = 0;
    
          //_ConnectionthRead object instantiation
          _connectionThread = new System.Threading.Thread(new ThreadStart(ConnectToClient));
    
          //Thread background
          _connectionThread.IsBackground = true;
    
          //Thread start running
          _connectionThread.Start();
        }
        catch(Exception ex)
        {
          MessageBox.Show("Thread start failed");
        }
      }
    
      //Connect to the client
      private void ConnectToClient()
      {
        try
        {
          //Start listening 6001 port
          _listener = new TcpListener(IPAddress.Any, 6001);
    
          _listener.Start();
        }
        catch(SocketException se)
        {
          MessageBox.Show("Server monitors failed" + se.Message);
    
          StopServer();
    
          return;
        }
    
        //Listening to the client's connection request
        try
        {
          for(;;)
          {
            //Waiting for the client's connection request
            TcpClient client = _listener.AcceptTcpClient();
    
            //Create a thread to start receiving client data
            Thread t = new Thread(new ParameterizedThreadStart(ReceiveDataFromClient));
    
            //Thread background
            t.IsBackground = true;
    
            //Thread priority
            t.Priority = ThreadPriority.AboveNormal;
    
            //Thread name
            t.Name = "Handle Client";
    
            //Turn on thread
            t.Start(client);
    
            //Add thread objects to generic collection
            _threads.Add(t);
    
            //Add the client to the generic collection
            _clients.Add(client);
          }
        }
        catch(SocketException ex)
        {
          MessageBox.Show("Socket error" + ex.Message);
        }
        catch(Exception ex)
        {
          MessageBox.Show("Error" + ex.Message);
        }
      }
    
      //Accept the data from the client
      public void ReceiveDataFromClient(object clientObject)
      {
        //Define TCPCLIENT objects and assign
        TcpClient client = clientObject as TcpClient;
    
        //Define NetworkStream objects and assign values
        NetworkStream netStream = null;
    
        try
        {
          //Get the network data stream of the client
          netStream = client.GetStream();
        }
        catch(Exception ex)
        {
          if(netStream != null) netStream.Close();
          MessageBox.Show("Error" + ex.Message);
          return;
        }
    
        if(netStream.CanRead)
        {
          //Add the data stream to the _streams generic collection
          _streams.Add(netStream);
          try
          {
            byte[] receiveBuffer = new byte[512];
            int bytesReceived;
    
            //Loop read the data from the client
            while((bytesReceived = netStream.Read(receiveBuffer, 0, receiveBuffer.Length)) > 0)
            {
              if(Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived) == "s")
              {
                MyJob.RunContinuous();
                //Messagebox.show ("Accepted data:" + encoding.ascii.getstring (ReceiveBuffer, 0, BytesReceive);
              }
    
              if(Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived) == "e")
              {
                MyJob.Stop();
                //Messagebox.show ("Accepted data:" + Encoding.ASCII.GetString (ReceiveBuffer, 0, BytesReceived);
              }
            }
          }
          catch(Exception ex)
          {
            MessageBox.Show("Error" + ex.Message);
          }
        }
      }
    
      //Stop server
      private void StopServer()
      {
        if(_listener != null)
        {
          //Turn off TCP listening
          _listener.Stop();
    
          //Waiting for server thread interrupt
          _connectionThread.Join();
    
          //Close all client network data streams
          foreach(NetworkStream s in _streams)
            s.Close();
    
          //Clear _Streams generic collection
          _streams.Clear();
    
          //Turn off client connection
          foreach(TcpClient client in _clients)
            client.Close();
    
          //Clear the contents of _clients generics
          _clients.Clear();
    
          //Waiting for all client threads interrupt
          foreach(Thread t in _threads)
            t.Join();
    
          //Clear the contents of the _threads generic collection
          _threads.Clear();
    
        }
      }
    }
    

    Need a super terminal: HypertRM, this Baidu can download, after all, is a course of buying, although not expensive, but sharing is a bit wrong, so do not share the terminal and how to connect. Forgive me.

    Effect: The effect of "S" after the super terminal interface is entered as follows:

    image

    相关文章

      网友评论

          本文标题:VisionPro C# written job scripts

          本文链接:https://www.haomeiwen.com/subject/rmqsnltx.html