Getting Started

Cognex Designer is an integrated development environment for developing 2D and 3D machine vision applications. The software allows machine vision developers to create flexible solutions to complex machine vision challenges.

Leveraging over thirty years of vision engineering, Cognex Designer provides multi-camera support, drag-and-drop application and HMI development environments, high-speed discrete input/output and factory floor networking protocol support, and advanced scripting and user management features.

The Cognex Designer Help File will help you:

  • Become familiar with the Cognex Designer Integrated Development Environment
  • Walk you through the entire process of Developing a Cognex Designer Project
  • Show how to interact with other devices through Industrial Communications and Precision I/O
  • Provide helpful How To... guides
  • Finish your project by successfully Deploying a Cognex Designer Project

Release Information

Legal Notices


Release Information

This section contains information about the current release of Cognex Designer and the release history.

Security Requirements for VisionPro

About this Release

Migrating to This Release

Resolved Issues

Known Issues

Product and Upgrade Codes

Supported Hardware

Designer Sample Projects

Release History


Security Requirements for VisionPro

The latest release of VisonPro requires the latest VisionPro drivers and the latest supported VisionPro dongles, made by Wibu-Systems.

Dongles supporting VisionPro releases 9.2 and older are not supported by Cognex Designer.

Always consult the Cognex VisionPro web page or installation documentation for up-to-date information on what dongle to use with your current version of VisionPro.


About this Release

Cognex Designer 4.0.0 introduces multiple new or changed capabilities since the previous generally available (GA) release (2.7). For a brief summary of key features in this release, play the video.

Click here to launch in a separate window.

  • Supports VisionPro 9.3
  • Supports Cognex ViDi Suite - Supports Cognex ViDi Suite, which enables Deep Learning programming within Cognex Designer. The ViDi Suite is a separate product and requires an additional license and installation. Please see the Cognex Deep Learning-based Image Analysis page or contact your Cognex sales representative for more information about the ViDi Suite optional plug-in for Cognex Designer.
  • WebHMI - With WebHMI: A Functional Overviewaccess your deployed application through a standard browser, enhancing user productivity. Run your remotely hosted applications, free from the constraints of local sites and domains. Drag and drop a display or viewer object on Web Pages and bind objects to any tag, function, or query. Create JavaScript Overview to add advanced functionality to your WebHMI applications. Deliver your vision application securely with support for Web authentication andSetting Timeout for WebHMI log-ins. For more information, see WebHMI: A Functional Overview.
  • Improved IDE and New Graphical Editing Shortcuts - Featuring a high-resolution rich-text interface, ability to add multi-line text to labels, and other convenient graphical shortcuts for Working With Task Blocks and Working With Script Blocks.
  • Localization - Manage multiple-language translations from a single interface with Project Localization.
  • Launch Page - Use the Cognex Designer Launch Page to quickly open new projects, saved projects or sample projects with a few mouse clicks.
Note: See the Release History topics for a summary of major new capabilities that were introduced in the previous releases of Cognex Designer.

PC Requirements

Operating System Requirements

Plugin Development Requirements

Vision Controller Requirements

Web Browser HMI Requirements

About Cognex ViDi Suite


PC Requirements

Cognex Designer shares the same PC configuration requirements that VisionPro supports. Please see the PC Configuration Guide, which is accessible from the Windows Start Menu (Cognex > VisionPro > Documentation > English > Hardware Manuals).

Note: For a complete list of compatible versions of Cognex Designer and VisionPro, please visit the Cognex Designer Support Website.


Operating System Requirements

Microsoft Windows Operating System | Service Pack | English | German | Japanese | Korean | Simplified Chinese
Windows 7 Premium/Professional/Ultimate (64-bit) | SP1 | ✓ | ✓ | ✓ | ✓ | ✓
Windows 8.1 (64-bit) | Update 1 | ✓ | ✓ | ✓ | ✓ | ✓
Windows 8 Embedded (64-bit) Note: Installed on the Cognex Vision Controller |  | ✓ | ✓ | ✓ | ✓ | ✓
Windows 10 (64-bit) |  | ✓ | ✓ | ✓ | ✓ | ✓
Note: Cognex Designer is not localized and so changing the language of the OS will not affect the language in the development environment.


Plugin Development Requirements

The following requirements are necessary for developing plugins for Designer:

  • Microsoft Visual Studio 2012, 2013 or 2015

    Note: Microsoft Visual Studio 2013 is NOT supported on the Windows Embedded 8.0 OS used on the Vision Controller.

  • Microsoft .NET Framework 4.6


Vision Controller Requirements

Cognex Vision Controller Requirements

For information regarding the Cognex Vision Controller requirements, please consult the Cognex Designer Support Website. The Technical Bulletins contain additional information about updating the Vision Controller to the latest release of both Cognex Designer and VisionPro.


Web Browser HMI Requirements

  • Google Chrome™ browser, version 54 or greater
  • Internet Explorer version 11
Note: >
  • For the best performance, Cognex recommends using Google Chrome version 54 or greater to view and interact with your Web-based HMI.
  • Due to issues in Internet Explorer and Google Chrome, displaying HMIs in Web Browsers for a long period of time (multiple days) can result in the browser window being non-responsive or the browser crashing. Cognex recommends periodically restarting the Web Browser in this scenario.


About ViDi (Deep Learning)

About the Cognex ViDi Suite of Tools

The Cognex ViDi Suite uses deep learning to accomplish tasks not previously possible using traditional machine vision software libraries.

The Cognex ViDi Suite tools share a common engine, but each tool has a distinct focus:

  • Localization (Blue Locate tool)
  • Cosmetic inspection (Red Analyze tool),
  • Classification (Green Classify tool)
  • Hard-to-read OCR (Purple Read tool)

By using the ViDi plug-in, you enable deep learning integration capabilities with Cognex Designer.

See the ViDi documentation for complete information about the ViDi and Cognex Designer integration.


Migrating to this Release

This topic contains information about changes that may affect existing projects when migrating projects from the last release of Cognex Designer (Cognex Designer 2.7) to the current release of Designer.

Note: For more information about migrating from earlier releases, see the Release Migration History topic.

  • Update to .NET Framework 4.6

    Existing plugins will continue to work. However if existing plugins need to be rebuilt or when creating new Plugins, the project must target .Net Framework 4.6. Plugin developers should consult the Updating a Visual Studio Plugin Project for more information.


Resolved Issues

Cognex Designer 3.0 introduces multiple new or changed capabilities since the previous generally available (GA) release of Designer (2.7):

This section describes changes and resolved issues in Cognex Designer 3.0.

Note: Change Request numbers (CR#) have been included (where applicable) to improve the tracking of issues reported via Cognex Technical Support.
CR# | Issue
33048 | Can reconfigure script I/O without losing data
34076 | Designer crashes when switching back and forth between classic and aero themes.
36745 | Script exception message to link to actual script for easier diagnostics.
38370 | Publish $Reconfigure method for Serial and TCP devices.
44464 | TCP / IP device not correctly processing byte data
49033 | TCP Server loses data when being flooded


Known Issues

Known Issues and Changes In Behavior

  • As of release 4.0.0, 2.x Cognex Designerproject sequences are replaced with a sub task.

  • In release 4.0.0, tasks will take a longer time to execute in Test Mode than in release 2.x. This is due to increased Garbage Collection time in the development environment. As a result, always benchmark using a deployed application.

  • Cognex Designer 2.1 will fail to launch (a Mandatory Designer Plugin Not Available error message will be displayed) if the PC also contains Cognex Designer 2.5 and VisionPro 8.4. To use Designer 2.1, uninstall Designer 2.5.

    Cognex Designer 2.5 requires VisionPro 9.0 to work correctly.

    Note: For a complete list of compatible versions of Cognex Designer and VisionPro, please visit the Cognex Designer Support Website.
  • Cognex Designer 2.1 Cannot be Used on a PC That Also Has Cognex Designer 2.5 and VisionPro 8.4

  • Store Project Files and Related Content in the Same Directory

    Cognex recommends to store all files needed for a Designer project in the same directory as the project (by default MyDocuments\CognexDesigner\Projects\{ProjectName). Since this includes database files, recipes, resources, etc., try to avoid sharing files between projects because the Save As operation copies files and folders only from the project folder.

  • Windows Defender

    If Windows Defender is enabled for real-time protection it may also perform disk scans at a user-specified time. The disk scans may interfere with busy vision software applications. If so, consider disabling Windows Defender, or managing behavior in a manner appropriate for the application.

  • The Expression Builder 'ItemAt($index, $array) ' Function Does Not Update the Returned Value When Items in the Collection Change

    When an "ItemAt($index, $array)" function is constructed in the Expression Builder, it will only update the returned value when the value of the "$index" tag changes, or a new array is assigned to the "$array" tag.

    The following C# script statements illustrate how to trigger a value change event:

    $index++;
$array = { "one", "two", "three" };

    The following C# script statement will not trigger a value change event:

    $array[1] = "new value";

  • VisionPro Tool Editor and ToolBlock Editor Controls Modifications While a Task is Running

    If a Page contains a VisionPro Tool Editor or VisionPro ToolBlock Editor element, they should be configured to not allow user interaction while the application sequence is running. Changes to these two types of controls can be made when the application is being modified at design time in the development environment, or in a deployed application, but only when the sequence using the tools is not running.

  • Unable to Load Microsoft® SQL Server® Database That Contains decimal, money or smallmoney Column Data Types

    Designer does not support the decimal, geography, hirachyid, image, money, numeric, smallmoney , sql_variant, time, timestamp and xml data type parameters. When creating a database, ensure that these types are not used for columns, otherwise Designer will be unable to connect to the database.

    Designer only supports a sub-set of data types: bigint, binarybit, char, date, datetime, datetime2, datetimeoffset, float, int, nchar, ntext, nvarchar, real, smalldatetime, smallint, text, tinyint, uniqueidentifier, varbinary, varchar. Use Microsoft® SQL Server® 2008 Management Studio or later to create and edit SQL Server databases.

  • Modifications to Page Elements During Test Mode Persist

    If an element on a Page (e.g. CheckBox, TextBox, etc.) is modified while in Test Mode, after exiting Test Mode, the element will not return to its state prior to entering Test Mode. To do so, the Designer OnStartup Script must be used to explicitly set the default values of Page elements. For example, if a Page contained a TextBox which should be blank at startup, the script would be:

    $Pages.Page.TextBox.Text = string.Empty;

  • Return Statements in Designer Script Editor

    When wanting to use a return statement to exit a script function, use the "return null;" statement, instead of the "return;" statement. In the Designer Script Editor, scripts must always return an object, even though the signature of the script function returns void.

  • Designer User Authentication and Authorization

    Designer offers a simple mode for user authentication and authorization, and is not intended to be used in environments that require high security. For a more secure authentication and authorization model, please use Active Directory.

  • FFP Offline Requested Task Triggers for "Online" and "Offline" Status

    When implementing Factory Floor Protocol communications, it is important to note that within Designer, the OfflineRequested event is mapped into both a scriptable point called FFP Offline Requested and a Task Trigger called Devices.{CommCardName}.FfpOffineRequested. During execution, if the OfflineRequested event is fired, it will run the script registered to the scriptable point called FFP Offline Requested. At this point, the user can access the ReturnToPreviousState member of the argument, and determine the state of the device (False = Offline and True = Online). After this has occurred, the event triggers the FfpOfflineRequested Task Trigger. However, in this case, there is no way to determine the requested state, so any Task registered to run as a result of this trigger will be executed, regardless of the state.

  • Referencing Cognex.Designer and Visual Studio 2012 and 2013 Issues

    When referencing any Cognex.Designer assembly in a Visual Studio projects, the XAML designer may crash on 64-bit platforms when using Visual Studio 2012 with updates or later. To work around the problem, you can do any of the following:

    • Use Visual Studio 2015 or later.
    • On 64-bit systems, use Visual Studio 2012 without any updates.
    • Use a 32-bit platform, with 32-bit versions of Cognex Designer and VisionPro. In this case, you can use Visual Studio 2012 with updates and Visual Studio 2013 as well.
    • Use an XML editor (without a UI designer).
    • On 64-bit systems, install Cognex Designer under the Program Files (x86) folder (we suggest this workaround only for developing HMI Plugins).

  • Designer Must Always Use the Launcher

    Running Cognex.Designer.exe directly is not supported, and functionality may not work correctly. Always use the Cognex.Designer.Launcher to start Designer.

  • Uninstalling/Reinstalling Software on a Cognex Vision Controller

    In the event that the default installations of VisionPro or Designer need to be uninstalled and then newer versions installed, if a black desktop (no Cognex wallpaper) and a blank, blue Taskbar is encountered after the initial reboot after uninstalling/reinstalling, press the Windows Logo key to return to the Start screen, and then select the Desktop tile/icon to return to the correct Desktop.

  • Changing the Primary Language of the Operating System on a Cognex Vision Controller

    If the primary language of the Operating System on a Cognex Vision Controller is changed (e.g. from English, the default language, to Simplified Chinese), the Vision Controller will need to be restarted. In the event that the desktop appears without the Cognex wallpaper and a blank, blue Taskbar is encountered after the reboot, press the Windows Logo key on your keyboard to return to the Start screen. Next, select the Desktop tile/icon to return to the correct Desktop.

  • Factory Floor Protocol to Output Mappings

    A startup issue whereby if the mapping is set to falling-edge trigger, and the bit state is low, and another signal transition causes the factory protocol to push an update through the logic, the mapping will false-trigger one time and incorrectly fire the discrete event.

    This only occurs when the bit state starts low, and the mapping is set to falling-edge trigger, or the bit state starts high, and the mapping is set to rising-edge trigger.


Product and Upgrade Codes

  • API Version: 4.0.0
  • Upgrade codes
    • x64 - 84F14F46-58D4-4B7C-A963-4C7F1D57D1DB
  • Product Codes
    • x64 - 21B3FB72-8EEE-4B76-9D37-26EE0ED5F464


Supported Hardware

The following acquisition platforms, communication cards, cameras and sensors are supported by Cognex Designer.

Supported Acquisition Platforms and Communication Cards

Supported Cameras and Sensors


Supported Acquisition Platforms and Communication Cards

  • Cognex Vision Controller
  • Cognex CC24 I/O Communication Card
  • Cognex CFG-8704e Frame Grabber Card
  • GigE Vision
  • MVS-8602e CameraLink
  • Acquisition Interface Kit (AIK)


Supported Cameras and Sensors

  • Cognex 2D Industrial Cameras (CIC cameras)
  • Cognex 3D Displacement Sensors (DS900 series and DS1000 series)
  • As well as those supported by VisionPro for the Acquisition Platforms listed above.


Designer Sample Projects

Designer includes a sample project to help illustrate how to use the program, and how different elements of Designer fit together to create modern machine vision application solutions. For more information on opening the sample project, see the Cognex Designer Launch Page - Sample Projects topic.

Tip: For additional information and sample codes and projects, please visit the Cognex Designer Support Site. A link to the Cognex Designer Support Site is also included in the Help menu.
Note:

Subject to Cognex Corporations terms and conditions and license agreement, you are authorized to use and modify this source project in any way you find useful, provided the Software and/or the modified Software is used solely in conjunction with a Cognex Machine Vision System. Furthermore you acknowledge and agree that Cognex has no warranty, obligations or liability for your use of the Software.

This sample program is designed to illustrate certain Cognex Designer features or techniques in the simplest way possible. It is not intended as the framework for a complete application. In particular, the sample program may not provide proper error handling, event handling, cleanup, repeatability, and other mechanisms that a commercial quality application requires.

Copyright (C) 2004-2017 Cognex Corporation


Release History

The following topic lists the features and resolved issues in previous releases of Cognex Designer.

Note: Cognex Designer is backward compatible, which means that projects created with earlier Designer versions can be opened and edited. Designer does not support loading projects created by a newer version of Designer in an earlier version.

Cognex Designer 2.7 Release

Cognex Designer 2.7 introduced multiple new or changed capabilities since the previous generally available (GA) release of Designer (2.6):

  • Supports VisionPro 9.2
  • No longer supports x86 (32-bit)

Resolved Issues in Designer 2.7

CR# | Issue
44464 | Serial device not correctly processing byte data

Cognex Designer 2.6 Release

Cognex Designer 2.6 introduces multiple new or changed capabilities since the previous generally available (GA) release of Designer (2.5):

  • Supports VisionPro 9.1
  • Supports .NET Framework 4.6
Note: This primarily affects plugin developers.

Resolved Issues in Designer 2.6

CR# | Issue
41629 | Fixed an issue, where a tag exposed in a VisionPro ToolBlock got into an invalid state and caused start up error.
40523 | Fixed an issue with obfuscation that prevented custom Plugins being developed using Visual Studio 2015.

Cognex Designer 2.5 PR5 Release

Cognex Designer 2.5 PR5 introduces multiple new or changed capabilities since the previous generally available (GA) release of Designer (2.1):

  • Update Properties of RS232 and TCP/IP Devices

    The right-click menu for RS232 and TCP/IP Devices has been updated and now includes a Reconnect option, which allows you to reconfigure the properties of a previously connected device.

    In addition, the properties of RS232 devices can be updated programmatically, while at runtime.

  • Updated VisionPro Display 3D and New VisionPro Display 3D Status Bar

    The VisionPro Display 3D has been updated with the new control introduced in VisionPro version 9.0, and the VisionPro Display Status Bar 3D element has been added as a new control in Designer 2.5.

  • Find/Replace Dialog for the Script Editor

    A Find and Replace dialog has been added to the Script Editor, using the Script Editor Keyboard Shortcuts.

  • Minimize the Window of Deployed Applications

    The Windowed Mode parameter has been added to the Deployment Options dialog, which determines whether or not the deployed application window can be minimized.

  • Add External Assemblies to Designer Projects

    The ability to add custom or 3rd party DLL/.NET assembly references to your project, which allows you to create tags of any data type, through the External Assemblies tab of the Project Settings dialog, and the Script References dialog (see the Adding References topic for more information).

  • Longer Security Operation

    The Designer security mechanism has been modified to last 8 hours when using a Cognex USB Development Dongle.

  • New Database Sample

    A new sample project has been added to the Cognex Designer Launcher - Samples tab, showing examples for implementing and using databases in Designer.

  • The Cognex Designer User Guide Improvements

    The Cognex Designer User Guide has been overhauled, with a new Table of Contents and numerous new topics, including new How To... topics.

  • Resolved Issues in Designer 2.5 PR4

    CR# | Issue
    41339 | Fixed an issue when loading an older project whose PropertyDefinition is set to null. Now, when loading a project with a ConfigurableBlock that has a PropertyDefinitions property set to null, it will be converted to an empty array.
    41311 | Fixed an issue present in Designer 2.5 PR1, PR2 and PR3 that affected custom plugins, in which a published property in an abstract class would not be detected.
    39276 | Fixed an issue when loading projects in Designer 2.5 that were created in Designer 2.0, which resulted in Designer 2.5 closing unexpectedly.
    38936 | Fixed an issue with the Format PLC Output Data block throwing a "Specified cast is not valid" error, when migrating a project from Designer 2.0 to 2.5.
    39283 | Fixed an issue when a Cog3DPlane value was saved as a persistent tag. The value is now saved and restored correctly.
    39528 | Fixed an issue with Data Change scripts which could cause a "The data change script is no longer connected to a tag." error message.
    38292 | Fixed an issue when loading large projects; the Designer application could take additional time to startup while the project was loaded.
    36625 | Fixed an issue with an Out of Memory - Value of an input and output pin in a Sub Sequence block was saved in a project file.
    36505 | Fixed an issue where an Unhandled Exception was encountered when logging in via Remote Desktop to a Vision Controller while a Designer project was running.
    36510 | Fixed an issue with a possible deadlock on long running image inspection tasks.
    36507 | Fixed an issue with a Parallel region Task 'InvokeAsync' error.
    35185 | Fixed an issue with deployed applications, which showed script compile errors at startup: "Could not write to output file 'C:\%TMP%\z13st3bc.dll', The process cannot access the file because it is being used by another process."
    35503 | Fixed an issue with a project freezing when a Sequence was run, and a VisionPro Tool Block is open.
    35568 | Fixed an issue where changing the SelectedItem property in one SelectionBox would change the SelectedItem property in an unrelated SelectionBox.
    35723 | Fixed an issue where Designer would crash when using a CogPMAlignTool on the Vision Controller.
    36168 | Fixed an issue where the Tag Browser would open slowly if there were more than 1000 tags.
    36165 | Fixed an issue where disconnecting a camera would cause any links to the associated Camera block to be broken.

Cognex Designer 2.1 PR1 Release

  • Updated Project File Format

    The file format of Designer projects has been modified, and when projects developed in previous versions of Designer are opened and loaded in Designer 2.1, they will automatically be converted to the new format.

  • Sub Sequence Blocks now Allow Input/Output Pins

    The Sub Sequence block has been updated and modified, and now contains internal and external input and output pins to help configure a Sequence.

  • Updated Data Type Selector

    The Data Type Selector has been updated and modified, and now also contains the ability to create data type arrays and/or generic data types with the Complex Type Selector.

  • Create Arrays

    The ability to create single-dimensional and multi-dimensional arrays of data has been added, through both the Complex Type Selector and in the Expression Builder. This allows Designer to pass groups of related data around a project. For example, transferring arrays of integers, doubles or CogBlobResults from one Sequence block to another.

  • Updated Template File Format

    The file extension for the template files has been updated, from .cdt to .cdtx. Please see the Templates and Migrating to this Release topics for more information about the file format change.

  • Updated Recipe File Format

    The file format for Recipes has been modified. Please see the Migrating to this Release topic for more information about the file format change.

  • Updated Keyboard Shortcuts

    The following keyboard shortcuts have been introduced:

    • CTRL+S: Saves a project.
    • F1: Opens the Cognex Designer User Guide.
    • F2: Used to rename a node in the Application Explorer treeview.
    • F5: Used to start and stop Test Mode.
    • F6: Executes the current Sequence, or compiles the current script (depending on which editor is active, e.g. the Sequence Editor or the Script Editor).

  • Resolved Issues in Designer 2.1

    CR# Issue

    Added the ability to create arrays of data using the Complex Type Selector, and basic functions to handle arrays in the Expression Builder.

    33190

    Added keyboard shortcuts to Designer for saving a project (CTRL+S), opening the Cognex Designer User Guide (F1), renaming a node in the Application Explorer treeview (F2), starting and stopping Test Mode (F5) and executing the current Sequence or compiling the current script (F6).

    34614

    Added "String.FormatNumber(value, decimals)" for formatting a double value data type in the Expression Builder.

    34432

    Added the RunAsync(...) function to the Task functions, which allows a Task to be run asynchronously from a script, using the following format: $Tasks.Task.RunAsync(..);

    34416

    Added the ability to publish the recent query results from a database query, through a tag, using a script.

    34410

    Added the ProductVersionString tag, which retrieves the project version information so it can be used programmatically or displayed on the HMI.

    32640

    Fixed an issue where a memory leak was possible during development when a mouse hovered over a pin storing an image.

    32709

    Fixed an issue where a 2D Image Display would be resized when going into Test Mode.

    32814

    Fixed an issue where custom splash screens were not displayed.

    34389

    Fixed an issue where two Script blocks, pointing to the same script, changes in one block were seen by the other block.

    34395

    Fixed an issue where the Tag Manager would not detect a circular tag reference.

    34407

    Fixed an issue where importing tags using CSV files caused an error in some cases due to a missing default value. Tags that were exported with null values will not be able to be imported in Designer 2.1 and later.

    34458

    Fixed an issue where having two tags written to by different Tasks, and binding their sum to a Label, could cause Designer to not respond.

    34470

    Fixed an issue where a TCP/IP Client device would not reconnect after the server shuts down and reopened the connection.

    34809

    Fixed an issue where VisionPro Tool Blocks that share the same input image tag may have crashed when executed in parallel.

    34901

    Fixed an issue where the Expression Builder bitwise operators do not work.

Cognex Designer 2.0 Release

  • Tasks, Sequences and Blocks

    The following enhancements have been implemented. For more information on them, see the Sequence Blocks topic.

    • New Sequence Blocks have been created to make byte array handling easier. These can be used when using the UserData from the FFP on the Cognex Communications Card:
      • Format PLC Input Buffer
      • Format PLC Output Buffer
    • New Sequence Blocks have been created for composing and decomposing arrays, and for retrieving an element of an array, to make the handling of general arrays easier:
      • Compose Collection
      • Decompose Collection
      • Get by Index
    • New String Encoder and Decoder (to/from byte array) Sequence Blocks:

      • Decode Byte Stream Data

      • Encode Byte Stream Data
    • The Notify PLC has been improved to allow setting up the input values directly on the Configuration UI and add a graphical interface to setup complex input values.
    • New Sequence Blocks have been created to “manually” schedule and cancel a (scheduled) PrecisionIO event:
      • Cancel Event
      • Schedule Event

  • Communications

    New Sequence Blocks have been created to make possible using COM port and TCP/IP communication without scripting:

    • Decode Byte Stream Data

    • Encode Byte Stream Data
    • Receive Data
    • Send Data

    Support for SLMP Protocol, similar to existing EIP and PROFINET support, has been added. For more information, see the SLMP PLC Setup topic.

    Added a UI to be able to configure Precision IO events (causes and responses) for the Cognex Communications Card. For more information, see the Precision IO Configuration Editor topic.

  • Templates

    It is now possible to import and export components from a project into a user library and that can be easily re-used in another project. For more information, see the Templates topic.

  • Expression Builder

    The Expression Builder has been revamped. It is recommended to run a project verification that should identify any expressions that are no longer compatible.

    Known differences since v1.0:

    • Equality comparison between an object and a string used to perform string comparison (e.g. converting the object to string first), allowing expressions like: $myBoolTag="True". This is no longer allowed.
    • Numeric values were compared as integers, e.g. 3.14 = 3 evaluated to true. This has been fixed.
    • The old expression builder was culture-dependent (for example, decimal separators). The new one uses culture-agnostic parser.

    For more information, see the Expression Builder topic.

  • Updated Plugins and Projects

    It is now possible to automatically update a project to a newer version of a plugin it depends on. For more information, see the Updating a Designer Project To a Newer Version Of The Plugin It Uses topic.

  • Designer Launcher Enhancements

    The Designer Launcher has been enhanced with two tabs, Samples and Utilities. For more information on them, see the The Cognex Designer Launcher topic.

  • Opto and Differential Trigger Signals

    Switching between trigger signals no longer requires scripting. See the Switching Between Opto- and Differential Trigger Signals topic.

  • Resolved Issues in Designer 2.0

    Issue | Description
    Designer gives an error about the SQLite database | Third-party applications may install (against SQLite guidelines) the System.Data.Sqlite.dll into the Global Assembly Cache (GAC). This could cause Designer to show the "Visual C++ Runtime Error" message.
    Memory error while saving | This occurred while working with unusually big images and objects.
    Changing the name of a Tag assigned to a Pin is not updated in Sequence Editor | When a Tag assigned to a Pin was renamed, the displayed Tag name in Sequence Editor was not updated/renamed.
    HMI builder hangs when using an ungroup command | The HMI builder hanged when two or more HMI elements were grouped, and an additional element (type already existent in the group as well) was created and then the grouped elements were ungrouped.
    DS1100: The laser does not shut down when the user exits from Designer | It was possible to enable the laser in Acquisition Wizard and then exit Designer with the laser on.
    Project file is corrupt and asks for a password when loading | The saving process had to be enhanced to prevent accidental effects on the project file.
    Unhandled exception when closing Designer and a connected device is being renamed | When Designer was closed while a connected device was being renamed the application threw an unhandled exception.
    Replacing and renaming tags stop working after saving and reopening the project | Replacing and renaming tags in scripts did not work after saving and reloading the project until the scripts were recompiled.
    The Save As functionality does not transfer necessary files | When Save As was used to save an existing project under another name/path, only the .cdp file was copied/renamed to the new location. This function has been enhanced to copy all files and subdirectories from the original project path as well.

Cognex Designer 1.0 PR1 Release

The Cognex Designer 1.0 Patch Release 1 did not contain any new features compared to version 1.0, only enhancements to existing features and resolved issues.

Release Migration History

Previous Product and Upgrade Codes


Release Migration History

Closed Migrating projects from Cognex Designer 2.1 to Designer 2.5

This topic contains information about changes that may affect existing projects when migrating projects from Cognex Designer 2.1 to Designer 2.5 PR5.

  • Using the Updated VisionPro Display 3D and New VisionPro Display 3D Status Bar

    The VisionPro Display 3D control has been updated with the new control introduced in VisionPro version 9.0, and VisionPro Display Status Bar 3D is a new control in Designer 2.5. This will affect projects that were using the VisionPro Display 3D control in their HMI.

    The following considerations apply to the new controls:

    • The previous VisionPro Display 3D included a right-click context menu which could be used to display the X, Y and Z coordinates either on the display itself, or in a built-in status bar (or both). These options have been removed from the new VisionPro Display 3D control. Now, in order to display the coordinates, you must add a VisionPro Display 3D Status Bar and configure the Subject property to the VisionPro Display 3D.
    • The VisionPro Display 3D does not support displaying 2D images as height maps; these types of images will not be displayed and a warning will be shown, instead.
    • The VisionPro Display 3D does not work when using a Windows Remote Desktop Connection. Third party options, such as VNC® or TeamViewer, may be used.
    • The VisionPro Display 3D requires a VisionPro security bit; therefore, previously created Designer projects will need to be updated with this security bit to continue to work correctly.
    • The VisionPro Display 3D will not work on virtual machines.
Closed Migrating projects from Cognex Designer 2.0 to Designer 2.1

  • New Project File Format

    The file format of Designer projects has been modified, and when projects developed in previous versions of Designer are opened and loaded in Designer 2.1, they will automatically be converted to the new format. Projects saved in Designer 2.1 cannot be opened in previous versions of Designer. For more information, see the Cognex Designer Version Compatibility topic.

  • Recipes Folder Location

    For Designer 2.1, the folder location of Recipes will no longer be editable, and must be located in the following directory: <ProjectName>\Recipes\<RecipeName>

    Note: If you had edited the Recipe directory location in 2.0, you must manually move your Recipe folder into the new directory location.

  • Recipes File Format Conversion

    Recipes will only be converted from XML to JSON format when they are being loaded through the System.Recipes.{RecipeName}.Load and the System.Recipes.{RecipeName}.LoadFile methods.

  • New Template File Extension in Designer 2.1

    For the Designer 2.1 release, the Template file extension was updated from .cdt to .cdtx. The first time that you start Designer 2.1, all of your .cdt template files will be automatically converted to .cdtx files, with the same name. Both files will exist in the Templates directory (C:\Users\<username>\Documents\Cognex Designer\Templates).

    If you delete a .cdtx file, you will also need to delete the .cdt file. Otherwise, when you start Designer 2.1 again, or refresh the tree view in the Template Browser, Designer will automatically perform the conversion process again and recreate another .cdtx file, based on the .cdt file.

  • Read IO and Write IO Block Visible Pins State Change

    In Designer 2.0, it was possible to add and configure Read IO and Write IO blocks with Visible Pins, even though they did not have the Selected Device property set to a supported device (Cognex Communication Card or Vision Controller). If a project is loaded in Designer 2.1 which has these types of Read IO and Write IO block configurations, the pins will not be visible until the Selected Device property is set, and any links between the pins will disconnected and have to be reset.

Closed Migrating projects from Cognex Designer 1.0 to Designer 2.0

  • MessageID Pin Type Changed

    The MessageID pin of the Notify PLC block in AsyncSoftEventComplete has been changed from a int (Int32) data type to a long (Int64) data type.

    Note: This does not cause any issue with existing projects.

  • Opening 1.0 or 1.0 PR1 Projects in Designer 2.0

    When a Designer 1.0/1.0 PR1 project is opened in version 2.0, the UsedAcquisitionIDCollection pin of the Notify PLC block in InspectionCompleteMode will be replaced with two other pins: AcquisitionID0 and CameraIndex0. If you have more than one cameras, you can set it in the block’s Configuration UI.

  • "Assign New Tag" Option

    Starting with Designer 2.0 the Assign to New Tag option on a pin does not initialize the created tag with the data-type’s default value.

  • Read IO Block New Pin

    A new pin has been added to the Read IO Block: PrioState.

  • Expression Builder

    The Expression Builder has been revamped. It is recommended to run a project verification that should identify any expressions that are no longer compatible.

  • Opening 1.0 projects that have WriteIOBlock with pins

    When an 1.0 project is opened in version 1.0 PR1, the existing "DS1000OutputBank0Line0" "DS1000OutputBank0Line1" pins of a WriteIOBlock will be replaced with new empty pins. If the pins were assigned to tags, the connection to the tags will be no longer available. This means that the user has to reassign the pins to the tags (since they are still available in Tag Manager).

  • Migrating Plugins From Designer 1.0 to 1.0 PR1

    After Designer 1.0 PR1 is installed, all new projects created using either 1.0 or 1.0 PR1, will use the 1.0.1 VisionPro Plugin. Old projects that use VisionPro Plugin 1.0.0.0 will need to be updated to VisionPro Plugin 1.0.1, using the Edit Project Plugins option from the Launcher. Click Edit Project Plugins, select the desired .cdp project file in the Open file dialog box, and check/uncheck the desired plugins.


Previous Product and Upgrade Codes

Cognex Designer 2.6

  • API Version: 3.5.0
  • Upgrade codes
    • x86 - A667A24A-4053-46DB-9F21-08C7C1AAF225
    • x64 - 09463BE5-A8A1-4A11-B5F4-1FB103045FFD
  • Product Codes
    • x86 - 20314593-0303-4894-8971-4449E16DC793
    • x64 - E2951431-1CD9-4B62-ADF4-43A5FD71C387

Cognex Designer 2.5 PR5

  • API Version: 3.4.2
  • Upgrade codes
    • x64 Upgrade Code : {05535DD2-B5CE-43AC-8A6F-B3E6F688152D}
    • x86 Upgrade Code: {6F5CE606-BF9D-49C0-AF35-A0D640DCB7EC}
  • Product Codes
    • x64 Product Code: {BE5CEE3F-827E-46B6-B5FF-B1367B2CF87C}
    • x86 Product Code: {E58141E1-53E6-4B45-9CD1-11E6D4D42857}

Cognex Designer 2.5 PR4

  • API Version: 3.4.1
  • Upgrade codes
    • x64 Upgrade Code : {05E4ECBF-F7DD-4A0B-B89A-1DE7AF62EDCE}
    • x86 Upgrade Code: {3AF8F441-3C09-407B-9D3A-32043FC71139}
  • Product Codes
    • x64 Product Code: {088A01D1-C55D-40E4-8564-979121053E0E}
    • x86 Product Code: {A4CF8B0B-7291-462E-A402-77E1A1863566}

Cognex Designer 2.5 PR3

  • API Version: 3.4.0
  • Upgrade codes
    • x64 Upgrade Code : {2A5E6455-3836-4355-AF7F-38756089B7E1}
    • x86 Upgrade Code: {4BC0E777-A9FD-4D5C-9D9D-16D9602F8BCA}
  • Product Codes
    • x64 Product Code: {700FEF35-30BD-4CD2-90EE-4BD07AE68EED}
    • x86 Product Code: {F05AD810-2439-43E2-84DB-7455C01E2EE6}

Cognex Designer 2.5 PR2

  • API Version: 3.3.0
  • Upgrade codes
    • x64 Upgrade Code : {0DDB9972-5984-40B0-9C66-CC1FBD7FBF7A}
    • x86 Upgrade Code: {8F99785D-6FB4-4338-A4FD-14A404846DD5}
  • Product Codes
    • x64 Product Code: {7362BAC2-5DEF-4442-B60B-B1F409437762}
    • x86 Product Code: {620CA0D5-F890-4B52-B422-4391BB662BC1}

Cognex Designer 2.5 PR1

  • API Version: 3.2.0
  • Upgrade codes
    • x64 Upgrade Code : {23113A5C-4075-49AA-8810-7C4A3EAD3987}
    • x86 Upgrade Code: {E53089F6-C513-4833-BD35-F359C356BFEC}
  • Product Codes
    • X64 Product Code: {AEA08E15-7752-4BD1-A914-A23C9D575147}
    • X86 Product Code: {81C5F404-0820-449C-968A-2FA3FD666C6B}

Cognex Designer 2.5

  • API Version: 3.1.0
  • Upgrade codes
    • x64 Upgrade Code : {E2C81BA6-E13A-4A4E-85D2-D95D15FF228E}
    • x86 Upgrade Code: {FC3C5831-C296-4D05-8103-C21072024C31}
  • Product Codes
    • X64 Product Code: {263D442E-D9F2-43CE-9360-0DD4F50CCE4E}
    • X86 Product Code: {480E41FB-CE00-4ED1-A0EB-A7D958A8A84E}

Cognex Designer 2.1

  • API Version: 3.0.0
  • Upgrade codes
    • x64 Upgrade Code : {97F0B719-546F-4AA6-BC55-815FCA69EC23}
    • x86 Upgrade Code: {5F63548C-8FD0-4989-8DC5-9461DDD1C151}
  • Product Codes
    • X64 Product Code: {588BE36C-5F7E-440D-BEA3-B443FC39A9FF}
    • X86 Product Code: {C898076C-30E1-4614-A126-A69112EE32C7}

Cognex Designer 2.0

  • API Version: 2.0.0
  • Upgrade codes
    • x64 Upgrade Code : {02DBDD85-75DB-42A9-AC6C-F489779D3C6B}
    • x86 Upgrade Code: {FDA5A797-AB67-47F3-98E4-A1D6BFB7462B}
  • Product Codes
    • X64 Product Code: {62FE9614-45D0-4CFB-A0C5-FF30B5C96E62}
    • X86 Product Code: {7712CB00-516B-412D-A60D-60F070E12352}

Cognex Designer 1.0 PR1

  • API Version: 1.0.1
  • Product Codes
    • X64 Product Code: {0DE9D772-01F8-4CE9-A3A5-20F03C8F710E}
    • X86 Product Code: {63293020-9AFE-4125-A08D-90934DE68935}

Cognex Designer 1.0

  • API Version: 1.0.0
  • Product Codes
    • X64 Product Code: {B5F274C9-A833-46C8-A479-BBC9DC7FE016}
    • X86 Product Code: {7984E600-9901-4B0D-82B6-8997B0E97B40}


Legal Notices

The software described in this document is furnished under license, and may be used or copied only in accordance with the terms of such license and with the inclusion of the copyright notice shown on this page. Neither the software, this document, nor any copies thereof may be provided to, or otherwise made available to, anyone other than the licensee. Title to, and ownership of, this software remains with Cognex Corporation or its licensor. Cognex Corporation assumes no responsibility for the use or reliability of its software on equipment that is not supplied by Cognex Corporation. Cognex Corporation makes no warranties, either express or implied, regarding the described software, its merchantability, non-infringement or its fitness for any particular purpose.

The information in this document is subject to change without notice and should not be construed as a commitment by Cognex Corporation. Cognex Corporation is not responsible for any errors that may be present in either this document or the associated software.

Companies, names, and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, nor transferred to any other media or language without the written permission of Cognex Corporation.

2019 April 10 10:45 AM

Revision: 4.0.0.8

Copyright © 2017. Cognex Corporation. All Rights Reserved.

Portions of the hardware and software provided by Cognex may be covered by one or more U.S. and foreign patents, as well as pending U.S. and foreign patents listed on the Cognex web site at: http://www.cognex.com/patents.

The following are registered trademarks of Cognex Corporation:

Cognex, 2DMAX, Advantage, AlignPlus, Assemblyplus, Check it with Checker, Checker, Cognex Vision for Industry, Cognex VSOC, CVL, DataMan, DisplayInspect, DVT, EasyBuilder, Hotbars, IDMax, In‑Sight, Laser Killer, MVS‑8000, OmniView, PatFind, PatFlex, PatInspect, PatMax, PatQuick, SensorView, SmartView, SmartAdvisor, SmartLearn, UltraLight, Vision Solutions, VisionPro, VisionView

The following are trademarks of Cognex Corporation:

The Cognex logo, 1DMax, 3D‑Locate, 3DMax, BGAII, CheckPoint, Cognex VSoC, CVC‑1000, FFD, iLearn, In‑Sight (design insignia with cross‑hairs), In‑Sight 2000, InspectEdge, Inspection Designer, MVS, NotchMax, OCRMax, PatMax RedLine, ProofRead, SmartSync, ProfilePlus, SmartDisplay, SmartSystem, SMD4, VisiFlex, Xpand

Portions copyright © Microsoft Corporation. All rights reserved.

Portions copyright © MadCap Software, Inc. All rights reserved.

Other product and company trademarks identified herein are the trademarks of their respective owners.


Cognex Designer Integrated Development Environment

This section describes the Integrated Development Environment (IDE) of Cognex Designer. This is used to develop your machine vision application prior to deployment.

Graphical Features of the IDE

The Cognex Designer IDE supports the following graphical features;

  • Rich Text, making pin names more readable
  • Multi-line Text that can be used when adding labels
  • Arrowheads available with lines
  • Enhanced Zoom-in and Zoom-out capability

Cognex Designer IDE Areas

The Cognex Designer IDE is structured into four main areas.

Tip: Cognex Designer supports customizing the development environment through dock-able windows, so the environment can be re-arranged to the user's preferences.

  1. The Project Explorer, which is used to add, configure and organize everything within your project.

    • System
    • Pages
    • Scripting
    • Databases
    • Tasks
    • Components
    • Devices

  2. The Project Editors, which are used to construct your project:

    • Task Editor
    • Page Editor
    • Expression Builder
    • Tag Manager
    • Script Editor
    • Recipe Editor
    • Alarm Editor
    • Precision IO Configuration Editor

  3. The Project Windows area, which are used to navigate your project:

    • Search
    • Tag Browser
    • Template Browser
    • Toolbox

  4. The Project Diagnostics area is used to monitor your project:

    • Errors
    • Output
    • Project Verification
    • Watch
    • Communications Monitor
Note: For more information related to how to use Cognex Designer, please see the Developing a Cognex Designer Project topics.

Project Explorer

Cognex Designer Launch Page

Project Editors

Quick Navigate

Project Windows

Project Diagnostics


Project Explorer

The Project Explorer shows the contents of the current application. It is divided into different categories, or nodes, depending on the different functionality.

To interact with the nodes in the Explorer, double-click on an item in a category to perform the item's default action, and right-click items to launch a context sensitive menu for configuration options.

Note: You can password protect some of the items in the Project Explorer, such as pages and tasks that you create. For more information, see Project Component Password Protection.

  • System: Contains the configuration options for Alarms, Project Localization, Resources, Project Settings, Tag Manager and User Access.

  • Recipes: Contains all of the recipes in the project. New recipes can be added through the right-click menu.

  • Task: Contains all of the currently configured processing tasks. New tasks can be added through the right-click menu.

  • Web Pages: Contains all of the WebHMI pages configured in the project. Organizational folders and new Web Pages can be added through the right-click menu.

  • Page: Contains all of the HMI pages currently configured in the project (these can be organized into folders, if necessary).

  • Scripting: Contains all the configured User Scripts, Key Scripts and Data Change Scripts configured in the project. New scripts can be added, and existing scripts can be organized into folders, if necessary.

  • Databases: Contains all of the databases attached to the project, as well as their associated tables and queries. A new database can be created through the right-click menu.

  • Components: Contains additional tools, which include a Clock, Disk Monitor, Inactivity Monitor, Shift Registers and Timers.

  • Devices: Contains the devices currently available to the system; the icon beside the device indicates the current state of the device.


Cognex Designer Launcher

Cognex Designer Launch Page

The Cognex Designer launch page is used to start new projects and open existing projects, provides easy access to Cognex recent projects and sample projects, and launch utilities used to configure components so they can be programmed within Cognex Designer.

Projects

Samples

Utilities


Cognex Designer Launcher

Cognex Designer Projects

Designer projects can be launched by clicking on the option to create a new project, or open an existing or recent one. Cognex Designer Project Files contain the configuration of specific Cognex Designer applications, and they are required in order to make modifications to the application in Development Mode.

New Project

Open Project

Recent Projects


New Project

When using the New Project option, Designer creates a folder using the new project's name. It also creates a .cdp file, with the same name as the folder, upon saving.

Note:
  • The project's name cannot contain special characters, like " < > | : * ? \ / and/or a space.
  • For the full path of the Projects folder, see the Designer Folder Structure topic.


Open Project

Open Project is used to load an entire project, where you select the folder containing the project you want to open.

Note:
  • It is possible to modify the names of the project files and their folder, but to use the Open Project functionality, the folder containing the .cdp file must have the exact same names.

  • If folder is selected that does not contain a project file with the same name, the following error will be shown:


Import Project

Recent Projects

The Recent Projects window is used to load the most recent project files and can be further identified by a date and timestamp.

Note: Hover over the file to see the folder path.


Cognex Designer Launcher - Samples

Cognex Designer Launch Page - Sample Projects

The Sample Projects window shows the available samples for Designer, which illustrates how the Designer functionality is integrated to create a working application.

Note: In addition to the samples installed with Designer, visit the Cognex website for additional samples.

  1. To open a sample project, select and double-click it from the Sample Projects window of the launch page.

  2. This will create a new project in your Projects directory. If you save the newly created sample project, to continue editing or using this version of the project, select it from Recent Projects window in the launch page.

    Note: If you select a sample project from the Sample Projects window, and it has already been opened and saved, Designer will create a new project with a number appended (e.g. FunctionSample1, FunctionSample2, etc.).


Cognex Designer Launcher - Utilities

Cognex Designer Launch Page - Utilities

The Utilities Bar, accessed from the bottom the Launch Page, contains all the applications which are allowed to run from the launch page. Clicking on one of the items listed will launch the selected application. These applications will lock the Designer’s launch page as long as the application is running. If the application does not exist at the given location, it will not show up in the list.

Click the blue bar to see the applications available in the utilities:

  • Cognex GigE Vision Configurator - Used to configure GigE camera(s) connected to the computer.
  • Cognex Comm Card Configurator - Used to configure the Cognex Communication Card.
  • CogCLSerial - Cognex Camera Link Serial Communication Utility, used to configure camera link acquisition.

  • Project Plugin Configurator - Used to add or remove a plugin in a specific project file.

  • Report a Problem Utility - Used to report any problems encountered while using the application.

Related Topics

For more information, reference the following guides that have been installed with VisionPro (the default path is: Program Files\Cognex\VisionPro\Doc\en\Hardware Manuals):

  • GigE Vision Cameras User Guide
  • CC24 Communication Card Hardware Manual
  • MVS-8600 Hardware Manual

Project Plugin Configurator


Project Plugin Configurator

The Project Plugin Configurator displays a list of all the plugins that are contained within the plugin directory, allows you to select compatible plugins, and loads them into a specific Designer project.

To access the Project Plugin Configurator, click the blue Utilities bar upon launch of the application.

To configure project plugins, click the Project Plugin Configurator button and do the following:

  1. Upon launch of the file explorer window, select the project (.cdp) file that you would like to configure plugins for, and click Open. This loads the all system plugins that the project is aware of into the Project Plugin Configurator.

  2. Select the compatible plugins you want to include in your project, and click OK. After you click OK, the file will be saved, and a backup will be created.

    If the plugin is unavailable, it means that it can't be loaded due to version compatibility issues. See How To... Plugins for more information.

  3. From the project launch page, open the project file that you want to work with. The plugins are now accessible within this project.

Unsupported Characters for Windows File Directories and Paths

Cognex Designer plug-ins and company names cannot include characters that are invalid for Windows file names or directory names and paths.

These characters include:

  • ASCII/Unicode characters 1 through 31
  • Quote (")
  • Less than (<)
  • Greater than (>)
  • Pipe (|)
  • Backspace (\b)
  • Null (\0)
  • Tab (\t)

Examples of invalid names include:

  • Company Name: Cog|nex<
  • Name: My "Final" LED


Project Editors

Project Editors are the primary editing windows for a given item in Cognex Designer, such as Alarms (Alarm Editor), Recipes (Recipe Editor), Task (Task Editor), Tags (Tag Manager) or Page (Page Editor), and even some devices may contain an editor.

Note: The Toolbox and Properties are common for all Project Editors, and display context sensitive information based upon the selected item, and the item/subject within the document selected. Some devices may also contain an editor; however, some device plug-ins may not include an editor.

Alarm Editor

Expression Builder

Page Editor

Precision IO Configuration Editor

Recipe Editor

Script Editor

Script Definition Editor

Task Editor

Tag Manager

Web Page Editor


Alarm Editor

The Alarm Editor is used for creating and editing alarms, and also includes the ability to import and export alarms to and from other projects.

Control | Description
Name | Specifies the name of the alarm; the name must be unique and only contain alphanumeric or underscore characters.
Description | Specifies additional information about the alarm.
Expression | Specifies the activation conditions for the alarm.
Auto Ack | Determines whether or not the alarm should be automatically acknowledged once it has been cleared.
Priority | Specifies the alarm's priority level (this is an optional setting).
Group | Specifies the group name in which the alarm resides (this is an optional setting).
Off Message | Specifies the message that the alarm displays when the Expression condition is false.
On Message | Specifies the message that the alarm displays when the Expression condition is true.


Expression Builder

The Expression Builder allows you to create simple expressions, which are normally used for binding Web Page elements (typically constructed in the Web Page Editor).

For example, in your application, you want to decide whether or not to display an image based on an "if" condition, which marks the threshold between a good or bad product. You can construct a simple expression for this using the Expression Builder Language Elements.

Note:
  • The Expression Builder dialog's label always marks the field being bound, and the data type for that field.
  • When starting, the "No binding" error message is present, by default.
Control | Description
Help | Displays the Cognex Designer User's Guide
Validate | Checks the validity of the expression.
Associations | Maps the expression's return type to the type required by the binding, e.g. a number to a color. Note: For more information, please see the Binding Associations topic.
Tag Selector | Launches the Tag Selector dialog, which displays the list of available tags.
Tag | Shows the list of available tags.
Constant | Shows the list of the available constant values.
Function | Shows the list of the available functions.
... | Shows the list of all functions, tags, and constants.
Result | It attempts to evaluate the expression and returns the resulting value. If there are errors, it provides quick feedback on possible syntax errors. This element is only visible (can be collapsed still) if the entered expression is invalid. If collapsed, the parser error is shown as a tooltip.

Expression Builder Features

Expression Builder Language Elements

Tag Selector


Expression Builder Features

Expression Builder has some built-in features that are intended to help you construct your expressions.

  • Syntax highlighting: To find errors easier, non-existing functions, identifiers and tags are highlighted with a red background (the error message is collapsed by default).

    The text editor also uses the same syntax highlight color scheme as the Script Editor. The text editor highlights the following language elements:

    • Operators
    • Constant values
    • String literals
    • Tag references
    • Function names

    • Comments

  • Auto-completion: The text editor provides an auto-completion function with IntelliSense-like features. Pressing Ctrl+Shift+Space or Ctrl+Space will search for relevant functions, constants, and tags.

  • Creating tags on-the-fly: Expression Builder does not allow you to save the expression if it is invalid. There is, however, one exception to this behavior; you can save the expression with invalid tag names. In this case, the (yet) nonexistent Tag is highlighted and you can create it later in Tag Manager.


Expression Builder Language Elements

Note:
  • The syntax is not case sensitive, however, it is highly recommended to use the casing presented in the auto-complete lists.
  • For common usage of Arithmetic and functions and Constants reference MS .NET / C# online documentation.
Language Element | Notes | Supported formats/values/examples
Arithmetic operators | (in order of precedence)
Exponentiation ^
Unary negation –
Multiplication and floating-point division *, /
Integer division \

Modulus arithmetic

(Returns the remainder after a number is divided by a divisor. The result always has the same sign as the divisor.)

 MOD
Addition (string concatenation) and subtraction +, –
Comparison operators

Equals (this works when comparing strings)

 =
Not Equal (this works when comparing strings) <>
Less Than <
Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Logical and bitwise operators

Negation

Note: The Negation (NOT) operator only supports logical operations, and does not support bitwise operations.
 NOT
Conjunction | AND
Inclusive disjunction | OR
Exclusive disjunction | XOR
Comment
Note: Since only syntactically valid expressions can be saved, there is the possibility to comment out sections for editing them later. If you want to comment out an expression, some dummy value can be provided before the comment, for example:
"1 // Math.Max(Math.Sin($myTag)*1, 12)"

// Comment

Constants
Note: For a list of all Constants, and a description of each, use the Constant button in Expression Builder and see the relevant tooltip.
Epsilon
False
NaN
NegativeInfinity
Null
PositiveInfinity
Pi
True
Functions
Note: For a list of all functions with descriptions, use the Function button in Expression Builder and see the relevant tooltip.
  • Math.Sin(pi)
  • String.Concat("a","b","c")
Parentheses
Note: [ ] and { } are not supported
2*(3+4)
Arrays

Arrays can be constructed using the ArrayOf and ListOf functions, and the ItemAt function can be used to access elements of an array.

Note:

When an "ItemAt($index, $array)" function is constructed in the Expression Builder, it will only update the returned value when the value of the "$index" tag changes, or a new array is assigned to the "$array" tag.

The following C# script statements illustrate how to trigger a value change event:

$index++;
$array = { "one", "two", "three" };

The following C# script statement will not trigger a value change event:

$array[1] = "new value";

The following example illustrates how to access elements of an array, using simple syntax:

ItemAt($tag_testInt, ListOf(0, 10, 20, 30, 40, 50))
// Place in the binding for the value of a Label
// Then by changing the value of the tag from 0 to 5, the value of the label will change from 0 to 500
String Literals

Supported escape sequence for strings:

 "sample Bob's name"
  • "Bell (alert): \a"
  • "Backspace: \b"
  • "Formfeed: \f"
  • "New line: \n"
  • "Carriage return: \r"
  • "Horizontal tab: \t"
  • "Vertical tab: \v"
  • "Single quotation mark: \'"
  • "Double quotation mark: \""
  • "Backslash: \\"
  • "Unicode char in hexadecimal notation: \u0020"
Tag Reference
  • $myTagName
  • $System.Users.CurrentUsername
White Space

Extra white space, if not part of a string, is ignored.

Operators do not need white space, but it may be useful for readability.

You may press <enter> and continue an equation on the next line.

You may not press <enter> and continue a string onto a second line.

The example below illustrates the valid use of multiple lines:

if($tag4,
"evaluated as true",
"evaluated as false")

//example:  invalid use of multiple lines
" this
string  cannot  be on two lines"


Tag Selector

The Tag Selector dialog is used to select tags within the project. The dialog is launched from the Expression Builder dialog by pressing the Tag Selector button, or right-clicking a block pin and selecting Assign to Tag. When the dialog is launched, it populates the list of tags is filtered based on the selected type when it was launched. Check the Show All Types checkbox to view all of the available tags.

You can select a tag by double clicking or selecting a tag and then clicking the Accept button.


Page Editor

The Page Editor is a modern WYSIWYG user interface (UI) editor used to create a Page, an interactive HMI UI for vision applications. Most of the properties of the User Controls can be bound to Tags, or incorporate expressions with the Expression Builder, to ensure fast and effective HMI UI building.

Note: More information on how to develop an HMI UI with the Page Editor can be found under the Pages section.

  • The Page Toolbox contains a tree of HMI UI User Controls which can be dragged and dropped onto the Page.
  • The Properties window will populate with the selected control's properties.
    Note: The properties of the Button user control contain the Click Command option. Since you can also assign a custom script to a button being clicked, bear in mind that in this case both commands will be executed.

Page Editor Navigation

Page Editor Keyboard Shortcuts

Page Editor Position Control


Page Editor Navigation

Navigation is located in the top right hand corner is the pan & zoom control. Pressing the arrow keys will pan the editor, and the slider will affect the zoom.

The HMI builder can also be navigated in the following ways:

  • Left Click - Select
  • Right Click - Context Menu
  • Right Click + Drag - Pan
  • Shift + Left Click + Drag - Group Select
  • Shift + Right Click + Drag - Force Pan
  • Ctrl + Mouse Wheel - Zoom in/out


Page Editor Keyboard Shortcuts

The HMI Builder has the following keyboard shortcuts:

  • Ctrl + C - Copy
  • Ctrl + X - Cut
  • Ctrl + V - Paste
  • Ctrl + Z - Undo
  • Ctrl + Y - Redo
  • Ctrl + R - Replace Tags


Page Editor Position Control

Located in the bottom right-hand corner of the Page Editor, position and size values (pixel coordinates) of the most recently selected control are displayed. These values can also be manually adjusted by the developer.


Precision IO Configuration Editor

The Precision IO Configuration Editor is used to configure the input/output lines for the Cognex Communication Card (both a physical or simulated card) in a Task. Once a card is connected, the Precision IO Configuration can be launched by either double-clicking on the device or right-clicking the device and selecting Precision IO Configuration from the context menu (this option only exists for physical cards).

Note: The Precision IO Configuration can also be used with a disconnected, physical card, but not with a simulated card.

This editor is used to setup the event causes and responses, as well as the I/O host notification script. The editor's input, output and line numbers are populated by the specified communication card, therefore the connected or disconnected card will change the behavior of the editor. If a card is disconnected, all of the available input and output banks for that card model will be present, even if, when connected, they would not be available.

Adding and Configuring Events


Recipe Editor

The Recipe Editor is used to create and build recipes. Tags can be added to the Tag Name column by manually typing in the name of the tag, or dragging and dropping tags from the Tag Browser. The Value column displays the current value associated with the tag.

Note:
  • Read-only tags are not supported in recipes.
  • The tag value displayed in the Recipe Editor is its current value, and does not correlate to the value of the tag in the recipe or recipe configuration.
  • See the Recipes topic for more information on adding, editing and using recipes.

  • The Recipes drop-down menu is where you can select the recipe you wish to edit.

  • The Add button launches the Add New Recipe dialog, where you create a new recipe and define its name.

  • The Remove button deletes the selected recipe.


Script Editor

The Script Editor is used to edit scripts. Cognex Designer provides a powerful scripting environment using Microsoft C# .NET. You can write standard C# .NET code and have it execute within the Cognex Designer environment.

The Toolbox is similar to the Tag Browser, but contains $ Functions, as well as Tags. You can drag and drop items from here into the script in order to use it.

The Properties window contains a list of the Using statements being used by the code (see the Calling External Code and Using Statements topic for more information), and a link to the Script Reference dialog (see the Adding References topic for more information), which lists all the libraries and DLLs that the script is currently referencing, and can reference.

  • Saves the current script, so long as there are no errors.
  • Deletes the current script. Prompts for confirmation before removing.
  • / [image] (lower left-hand corner of the editor window) Indicates whether or not the script was correctly formatted or not, after the script has been compiled.
Note: For more details on how to develop with the Script Editor, see the Scripting topic.

Script Editor Keyboard Shortcuts


Script Editor Keyboard Shortcuts

While editing code in the Script Editor, the following keyboard shortcuts are available:

  • Ctrl + F = Opens the Find tab of the Find/Replace dialog:

  • Ctrl + H = Opens the Replace tab of the Find/Replace dialog:


Script Definition Editor

The Script Definition Editor is used to define the input and output arguments of scripts.

  1. Press the Add or Remove buttons to adjust script arguments.
  2. Enter a name for the argument, and then use the Data Type Selector to configure the type of data that will define the argument.
  3. If the script will return a data type, check the Return Type checkbox, and then use the Data Type Selector to configure the type of data to be returned by the script.

Data Type Selector


Data Type Selector

The Type Selector control is used when selecting a Data Type. The control can be used to search for a data type by selecting from the pre-populated drop-down list, by name (by typing in the textbox), or pressing the ... button to launch the Complex Type Selector dialog (which allows the creation of arrays). Select the desired data type from the drop-down list.

  • When the search field is empty, the drop-down list will be auto-populated with the most common data types, as well as the most recently used data types:

  • When using the search field by typing in a data type's name, it will list the corresponding data types:

  • To search by namespace, as well, when typing, add a "." character to the search:

Complex Type Selector


Complex Type Selector

The Complex Type Selector dialog is used to create data type arrays and/or generic data types.

Note:
  • Press the Browse Assembly button to add project level assembly references. For more information, see the External Assemblies topic.
  • If a tag is constructed from an externally referenced assembly, and the data type of the external assembly is modified (e.g a referenced assembly contained a data type called "TypeA" which was used as a data type for a tag, and then TypeA is renamed), an error will appear in the Output window, and the Tag Manager will display the tag without a Data Type.

  1. To search for a data type, type the text of the name in the Filter text box; the search will look for namespaces and data types without having to enter a "." character.

  2. Once you have selected the desired data type, the Accept button will be enabled.

Creating an Array with the Complex Type Selector Dialog

Creating Generic Data Types with the Complex Type Selector Dialog


Creating an Array with the Complex Type Selector Dialog

The Complex Type Selector dialog allows you to create multi-dimensional data arrays, such as an array of integers or an array of blobs.

  1. To make an array, check the Make Array Type checkbox.

  2. Then define the size of the array by adjusting the Dimension parameter.

  3. The Selected Type caption will display the array configuration.


Creating Generic Data Types with the Complex Type Selector Dialog

Using the Complex Type Selector dialog, you can also create .NET generic data types. For example, you can create a System.Collections.Generic.List<T> or a System.Collection.Generic.Dictionary<TKey,TValue> type.

  1. To create a generic data type, in the Filter textbox, enter a string that matches the C# generic parameter declaration.
  2. Once the desired generic data type is listed, select it to enable the configuration of the accompanying Generic Parameters.

  3. The Generic Parameters are defined using the Data Type Selector.

Note:

Nested data types can be created by pressing the ... button to launch another Complex Type Selector dialog. The example below shows a multiple nested data type.


Task Editor

The Task Editor is used to construct a Task, and is the primary workspace for developing image processing operations. These operations can then be organized in a flow diagram, and data can be linked between the different devices, tools and operations. Blocks and structures are arranged by the user and executed based on their position in the diagram (executing from the left to right of the diagram).

Note: The Task Editor for a Sub Task block is nearly identical, but it contains the [image] Parent Editor button, which will return you to the Task in which the Sub Task is contained.
  • The Toolbox contains a tree of available blocks (encapsulated code with simplified input and output pins) which can be dragged and dropped onto the Task.
  • The Properties window populates with the selected block's configurable properties.
Note: See Task for more information on the Run button functionality.

Task Editor Navigation

Task Editor Keyboard Shortcuts


Task Editor Navigation

The Task Editor can be navigated in the following ways:

  • Left Click = Select
  • Left Click + Drag = Group Select
  • Right Click = Context Menu
  • Right Click + Drag = Pan
  • Mouse Wheel = Zoom In/Out

  • Shift + Right Click + Drag = Force Pan


Task Editor Keyboard Shortcuts

The Task Editor has the following keyboard shortcuts:

  • Ctrl + C = Copy
  • Ctrl + X = Cut
  • Ctrl + V = Paste


Tag Manager

The Tag Manager is used to add, edit and remove tags in a project. Each row in the table contains a Cognex Designer tag.

Property | Description
Name | Specifies a unique name to identify the tag. The tag name must be unique, and may only contain alphanumeric or underscore characters. Can contain '.' but cannot start or end with it.
Comment | A text field where the user can enter additional information about the tag.
Data Type | Specifies the data type of the tag, using the Data Type Selector. Note: Tags can also contain an array of data, such as an array of integers or an array of blobs. These types of tags can be created by pressing the ... button to launch the Complex Type Selector dialog. For more information about creating an array data type for a tag, see the Creating an Array with the Complex Type Selector Dialog topic.
Value | Specifies the initial default value/setting of the tag.
R/O | Specifies whether or not the tag value is Read only.
Selected Path (Optional) | Specifies the device path where the data should be loaded. Note: See Selected Path for more details.
Persistent | Specifies whether or not the tag value should be saved on shutdown, and reloaded when the application starts up again.

Tags


Web Page Editor

The Web Page Editor is a WYSIWYG user interface (UI) editor used to create a WebPage, an interactive HMI UI for vision applications.

Note: More information on how to develop an HMI UI with the Web Page Editor can be found under the Web Pages section.

  • The Web Page Toolbox contains a tree of HMI UI elements which can be dragged and dropped onto the Web Page.

    Multiple elements on the Web Page can be selected by using pressing the Ctrl key and selecting the elements, or clicking on an empty area of the Web Page and dragging the mouse over the desired elements.

  • The Properties window will populate with the selected element's properties.

    Most of the Properties of the elements can be bound to Tags, or incorporated into expressions with the Expression Builder, which allows the values of the Properties to be "bound" so that the values will be updated in "real-time" when the project is in deployed mode.

    Note: For more information about bindings, see the Binding Properties topic.

Web Page Editor Keyboard Shortcuts

Web Page Editor Navigation


Web Page Editor Keyboard Shortcuts

The Web Page Editor has the following keyboard shortcuts:

  • Ctrl + C = Copy
  • Ctrl + X = Cut
  • Ctrl + V = Paste
  • Ctrl + Z = Undo
  • Ctrl + Y = Redo
  • Ctrl + R = Replace Tags
Note: If the Web Page Editor tab is undocked, the keyboard shortcuts will not operate, and you will need to use the right-click menu.


Web Page Editor Navigation

The following can be used to navigate within the Web Page Editor:

  • Left Click = Select
  • Left Click + Drag = Group Select
  • Right Click = Context Menu
  • Right Click + Drag = Pan (aka Scroll)
  • Mouse Wheel = Zoom In/Out
  • Shift + Right Click + Drag = Force Pan
Note:

  • In addition, the editor can be undocked and dragged out of the Cognex Designer IDE and moved to a new window (i.e. become a separate, floating window). Simply click the title of the tab and drag to a desired location. To reattach the undocked editor to a particular part of the Cognex Designer IDE, while dragging the editor, choose one of the five docking options. The middle option will restore the undocked editor to the tabbed order.

  • If the Web Page Editor is undocked, the Properties of any elements on the Web Page will be uneditable.
  • If the Web Page Editor tab is undocked, the keyboard shortcuts will not operate, and you will need to use the right-click menu.


Quick Navigate

Cognex Designer provides advanced search functionality to allow you to navigate large applications easily. The quick search is located in the top-left corner of the Cognex Designer Integrated Development Environment, and this field provides quick access to all objects within the application. When you type a script, page, HMI element or tag, Cognex Designer will either navigate directly to the object, or open the Search window to search for tag references.


Project Windows

Useful tools are hosted in a series of dockable windows, which allows you to freely arrange the development environment.

Note:

If you ever need to reset the environment to its default, you can do it in Tools | Options | Workspace.

Search

Tag Browser

Template Browser

Toolbox


Search

The Search tool window allows you to a search for usages of a given string inside scripts, property bindings and tags. This is a more complete search than that Quick Navigate, which only identifies tags.

The screen capture below shows an example as if someone searched for 'image', double clicked the second item, which opened the OnStartup script and highlighted the line with the text match.

Field | Description
Item | Denotes the text matched.
Source | Is the object (Script/Page/User Control) the contains the text.
Details | Contains more information about where the text was found.


Tag Browser

The Tag Browser window displays all of the tags currently registered in Cognex Designer. To display the Tag Browser window, navigate to View > Tag Browser. The Filter text box can be used to help quickly locate the desired tag.

Fields | Description
Address | Specifies the tag's unique name.
Value | The current value of the tag.
Data Type | The tag's data type.
R/O | Specifies whether or not the tag value is Read only.
Comment | Any additional information about the tag.


Template Browser

The Template Browser allows you to access all your own and imported template files from your user libraries. You can find it at View | Template Browser. To learn more about user templates, see the Templates topic.

  • The Template Browser lists your template files in a hierarchical manner and allows you to import any file with a right-click or by drag-and-drop (see Importing Items topic).

    You can search and filter your templates in the Filter section.

    • The type of each template is displayed in brackets.
    • A Tooltip is displayed, but only if the template has the value set.
    • A description is displayed in the grey region.
    • You can move templates to and from different folders, create new folders, rename and delete templates and folders.
    • Filter by the type of Template from the drop down box.

  • You can add new template directories to the default one in Tools | Options. By default, the Template Browser lists the files from %MyDocuments%\Cognex Designer\Templates.


Toolbox

The Toolbox is a context-sensitive utility of both the Page Editor, Recipe Editor, Script Editor and Task Editor, and populates tools based on which editor is selected. Drag-and-drop items from the Toolbox into their respective editors.


Project Diagnostics

The Diagnostics area provides feedback on the different components of your project, indicating errors and proactively searching for them, as well as monitoring tag values, outputs and data transfers.

Error Viewer

Output

Project Verification

Watch List

Communications Monitor


Error Viewer

Errors

The Errors window displays any script compilation errors present in the project. To display the Errors window, navigate to View > Errors, and the Errors window will be displayed below the Project Explorer.

Field | Description
Source | The full name of the script where the error originated from.
Description | The compiler's error message.
Category | Category of the error (this is most likely to be 'Scripts').
Note: Double-clicking on a line will take you to the line in error.


Output

The Output window shows the recent history of application messages; users may also write to the Output window through a script (for example, a JavaScipt console.log() function).

To display the Output window, navigate to View > Output, and the Output window will be displayed below the Project Explorer.

Field | Description
Timestamp | When the message was created.
Level | The severity level of the message.
Message | The details of the message.


Project Verification

The Project Verification window allows users to run a check on the application to search for possible errors. To display the Project Verification window, navigate to Project > Verify, and the Project Verification window will be displayed at the bottom of the Cognex Designer UI.

Press the Find Errors button to update the list of verification errors/warnings. Double-clicking on an item takes you to the error.

Field | Description
Category | The type of verification error, which provides a clue to where the error is located.
Description | Contains more information about where the error text was found.
Source | The object (Script/Page/User Control) that contains the error or warning.


Watch List

Watch

The Watch window allows users to monitor any tag in the application and modify tag values, while the application is running, without having to make changes to the HMI Pages.

To display the Watch window, navigate to Tools > Watch list.

Note: To modify tag values, they must be configured as Read/Write.
Field | Description
Name | The unique name of the tag. Tip: You can begin typing in the name of the tag, and it will auto-complete.
Value | The tag's value.


Communications Monitor

The Communications Monitor is used to monitor how often Designer is reading and writing to external Devices, and is particularly useful when the Devices are GigE cameras.

For example, two GigE camera variables could be configured as tags, in the Tag Manager.

The tags' Update Rate Properties are specified (the default is 1000 msec).

When the project enters Test Mode, the Communications Monitor will display a row for each tag, with information on the number of reads and writes to the Device.


Developing a Cognex Designer Project

This section covers how to use the development environment of Cognex Designer to create a machine vision application, and the topics provide information about the functional areas of Designer.

Note: For more information about the Cognex Designer development environment, see the Cognex Designer Integrated Development Environment topics.

Cognex Designer is used to solve complex machine vision applications by breaking down the development of the application into functional areas. Developing a project in Designer involves the following:

  1. Add the Cameras and Communications Devices that will provide the data for your application.

    • From the Project Explorer, add and connect the Devices for your project.

  2. Tasks are added to process the data, and are configured in a Task. This is the area of the application where you will define the vision processing capabilities, and the inputs and outputs to the system:

    • Task Blocks execute from left to right, and provide results for other blocks. Connect all of the functional blocks by connecting their input and output pins.
    • Layout the blocks, using Groupsand Parallel Regions to structure the execution order.

  3. Define the flow of data:

    • Utilize the Tag Manager to exchange information and data throughout the application. Tags will automatically route the data from Tasks to a Page, a Database and/or I/O, for example.
    • Using the Scripting tools, create custom scripts to interact with the data and tools in the project.
    • Use Recipes to save and utilize tags for different settings and configurations of your application.
    • Create Databases for storing data from the project.
    • Configure Users and their access to the project.
    • Add Alarms to notify you when there is a problem with the project.
    • Use Components to monitor the project.

  4. Create the Human-Machine Interface (HMI) for operator interaction with the application during runtime. This is done using Pages, which are used to convey the produced data for operator interaction.

    • Design the HMI interface using User Controls, Graphics, Media and Vision elements.
  5. Put your project in Test Mode to ensure that everything is functioning properly.
  6. Deploy the Designer project to your application. See the Deploying a Cognex Designer Project for more information.

System

Recipes

Tasks

Web Pages

Pages

Scripting

Components

Devices

Databases

Templates

Project Maintenance

Test Mode


System

The System category of the Project Explorer contains options for adding and configuring Alarms, Recipes and Resources, as well as managing the project, tags and users.

Alarms

Localization

Resources

Project Settings

Tags

Tag Manager

Users


Alarms

Alarms are used to alert users to problems within an application, and are managed using the Alarm Editor.

Alarms are setup by defining a condition that causes an alarm (i.e. a Device is disconnected). An alarm can have one of four states:

  • Inactive: The alarm condition is not active.
  • Unacknowledged: The alarm condition is active but not acknowledged
  • Acknowledged: The alarm condition is active and acknowledged
  • Restored: The alarm condition is not active and not acknowledged.

The state of an alarm will usually change in the following order:

Inactive > Unacknowledged > Acknowledged > Inactive

or

Inactive > Unacknowledged > Restored > Inactive

Adding Alarms

Import and Export Alarms

Acknowledging an Alarm

Displaying Alarms

Monitoring Alarm Changes


Adding Alarms

To add a new alarm, within the Alarm Editor, simply start typing the name of the alarm into the empty row at the bottom of the table. Alternatively, click the Copy button, which creates a copy of the selected alarm and its properties.

Note: The expression must evaluate to a Boolean value; the alarm will be active when the expression evaluates to true.
Tip: Pressing the Plus button will automatically scroll to the bottom of the table and allows immediate typing.


Import and Export Alarms

Cognex Designer supports importing and exporting the alarm list to a CSV file. This alarm list can be edited quickly in a program like Microsoft Excel and then imported back into Cognex Designer. This can be used as a way to very quickly generate and modify existing application alarms.

Note: More information on how to develop with the Alarms Manager can be found under the Alarms section.


Acknowledging an Alarm

The Alarm Editor provides a set of functions that can be used to interact with the Alarms. To acknowledge an Alarm, the Acknowledge function must be called from a script.

Note: For more information about creating the script, please see Monitoring Alarm Changes.

An alarm can be acknowledged individually or by acknowledging all alarms at once.

$System.Alarms.Acknowledge(Alarm1);

or

$System.Alarms.AcknowledgeAll();


Displaying Alarms

Alarms are typically displayed on a Page, using a Table User Controls, that lists the currently active alarms.

  1. To display a list of alarms in a Table, go to the Table's Properties and set the Source parameter to either:

    • System.Alarms.Active: Displays a list of alarms that are currently active.
    • System.Alarms.All: Displays a list of all the configured alarms.

  2. Once selected, the Table will be auto-configured with all of the available columns for the selected type. These columns can be edited by clicking the Columns parameter '...' button.


Monitoring Alarm Changes

Alarm states can be monitored using the Alarm State Changed script.

An alarm can be in four different states:

  • Inactive (0): The condition is false, and has been acknowledged.
  • Unacknowledged (1): The condition is true, and not acknowledged.
  • Acknowledged (2): The condition is true and acknowledged
  • Restored (3): The condition is false, and not acknowledged.
Control | Description
Alarms.AlarmsActive | At least one alarm is currently active (its condition is set to true).
Alarms.AlarmsUnacknowledged | At least one alarm has not been acknowledged.
Alarms.Acknowledge(alarmName) | Acknowledges the alarm matching the given name.
Alarms.AcknowledgeAll() | Acknowledges all alarms.

The following script logs the state change:

public static void AlarmStateChanged(System.DateTime time, string name, string description, string group, int priority, int state, string message)
{
    //If a new alarm occurs display the new alarm warning (only when the alarm turns on)

    if (state==1)
    {
        $Alarms_NewAlarm = true;
    }

    //Write the new alarm or an alarm reset to the event log (i.e. when an alarm turns on or off, but not an acknowledge event)

    if (state==0 || state==1)
    {
        $Databases.MyData.MyTable.AddRow(DateTime.Now, description + "-->" + message, priority, group);
    }
}


Project Localization

Use the Localization pane in the Project Editor to create projects supporting multiple languages.

To display the Localization pane, in the Project Explorer, double-click System > Localization. The Localization pane opens. Each Tag Name is defined with a Default String value and associated Translation.

Change Language at Runtime.

Add a Language

Remove a Language

Rename a Language

Import Translations Into a Project

Export Translations to a CSV File

Edit Tag Names

Edit Default Strings

Edit String Translation Values


Change Language at Runtime.

Change Language at Runtime by Creating a Project Localization Page

By creating a Project Localization page, you can change between languages at runtime. This is helpful as you switch languages while deploying to multiple locales.

  • You can perform advanced tasks with the same methods and properties by using Change Languages at Runtime Using the API.

    • To customize a page, open your project and do the following:

    1. Create a new page using the Page Editor.
    2. Add a ListBox from the Toolboxto the page you created.
      1. Drag a Listbox from the Toolbox and Page Editor.
      2. Using the Properties pane, invoke theExpression Builder ( [image]) to Binding Properties Localization.Languages to the listbox.
      3. Click OK. The list box is now customized to accept the language value the user selects.
    3. Add a button and assign a Button Click Command - WebPages.
      1. Drag a Button from the Toolbox and add it to the page you created.
      2. Using the Properties pane, Binding Properties Localization.LoadLanguage to the button's Click Command. The languageName drop-down box appears below the Click Command drop-down box.
      3. Invoke the Expression Builder to Binding Properties Pages.Page.ListBox.SelectedValue to languageName.
      4. Click OK.
    4. On the page, label the Button Load, or use another meaningful string.
    5. Test the page you created by putting the project in test mode. Click Project > Start Test Mode.
    6. To change between languages from a Page or WebPage, use the Project Localization page you created.
      1. Select the language you want displayed at runtime from the Select Language drop-down (listbox) you created.
      2. Click the Load Button you created to load the desired language at runtime.

    Localization Using the API


Localization Using the API

Change Languages at Runtime Using the API

To change languages displayed at runtime with the API, use the associated localization methods described in the table below.

To change a language at runtime using the GUI, see Change Language at Runtime by Creating a Project Localization Page.

Function Description Input(s) Output(s)
$Localization.LoadLanguage()

Changes the selected language at runtime to the language specified by the input. If the language is successfully loaded, it updates the value of $Localization.CurrentLanguage to the loaded language.

Throws an exception if the input languageName is invalid.

If the loaded language doesn't have a translation available, the translation reverts to using the default language

 string languageName void
$Localization.CurrentLanguage

Gets the currently loaded language at runtime.

This tag is read-only.

 None string

Using API Calls to Access Localization Methods

Do the following before making these sample API calls to test localization functionality.

  1. In the Project Explorer GUI, open the Localization pane by double-clicking System > Localization.
  2. Using the Tag Manager, create a tag named $Localization.Greeting.
  3. Add a Language named French.
  4. Using the Project Localization, edit the Default String and Translation values as appropriate.
  5. Create your program and use the example API calls coded below as neccessary in your application.

// Display localization tag on UI

$HMI.ShowMessage($Localization.Greeting);

// $Localization.Greeting has a default value of "Hello"

// Popup message saying "Hello" will appear

// Load another language

$Localization.LoadLanguage("French");

// Display localization tag on UI again

$HMI.ShowMessage($Localization.Greeting);

// $Localization.Greeting has a translation in French "Bonjour"

// Popup message saying "Bonjour" will appear


Add Language

Add a Language

Do the following to add a localization language.

Before adding, ensure your Designer Project is not in Test Mode.

  1. Open a project if you haven't already.
  2. Project Localization
  3. Click the Add new language icon on the Localization Pane Toolbar.
  4. In the Add New Language dialog, enter the name of the language you want to add.
  5. Click Accept.

Your localization language is added successfully and will be available in:

  • The Rename a Language dialog.
  • The list of languages returned by the API call.
  • The available languages in the Export Localized String dialog. See Export Translations to a CSV File.


Remove a Language

Do the following to remove localization languages.

Before removing, ensure your Designer Project is not in Test Mode and at least one localization language has been added.

  1. Open a project if you haven't already.
  2. Project Localization
  3. Click the Delete a language icon on the Localization Pane Toolbar.
  4. In the Remove Language dialog, select the languages you want to remove.
  5. Click Remove.

The selected localization languages are removed and:

  • All translations belonging to the removed language will be deleted.
  • The removed language will not be available in language drop-down boxes.
  • The removed language will not be returned by API calls.
  • The removed language will not be an available option when exporting translations.


Rename a Language

Do the following to rename a localization language. You can rename multiple languages at one time before clicking OK.

Before renaming, ensure your Designer Project is not in Test Mode and at least one localization language has been added.

  1. Open a project if you haven't already.
  2. Project Localization
  3. Click the Rename languages icon on the Localization Pane Toolbar.
  4. Select the language you want to rename, highlighting the entire row.
  5. Double-click the language you want to rename in the Edit Name field. The language name you want to replace is highlighted.
  6. In the Edit Name field, type the new name of the language.
  7. Click OK to confirm renaming of language(s).

For successfully renamed localization languages:

  • Each corresponding CSV file in the Languages folder is renamed accordingly.
  • The list of available languages uses the new language names.


Import Translations Into a Project

Do the following to import existing translations using a .csv file into a Designer project.

  1. Before importing, ensure the following is true:
    • You have a comma-delimited file (.csv file) that follows this format:
      • First Row
        • Tag Name
        • Default String
        • Translation
      • Each succeeding row contains the values of the headings in the first row, for each tag. For example,
        • Tag name, such as Greeting
        • Default String, such as Hello!
        • Translation, such as Hola!

      For example:

      Tag Name | Default String | Translation
      Greeting Hello!

      Hola!

      FirstNumber | One | Uno
      SecondNumber | Two | Dos
      ThirdNumber | Three | Tres
    • Your Designer Project is not in Test Mode.
  2. Import translation languages by doing the following:
    1. Open a project if you haven't already.
    2. Project Localization
    3. Click the Import translations icon on the Localization Pane Toolbar.
    4. Select the .csv file that contain the translations you want to import and click Open.
    Note: Consider the following when importing translations.
    • If an imported language doesn't exist in the project, then the imported language will be created using the filename of the imported .csv file.

    • If an imported tag already exists in the project and its default string conflicts with the existing project default string for that localization tag, the user will be prompted regarding whether to overwrite during the import process.

    • If an imported tag doesn't exist in the project, it will be automatically created.

    • If the imported language already exists in the project, the user will be prompted to confirm overwrite or cancel of the import process.

      Multiple translation languages can be imported at one time by selecting multiple .csv files.


Export Translations from a CSV File

Export Translations to a CSV File

Do the following to export existing translations to a .csv (comma delimited) file.

  1. Before exporting, ensure the following is true:
    • You have at least one localized string to export.
    • Your Designer Project is not in Test Mode.
  2. Export translation languages by doing the following:
    1. Open a project if you haven't already.
    2. Project Localization
    3. Click the Export translations icon on the Localization Pane Toolbar.
    4. Select the languages that will be exported.

    5. Specify the Export Directory the file(s) will be exported to by using the browse button or the provided textbox. If any conflicting exported files already exist in the chosen export directory, the user will be prompted to confirm an overwrite.

    6. Click Export.

Successfully exported translation languages will be available as CSV files with the following naming format:: project_name.language.csv. For example, for a Designer project named Localization, an English translation would be exported as Localization.English.csv.


Edit Localization Tag Names

Edit Tag Names

Do the following to edit tag names.

Before editing tag names, ensure your Designer Project is not in Test Mode and at least one localized string exists.

  1. Open a project if you haven't already.
  2. Project Localization
  3. Within the Tag Name column, double-click the string you want to edit.

    4. Project Localization

  4. Press ENTER.

The localization tag name is added or updated and

  • Edited text appears in deployed applications and in development deployed mode.
  • Any bindings set to the edited localization tags are updated.


Edit Default Strings

Do the following to edit default strings

Before editing default strings, ensure your Designer Project is not in Test Mode and at least one localized string exists.

  1. Open a project if you haven't already.
  2. Project Localization
  3. Within the Default String column, double-click the string you want to edit.
  4. Edit the default string name, replacing it with your desired default string name.
  5. Press ENTER.

The default string is updated and

  • Edited strings appear in deployed applications and in development deployed mode.
  • Any bindings set to the edited string are updated.


Edit Translations

Edit String Translation Values

Do the following to edit string translation values.

Before editing, ensure your Designer Project is not in Test Mode and at least one localized language exists.

  1. Open a project if you haven't already.
  2. Project Localization
  3. Select the language to be translated, highlighting the entire row in the Localization Pane..
  4. Double-click the string you want to edit in the Translation column.
  5. Edit the string translation with your desired value.
  6. Press ENTER.

The string translation value is updated and edited text appears in deployed applications and in development deployed mode for the translated language


Resources

Cognex Designer supports loading images and videos into the project as resources. These resources are stored with the project and can be accessed by Page elements in the application.

  1. To access the Resource Editor, double-click the Resources node under System in the Project Explorer.

  2. To add a resource, simply click the Import button and then browse to the file you want to use.

  3. Once selected, this file will be added to the list of application resources and available for use.

Using the Resource


Using the Resource

  1. In order to use the image or video resource, add an Image or Video Player control (Media group) to the Page.
  2. In the property grid for the control, you will be able to select the resource from a drop down list.

  3. Once selected, the Image or Video Player control will display the selected resource.


Project Settings

The Project Settings dialog is used to setup configuration options for your project.

Audit Trail

Deployment

External Assemblies

General

Scripts

Tasks

Project Component Password Protection

Web HMI Settings


Audit Trail

The Audit Trail settings are used when configuring your project to be compatible with an audit trail.

For more information on configuring and setting up an audit trail, see the How To... Audit Trail topics.


Deployment

The Deployment tab is used to configure the location of the folder where the deployed project will be located, whether or not to scale the deployed UI, whether or not the deployed UI can be minimized, and whether or not to overwrite the deployment folders.

Note: For more information, see the Deploying a Cognex Designer Project and Deployment Options topics.


External Assemblies

The External Assemblies tab allows you to add project level custom or 3rd party DLL/.NET assembly references to your project. This will allow the data types in external DLL files to be used while configuring and selecting a script reference or tag data type, for instance.

Pressing the Plus button will launch an Open File dialog, where you can browse for a .NET DLL.

To remove a previously loaded .NET DLL, select the assembly and then press the Delete button.

Press the Apply or OK buttons to commit your changes.

Note:
  • When an assembly that will be used in a Script is added via the External Assemblies tab, you will need to use the Script Reference dialog to select the assembly from the Discovered assemblies list and double-click the assembly to add it as a script reference. For more information about using the Script Reference dialog, see the Adding References topic.
  • The location of externally referenced assemblies must be in the same location for both development and deployed projects. Otherwise, an error message will be launched at startup, and the assembly will need to be located. Saving a project that contains invalid assembly references may cause the project to be corrupted and data may be lost.


General

The General tab allows you to apply a password for the project, and displays the name and version of the current project. If configuring a password for the project, it will prompt the user to enter the defined password before the project can be opened (the project must be saved before the password will take effect).

The Project Name and Project Version defines the name and version applied to the deployed project.

Note: For more information about deployment, please see the Deploying a Cognex Designer Project topics.


Scripts

The Scripts tab is used to declare project level DLL references and Using statements that apply to all of scripts in the current project. This is useful when several scripts use the same DLLs and Using statements, saving the need to reference each DLL for each individual script.

Press the Edit button to launch the Script References dialog, where you can add assembly references to your project.

Press the Plus button to launch the Add Default Namespaces dialog, where you can enter project Using statements.

Note:
  • After adding a reference to an assembly using the Script References dialog, and pressing the Accept button in that dialog, you must press the OK or Apply button in the Project Settings dialog to store the changes in the project.
  • For more information about adding references and Using statements, see the Adding References and Calling External Code and Using Statements topics.


Tasks

The Tasks tab is used to configure the memory management properties of the project.

Note: For more information, see the Memory Management topic.

Memory Management


Memory Management

Cognex Designer is built on Microsoft's .NET framework, which manages the memory of the application. However, most imaging libraries use unmanaged code, and hence some manual memory management is often required. A "cleanup/collect" must be performed every so often to prevent memory exceptions, and keep the system running smoothly.

Note: See the Garbage Collection (GC) Options topic for more information about implementing a GC strategy for your Designer application.

Setting Description
GC Frequency

This value specifies the number of times a Task (or multiple Tasks) has been run before garbage collection (GC) is performed. For example, if a project has a single Task, and the GC Frequency is set to 5, GC.Collect will be performed after a Task has been run five times. If a project has multiple Tasks, Task A and Task B, and GC Frequency is set to 5, after Task A has been run three times, and Task B has run twice, GC will be performed.
Dynamic Garbage Collection

Automated GC. When enabled, GC is performed based on the actual memory usage of the application and two configuration values:

  • Low Memory Use Threshold: If the application uses less memory than this level, no GC is performed. By default, this value is 50% of available physical memory.
  • High Memory Use Threshold: If the application uses more memory than this level, full GC is performed. By default, this value is 75% of available physical memory.

Between these two levels only newly created (Generation 0) objects are collected to provide maximum performance. Both levels are configured as a percentage of total physical memory and actual values are calculated upon application start. The total physical memory is considered to be 2 gigabytes on 32 bit systems, as this is the maximum amount a single process can access.

Increasing these levels might improve application performance at the cost of mean and peak memory use.

Note:
  • For more information on .Net GC and GC generations, please refer to this Microsoft topic.

  • Due to Designer controlling GC, if a CogToolBlock is going to be imported into a Designer project, ensure that the GC is disabled prior to being imported, because it cannot be disabled in Designer.

  • VisionPro only reports the time taken for a cleanup in the parent Tool/ ToolBlock, so if the cleanup occurs in the root ToolBlock, the time taken to execute the cleanup will not appear in the ToolBlock's RunStatus.TotalTime property.

Garbage Collection (GC) Options


Garbage Collection (GC) Options

There are essentially three different options for memory management in Designer: Simple Collection, Dynamic Collection and Manual Collection.

Note:

  • GC will take longer when Designer is in development mode, because there are more resources to check (the Designer application itself, and your project). Therefore, you should deploy your project before attempting any performance diagnostics related to GC. For example:

    • Designer and a single Task (no GC) = ~27ms
    • Designer and a single Task (with GC) = ~85ms
    • Deployed project with a single Task (with GC) = ~35ms
  • Automatic collection may occur if the .NET Framework deems that the scheduled GC is not sufficient, regardless of the collection strategy.

  • Simple Collection

    The simple collection strategy provides smoother, more reliable times than the dynamic collection strategy, and is suited to most normal applications. This strategy triggers a full GC, based on the GC Frequency setting (5, by default). A full GC may take awhile, because it scans every single object in the application to determine if any other object is still using it. Cognex recommends using this strategy by default, and only use the others, if required.

    To implement this strategy, simply set the GC Frequency setting to 5 (or whichever value best suits the needs of your application), and uncheck the Dynamic Garbage Collection checkbox.

  • Dynamic Collection

    The next strategy, dynamic, takes into account the amount of RAM usage before determining whether or not to do a full GC. With this strategy, if the current RAM utilization is below the Low Memory Use Threshold value, a general level-0 collection will be performed; if the RAM utilization is between the Low Memory Use Threshold and High Memory Use Threshold values, a general level-1 collection will be performed; and if the RAM utilization is above the High Memory Use Threshold value, a full, level-2 collection will be performed.

    The advantage of this strategy is that the program's throughput is higher until a full level 2 collection must be performed, at which point there will be a major performance hit.

    To implement this strategy, set the GC Frequency setting to 5 (or whichever value best suits the needs of your application), check the Dynamic Garbage Collection checkbox, and set the Low Memory Use Threshold and High Memory Use Threshold values.

  • Manual Collection

    This option should only be used by advanced users, and entails manually calling GC.Collect from a script, at the appropriate time. To implement this strategy, set the GC Frequency setting to 0, which will disable Designer's GC.

    Note:

    If GC.Collect is not called regularly enough, the built-in .NET GC will be performed automatically.

    Allowing the .NET GC to be performed has two significant drawbacks:

    1. The .NET GC can occur at any time, and when it does, the entire application is completely locked (i.e. no processing can occur) while the cleanup is performed.
    2. VisionPro image memory usage is not reported to the .NET memory management system, so the .NET GC may not run in time to prevent memory errors.


Project Component Password Protection

Individual components of a project can be protected, with a password being required to open and edit the individual component. When an individual component is protected, the project can be placed in deployed mode without the individual password(s) being entered. However, when the project is Program Mode, to view and/or edit protected components, the specified password must be entered.

The individual component protection is separate from the project-wide Security setting. A project can be configured to have its own password, which protects the entire project, while individual components within the project have their own separate passwords. This allows you to configure different layers of security for a project, where certain users can view the entire project, but have restricted access to individual components and/or Script Block within the project.

The following project components can be password protected:

  • User Scripts
  • WebPage
  • Task
  • Script Block
Note:

  • A protected User Script, individual WebPage or Task / Script Block can be exported as a Template. When a protected component is exported to another project, the component can be inserted into the project without supplying the required password. However, the password must be supplied if the component is to be edited or opened.

    As with the other protected components, exported items will have a key icon beside them in the Template Browser:

  • If a Task or WebPage that is protected has scripts associated with it, those scripts will appear in the Script Browser. However, those scripts will only be accessible if a user provides the correct password when prompted, unless the script is already open in a Script Editor instance. Similarly, the associated, protected scripts can only be deleted via the Script Browser if the correct password is supplied, or the script is already open in a Script Editor.

  • When using the Reconfigure Script I/O option to adjust the arguments and outputs of a protected Script block or User Script, you must provide the associated password. After the arguments and/or outputs have been reconfigured, the Script block and/or User Script will have the same password protection assigned to it.

    When reconfiguring a Script block within a protected Task that is not opened for editing, the password for the protected Task must first be provided.

  • If a protected Script block and/or User Script references Tags or other scripts that are renamed, those references will not updated unless the affected Script block and/or User Script is open in the Script Editor. These instances will be discovered by the Project Verification process, and the necessary changes can then be made by opening and editing the affected Script block and/or User Script.
  • The Search window will not identify items that are contained in protected scripts unless the Script block and/or User Script is open in the Script Editor.

Protecting Project Components


Protecting Project Components

The process of protecting individual project components is similar for each type of component.

  1. Select the project component to protect, right-click the component and select Protect from the menu.

    Note:
    • When selecting multiple components, such as several Script blocks, the Protect option is available in the right-click menu if one of the selected components has not been protected but can be protected. In addition, the Protect option will also be enabled if none of the selected components has been protected.
    • To protect a Script block or User Script, they must have first been initialized, i.e. a script has been added and compiled.

  2. The Protect Component dialog will be displayed, where you can set the password.

    Note:

    • If multiple components have been selected for protection, the dialog will state "[multiple items]" to indicate multiple components are being assigned a password.

    • When multiple components are selected, they must all share the same password.

  3. Once a project component is protected, a key icon will be placed beside the protected component:

  4. To open the component, you must enter the assigned component password.

Note:

Once a component has been protected, the protection can be removed by following the steps above, but selecting Unprotect from the right-click menu, instead.


WebHMI Settings

The WebHMI Settings are used to configure the authentication access of users and an inactivity timeout. For procedural steps to follow when working with WebHMI Settings, see WebHMI: A Functional Overview.

To add extra security, you may want to enable an automatic timeout (in minutes) to prevent authentication with WebHMI after a certain period of inactivity by the user. When the set Inactivity Timeout value expires, the dialog is locked and authentication is required to proceed.

Note: You cannot set an automatic timeout in test mode.

The ability to require a login to access all of the Web Pages can be controlled by setting the Enable Built-in Authentication setting for all of the WebPages contained in a project. When enabled, this setting covers all of the WebPages in a project, and cannot be applied selectively to an individual WebPage.

This will force a user to enter user credentials (user name and password) when accessing a project from a Web browser during deployed mode. The default WebPage will only load if the user is able to successfully log in; otherwise, the login dialog will continue to be displayed.

Note: When Enable Built-in Authentication is disabled, no log in is required and all of the elements have normal access (i.e. are determined by the logic on the WebPage).

While the project is in deployed mode, the Inactivity Timeout determines the interval for user interaction with the PC running the WebPage HMI. When this setting is enabled (it is enabled by default), the current user will be logged off and all WebPage Elements that require authorization will become disabled if there has not been any interaction during the specified time period.

Note: This feature works in deployed applications only. it does not function in test mode.


Tags

Tags are named variables that can be created by the user to store data, and can be inputs (read to) or outputs (written from). In programming terms, they are similar to global variables. The data stored in a tag can be accessed and shared throughout the entire application.

Tags are the primary way Cognex Designer shares information between the different areas of the application, and they are usually identified by the '$' character.

Tags can also contain an array of data, such as an array of integers or an array of blobs. These types of tags can be created by accessing the Complex Type Selector dialog, when editing the tag's Data Type (using the Data Type Selector), while in the Tag Manager.

Note: For more information about creating an array data type for a tag, see the Creating an Array with the Complex Type Selector Dialog topic.

Using Tags

Adding Tags

Selected Path

Extended Tag Properties

Import and Export Tags

Replace Tags


Using Tags

Tags can be used in variety of ways, but are primarily used as a binding to pass data between different components of the project.

  • Page

    Used to bind a Page element.

    Note: See the Binding Properties for more information.

  • Task

    Assigning tags to Task Blocks input and output pins. Right-click the pin and select either Assign to Tag or Assign to New Tag.

  • Scripting

    Press the $ key, followed by the tag name.

    Web Pages

    Used to bind the properties of WebPage Elements.

    Note: For more information, see the Binding Properties topics.


Adding Tags

Tags are edited using the Tag Manager. To add a new tag, simply start typing the name of the tag into the empty row at the bottom of the table.

Tip: Pressing the Plus button will automatically scroll to the bottom of the table and allow you to type immediately.

Note:

  • By using a name and then a period (".", like "Recipes.BoxHeight") puts the items in groups, making it easier to search when using code complete and tag browsing.

    Alternatively, you can press the Copy button, which creates a copy of the selected tags and their properties.


Selected Path

All Cognex Designer tags have a Selected Path property. This property can be used in a number of different ways to achieve different behavior.

Selected Path

Expression Paths

Tag Redirection


Selected Path

Device Paths

When a supported Device is connected, accessing data on the Device can be configured by setting the Selected Path to a Device variable.

Note: Currently, Cameras are the only supported Devices.

The format for the Device path is always: [DeviceName]DeviceVariable. When a Device path is set, all properties for the Device will be accessible in the auto-complete window.

Once the Device path has been set, an Update Rate property will become available for the tag.

The Update Rate property sets the desired time, in milliseconds, for the property to be polled from the Device.

When the tag's value is set, the Device's property will be updated during the next poll cycle.


Expression Paths

Tag paths can be expressions. These expressions can perform simple logical operations that are automatically updated whenever the source tag's value changes.

Some example expressions are shown below:

  • $IntTag1 * $IntTag2
  • $StrTag + " String Concatenation"
Note: If an expression is configured, the tag will effectively become read only. For more information on expressions, see Expression Builder.


Tag Redirection

Tags can be redirected. $Tag1.Path gets the current redirection path. The tag redirection path can be changed at runtime using scripts by setting the .Path property, as shown below.

  • $Tag1.Path = "Tag2"

The above line of code redirects Tag1 to be pointed at Tag2. Any change to the value of Tag1 will be changed on Tag2 and vice-versa. When a tag has a .Path configuration, the tag will no longer hold a value itself, but is instead used as a shortcut.

Note: When redirecting tags, ensure that the tags both have the same Data Type, otherwise an error may occur.

For example, a tag would be created that will be used for redirection, e.g. $TagRedirection.FlexiTag. As shown below, .the $TagRedirection.FlexiTag.Path = $TagRedirection.TagB. This configures $TagRedirection.FlexiTag to no longer hold any value itself; instead, it is a shortcut to whatever value stored by $TagRedirection.TagB.

Note: To view the above example, load the FunctionSample from the Cognex Designer Launch Page - Sample Projects tab, and open the TagRedirection Page (Pages > Concepts > TagRedirection).


Extended Tag Properties

Depending on the tag configuration, certain additional properties may be configurable in the Properties tool window.

The most common extended property is the Update Rate. This is configurable when the Selected Path parameter of a tag is referencing a device. The Update Rate specifies how often (in milliseconds) the data should be requested from the device.


Import and Export Tags

Tags can be exported as a template file and then imported back into Cognex Designer to quickly generate and modify existing tags.

  1. Select the tag to export, and then right-click with your mouse.

  2. This will launch the Export dialog, where you can configure a name, a tooltip and a description for the exported file, as well as its location.

Note:

You can also export tags into a CSV file, in order to be able to open them in a third party application, such as Microsoft Excel.

To export/import tags into/from a CSV file, from the Project Explorer System node, right-click Tag Manager and select the relevant option from the context menu.


Replace Tags

The Replace Tags function scans the selected controls for bindings.

  1. The Replace Tags shortcut can be located in the toolbar, or by using the Ctrl-R keyboard shortcut.

  2. This will launch the Tag Substitute dialog, where you can replace the desired tag.

    Note: The replaced tag name must be valid, otherwise you'll receive a "The requested substitution is not valid" error message.


Using a DataSet as a Tag

The DataSet Data Type can be stored as Tags. When stored as a tag, the DataSet is accessible everywhere in the application. There are two different methods for creating a DataSet as a tag: using the DataSet Editor or defining the DataSet tag in JavaScript.

You can use the DataSet Editor to quickly define the schema of the tag, and then pass the data into the table through a Script Block, for example. When stored as a DataSet tag, you can also use the tag as a read-only tag, where you can store predefined values. In this instance, you could use this data to be displayed on a WebPage for initial settings for various tools or procedures, or as a means to store settings and then parse the DataSet before applying the settings.


Tags - Best Practices

This topic covers best practices when using Tags within a project.

  • When creating Tags, use a period character between names (e.g. "VisionPro.TaskPins.BlobCount") to categorize your tags. This allows the Tag Browser to create a tree structure of your tags, and also assists with code completion.

  • When naming tags, avoid using the terms "Devices", "FileSystem", "HMI", "Pages", "System" or "Tasks". Using these terms may cause a conflict with an internal tag or object, and may be difficult to locate because it will be interspersed with the existing internal tags.
  • Minimize writing to a Persistent tag in Tasks, because it performs a disk I/O operation, so it may affect timing (and fluctuations in timing). Reading, however, has no impact on performance.
  • When using a Persistent tag, only serializable Data Types should be used. Otherwise, startup errors will occur.
Note:
  • There is no limit on the number of tags that can be created in a project.
  • Runtime performance is not affected by the number of tags.
  • Tags created in the Tag Manager are thread safe.


WebPages Tags

The following tags are associated with the top-level WebPage:

Note: For a list of tags associated with WebPage Elements properties, see the WebPages Element Property Tags topic.
Tag | Data Type | Read-Only | Description
$WebPages.CurrentAccessLevel Integer X

Returns the access level of the user currently logged in. Access levels are defined by the administrator.

Note:
  • This tag is changed only if the login has been successful, and is changed together with the $WebPages.CurrentUsername tag.
$WebPages.CurrentUsername String X

Returns a string containing the name of the user currently logged in. If there is no user logged in, an empty string will be returned.

Note: This tag is changed only if the login has been successful, and is changed together with the $WebPages.CurrentAccessLevel tag.
$WebPages.CurrentPageName | String | X | Returns page name.
$WebPages.CurrentPageTitle | String | X | Returns page title.
$WebPages.CurrentPageWidth | Integer | X | Returns width of current page.
$WebPages.CurrentPageHeight | Integer | X | Returns height of current page.
$WebPages.CurrentPageBackgroundColor | CjsColor | X | Returns CjsColor for the background color of the current page.
$WebPages.CurrentPageBorderColor | CjsColor | X | Returns CjsColor for the page border color of the current page.
$WebPages.CurrentPageBorderWidth | Integer | X | Returns border width of current page.

WebPages Element Properties


WebPages Element Properties

WebPages Element Property Tags

The following table contains the element properties, which will automatically be published in Cognex Designer as tags when the element is added to a WebPage. These properties can be set via bindings and WebPage Elements Event Handler Scripts, or monitored in Data Change Scripts (WebHMI), and can be accessed in the Tag Browser.

Element | Property | Tag | Type
CheckBox | Checked | $WebPages.[PageName].CheckBox.Checked | Boolean
DataTable | Content | $WebPages.[PageName].DataTable.Content | TableData
DateTime Entry | Format | $WebPages.[PageName].DateTimeEntry.Format | String
 | Value | $WebPages.[PageName].DateTimeEntry.Value | String
Display | Image Rotation | $WebPages.[PageName].Display.ImageRotation | Integer
 | Zoom Level | $WebPages.[PageName].Display.ZoomLevel | Double
 | Zoom Type | $WebPages.[PageName].Display.ZoomType | Integer
ListBox | Content | $WebPages.[PageName].ListBox.Content | TableData
 | Selected Index | $WebPages.[PageName].ListBox.SelectedIndex | Integer
 | Selected Value | $WebPages.[PageName].ListBox.SelectedValue | String
Numeric Entry | Value | $WebPages.[PageName].NumericEntry | Double
Radio Button | Checked | $WebPages.[PageName].RadioButton.Checked | Boolean
Selection Box | Content | $WebPages.[PageName].SelectionBox.Content | TableData
 | Selected Index | $WebPages.[PageName].SelectionBox.SelectedIndex | Integer
 | Selected Value | $WebPages.[PageName].SelectionBox.SelectedValue | String
Slider | Value | $WebPages.[PageName].Slider.Value | Integer
TextBox | Text | $WebPages.[PageName].TextBox.Text | String
Note:
  • All of the elements (Controls, Graphics) properties can be accessed via the $HMI.SetControlProperty() and $HMI.GetControlProperty() functions. Cognex recommends only using these functions when an element does not have an Cognex Designer published property tag.
  • The properties of the elements are the same as those exposed in the Web Page Editor, minus the white space between the names (i.e. Border Color > BorderColor).
  • When an element with a published property tag is placed on a Panel or in a Group, the path name of the element changes to include the name of the Panel or Group. For example, WebPages.WebPageName.PanelName.CheckboxName.Checked. If the element is ungrouped or removed from the Panel, the path name will be changed; for example, WebPages.WebPageName.GroupName.SelectionBoxName.Content becomes WebPages.WebPageName.SelectionBoxName.Content.

  • A DateTime column in a database query is not supported.

    You cannot use the DateTime tag in WebHMI, for example, displaying a table in WebHMI with a DateTime column.


Users

Cognex Designer provides the ability to manage multiple users, access levels and authentication modes.

User Configuration


User Configuration

Cognex Designer provides the User Configuration tool to allow the user to build a core user management system for the applications.

User configuration allows the user to:

  • Control access to the application based on either
    • Windows authentication
    • “Standard” - application authentication
    Note: See the Local Fallback topic for more information about supporting both options.
  • Control access to components/functionality based on:
    • value in a security field(s)
  • Read/use specific user profile information from Active Directory (AD)
  • Create local profile fields with the ability to store/retrieve data

Authentication Modes

User Field Editor

Access Levels


Authentication Modes

Cognex Designer supports two authentication modes and an additional hybrid mode:

  • Active Directory
  • Standard
  • Local Fallback - the hybrid mode enabling both (for more information, see the Active Directory Authentication topic)

Note: The Configure button is enabled when Active Directory is selected from the list.

Standard Authentication Mode

Active Directory Authentication

Local Fallback

Scripting

Login Implementation


Standard Authentication Mode

In Standard mode, the user name and password are maintained in an SQLite database. The database is found in the Data directory and is called runtime.db3. The table is called Users.

The Standard mode is only suggested for applications where minimal security is necessary, since:

  • The database is not password secure.
  • The passwords are stored as clear text, so they can easily be read by anybody with access.
  • There are no password nor user name rules.
  • There are no built in security groups/levels.
Note: Active Directory is not available in Standard mode, so users will not be able to log in with Windows/System credentials.

With Standard authentication mode, all essential user properties such as a user's email must be saved in the local database. The default fields are:

  • Username(string/text)
  • Password(string/text)
  • CurrentAccessLevel (int).

To add fields, see the Defining User Fields topic.

Note:

When deploying applications, consider the following:

  • Remove test users from the database and (if possible) add production users before deploying.
  • Consider how new users are to be added to the system. If you redeploy and want to save the current users in the deployed database, be sure to back up your database, before deploying the new version.


Active Directory Authentication

In Active Directory mode, the user name and password are maintained by your IT department.

You may access a subset of user properties from Active Directory that includes "EmailAddress" and "VoiceTelephoneNumber". For the full list of properties, see the User Fields And Data topic.

If you wish to use Security access level AD users, you will need to add your AD user names (not passwords) to the local Database: runtime.db3. For the full list of properties, see the User Fields And Data topic.

Active Directory Parameters

To view the parameters for Active Directory, click Configure.

  • Domain Name: to access Active Directory, provide the domain name
    • You can use a command line tool like Active Directory Explorer to confirm the user has access to AD
  • Local Fallback: enables Standard Authentication in addition to AD

    • For details, see the Local Fallback topic.


Local Fallback

Local Fallback enables Standard Authentication in addition to Active Directory (a hybrid mode). It should only be used where security is not an issue, as it exposes all the risks associated with Standard mode.

WARNING: Local Fallback mode is not recommended; use at your own risk.
Authentication mode selected | User name and password authentication maintained in: | Logins permitted | Security1 access level | User properties in local database2
Standard
 | User table in runtime.db3 | Only for users in User table | User table in runtime.db3 | Viewable
Active Directory
 | AD | Only AD accounts | User must be also in User table in runtime.db3 | Present, when the database field name is not an AD field name. At display time AD named fields display AD value from AD, ignoring any field value that is in the local table.
Active Directory with Fallback
 | AD and/or Usertable in runtime.db3 | Both | Both from above | Both from above
Note:
  • 1: Use the CurrentAcessLevel field in User table or create your own fields to take advantage of this.
  • 2: Depends on what field the user adds in addition to the defaults


Scripting

This topic describes the different user configuration-related scripts.

AddUser

public void AddUser(string Username, string Password, int CurrentAccessLevel);

  • Adds record to the User table
    • independent of the authentication mode selected
  • Input: a comma-separated list, one item for each field in the User table, in the same order as in the table
    • Names in the parameter list of the function are the names of the three default fields, to which you can add any number of custom fields as well.
  • Returns: no indication of success. One may use UserExists or Login to verify if adding a user worked.

ChangePassword

public void ChangePassword(string username, string newPassword);

  • Changes the password of the user name submitted
    • can not be used for resetting AD passwords
    • independent of the authentication mode selected
  • Inputs:
    • user name as can be found in the User table
    • new password (Designer has no rule checks for passwords)
  • Returns: no indication of success. One may use Login to verify if changing the password worked.

DeleteUser

public void DeleteUser(string username);

  • removes users record from the SQLite database
    • independent of authentication mode selected.
    • You can delete the current logged in user!
  • Inputs:
    • user name as can be found in the User table
  • Returns: no indication of success. One may use UserExists to verify if adding a user worked.

Login

public bool Login(string username, string password);

  • Login to the application with AD or Standard credentials
    • dependent of authentication mode selected
    • $System.Users.CurrentUsername is set to the username of the user who successfully logs in
    • The application's security behavior is based on the level the user provides for the user name and its access level.
  • Inputs:
    • user name as can be found in the User table
    • password as found in the database or Active Directory
  • Returns: true/false

Logout

public void Logout();

  • logs out of application
    • $System.Users.CurrentUsername becomes blank
    • The application's behavior is based on the user logged in, changes can be implemented by the user through scripting.
  • Inputs: none
  • Returns: no indication of success. One could check if $System.Users.CurrentUsername is empty.

UserExists

public bool UserExists(string username);

  • See if the user name is in the SQLite table
    • case sensitive
  • Inputs:
    • user name as can be found in the User table
  • Returns: true/false

Reference

$System.Users.CurrentUsername - current user successfully logged in.


Login Implementation

There are several ways to implement authentication. The following is a simple example that returns a message as a basis for starting out.

  1. In Application Explorer | Users, create some user-password pairs (or use existing ones).
  2. In Tag Manager, create the tag Loginstatus, Boolean type.
  3. Place the following on a page called Page.
    • Textbox called TextBoxLoginName.
    • Password box called PasswordBox.
    • A button.
  4. Right-click on the button and select Scripts | Mouse Click.
  5. Enter the script example below.
  6. Compile and run.

// use Login ( <user_name>, <password>) that return 1 or 0 (success/ failure)
// assign value to a tag  one creates in tag manager called  $Logingstatus with type of Boolean
// changes to page name and or object will require adjustments to relevant names

$Logingstatus=$System.Users.Login($Pages.Page.TextBoxLoginName.Text, $Pages.Page.PasswordBox.Password);
// simplest of code to show a popup message for success or failure
if (Logingstatus)
    {
    $HMI.ShowInformation ( "Successful login","Login status message" );
    }
else
    {
    $HMI.ShowInformation ( "Login Failed","Login status message" );
    }


User Field Editor

To manage user fields, from the User Configuration dialog, press the Define User Properties button.

Note: Delete and add fields with caution; if the User table already has data, especially when there is already an application in the field, you will replace its data with the new entries.

User Fields And Data


User Fields And Data

Fields are referenced as $System.User.<fieldname>

Default Fields

  • Username

    • Type: string

      This field is not configurable and may not be deleted.

  • Password

    • Type: string - clear text

      This field is not configurable and may not be deleted.

  • CurrentAccessLevel

    • Type: integer - default value is 0

      This field is configurable and may be deleted.

      Note: Handle this field with caution.

AD fields that may be displayed: (strings)

  • Description
  • DisplayName
  • EmailAddress
  • GivenName
  • HomeDirectory
  • HomeDrive
  • MiddleName
  • SamAccountName
  • Surname
  • UserPrincipalName
  • VoiceTelephoneNumber
Note: You must add a field in the User table for each field you want to display.

Data

  • You can view the contents of the User table by adding a Table HMI element to a page and setting the source to Runtime.Users.Getusers.
  • To get individual values, you can use the constructor as follows:
    • $System.User.<fieldname>;
  • You can manage the data in the User table in runtime.db3 with third party SQLite tools.


Access Levels

By default, Designer provides one integer field (CurrentAccessLevel) that can be used to control user access and permissions.

  • Use $System.Users.CurrentAccessLevel to get a current logged in individual user's settings.
  • If you use Active Directory authentication mode then add the AD user names to the SQLite database (access levels will be assigned automatically).
  • If you use Standard authentication mode (users managed in the SQLite database) make sure you assign a value to the CurrentAccessLevel field.

Security

Access levels are stored in the SQLite database. The database is not password protected, it is only as secure as the file/folder/machine security.

Note: Please design your security accordingly (like increasing security using AD fields or an SQL Server database to store values).

User Access


User Access

Cognex Designer supports two different modes of User Access. Cognex Designer provides a set of tags (depending on user mode) that can be connected to Page elements to either hide or disable controls, based on whether the user has sufficient access.

For example, the Enabled property of a Button could be bound to the expression $Users.CurrentUserAccessLevel >= 5. This would restrict the Button's functions to Administrator users.

User Access Standard Mode

User Access Default Mode

Defining User Fields

Active Directory


User Access Standard Mode

In this mode, the user can define any number of users and assign each an access level from (1 - Operator to 5 - Administrator).

To log on, a User can use:

  • $System.Users.Login(username, password): Attempt to log in with a specified user name/password.

Once a user is logged in, The Users.CurrentUsername and Users.CurrentAccessLevel tags are updated for the newly logged in user.

Users can be added and removed at runtime through these functions:

  • $System.Users.AddUser(username,password,accesslevel): Add a new user
  • $System.Users.DeleteUser(username): Remove a user
  • $System.Users.UserExists(username): Check if a user exists.
Note: Users can also be setup through User Configuration, by double-clicking the Users node under System in the Project Explorer.


User Access Default Mode

To access User Configuration, double-click the Users node under System in the Project Explorer.

By default, Cognex Designer user access is controlled through an integer variable, where each user is assigned an access level between 0 and 5.

Access to a Page control is configured by using an expression like $Users.CurrentUserAccessLevel >= 5 on the enabled property of a control.


Defining User Fields

Pressing the Define User Properties button of the User Configuration dialog launches the User Field Editor dialog, where additional information about users may be entered.


Active Directory

When using Active Directory as the security mode, the user name and password will be checked against the domain.

  1. In the User Configuration dialog, set the Authentication Mode to Active Directory.

  2. Press the Configure button to setup the Domain name that is going to be used.

  3. The custom user fields will now attempt to read their data from the user's profile on the Active Directory server. The Name field is actually a property of the user's profile, so it will be automatically populated. The IsMemberOf keyword will iterate through the Active Directory's list of groups and check if the user is a member.

    For information on using a custom user field to assign access levels, see the topic Locating a User's Group Memberships.


Recipes

Recipes are used to define a set of values of Tags, and these values can then be loaded and/or saved while a project is in deployed mode. Each project can contain one or more set of Recipes, and each Recipe is composed of one or more Configuration that defines the values of the associated tags.

Recipes can be thought of as a traditional food recipe, where the Tags are the "ingredients", and the Recipe Configurations define the serving size. For example, in this scenario, if you wanted to make a chocolate cake, and you wanted to make a single slice of cake, that would be one configuration. A cake for 4-6 people would be another configuration, and a cake for 10-12 people would be yet another configuration. The ingredients are the same, but the quantity varies.

In the (Undefined variable: $System.Recipes.ProductName) application, this would mean you had a Recipe called "ChocolateCake", with Tags for $Eggs, $Flour, $Sugar, $Butter, and three Configurations of Small, Medium and Large.

  • The Small Configuration would have $Eggs = 1, $Flour = .5, $Sugar = .33 and $Butter = .25
  • The Medium Configuration would have $Eggs = 2, $Flour = 1, $Sugar = .5 and $Butter = .5
  • The Large Configuration would have $Eggs = 3, $Flour = 2.5, $Sugar = 1.5 and $Butter = 1.5
  • Note:

    • Recipes support tags of the following data types:

      • Boolean
      • Integer
      • Long
      • Double
      • String
      • DateTime
      • Byte []
      • A CogDictionary data type can be used to save an array of patterns or other specific VisionPro types.
    • To update the values for a complex type, e.g. VisionPro ToolBlock or Tool, you must click into it’s value column, and press the "Retrieve the value from the system." button. This will copy the current values from the Tool Block into this recipe configuration.

Defining a Recipe

Recipe Files

Recipes $ Functions and Properties

Interacting with Recipes on a Page


Defining a Recipe

A Recipe is defined by one or more Configuration, which defines the tags (aka "ingredients") and the values of the tags for that Configuration. Each Configuration must have the same tags; therefore, if a tag is removed from one Configuration, it will be removed from all of the Configurations.

  1. To create a Recipe, under the System node of the Project Explorer, select Recipes and right-click and select New Recipe.

  2. The New Recipe Name dialog will be launched, where you specify the name of the Recipe (by default, Products is the new Recipe name).

  3. Once the Recipe has been named, the Recipe Editor will automatically be displayed.

  4. Press the green plus sign button to create a new Configuration and launch the New Configuration Name dialog (by default, NewConfiguration is the new Configuration name).

  5. Within the Configuration sub-editor, a Description can be given to the Configuration. The Tags that will be associated with the Recipe can be dragged and dropped from the Toolbox. Once the Tags have been added, set the appropriate default Value for each tag.

    Note: To update the values for a complex type, e.g. VisionPro ToolBlock or Tool, you must click into it’s value column, and press the "Retrieve the value from the system." button. This will copy the current values from the Tool Block into this recipe configuration.

  6. More Configurations can be added by again pressing the green plus sign and following the steps above to define the Configuration. Each defined Configuration will appear in the Recipe Editor.


Recipe Files

Recipes are composed of individual recipes and their associated Configurations. They are stored in the Projects\<Project Name>\Recipes directory, as JSON files.

Note: Although the files within the Recipes folder are in the JSON format, and can be edited by a standard text editor, Cognex advises only editing the files within Cognex Designer.

Within the Recipes folder, there will be a directory of "Recipes" folders, which will contain a "Directory" JSON file and the Configuration files (also in JSON format). The Directory file contains the name and description of the individual configurations. For example, if you had a project named "Inspection" that had a Recipe called "PartTolerance" with two Configurations called "Part1" and "Part2", the folder and file directory would be: Projects\Inspection\Recipes\PartTolerance, which would contain the Directory, Part1, and Part2 JSON files.


Recipes $ Functions and Properties

The following Recipes $ functions and properties can be accessed via User Scripts or through the Page Controls elements. For more information, refer to Recipes.

  • $ Functions

    Called using: $System.Recipes.RecipeName.$Function

    $ Function | Description | Arguments (with Data Type) | Returns
    Contains ("configurationName")

    Checks if the recipe (specified with RecipeName) has the specified recipe configuration.

    configurationName: String, specifying the name of the recipe configuration whose presence is checked.

    Boolean, returning true if the recipe configuration is found.
    Load ("configurationName")

    Loads the specified recipe configuration to the project.

    configurationName: String, specifying the name of the recipe configuration to load.

             N/A
    LoadFromFile ("sourceFileName") | Loads a recipe configuration from the specified file. | sourceFileName: String, specifying the location of the recipe configuration file to load. | N/A
    SaveToFile ("destinationFileName") | Saves a recipe configuration to the specified file location. | destinationFileName: String, specifying the location where the recipe configuration file will be saved. | N/A
    Remove ("configurationName")

    Removes the specified recipe configuration from the project, and deletes its values.

    configurationName: String, specifying the name of the recipe configuration to remove.

             N/A
    Save ("configurationName", "description")

    Saves the specified recipe configuration from the project, along with a description.

    Note: If a configuration with the same name already exists, execution of this function overwrites that existing configuration.
    • configurationName: String, specifying the name of the recipe configuration to save.
    • description: String, specifying the description of the configuration to save.
             N/A

  • Properties

    Accessed using: $System.Recipes.[RecipeName].[Property]

    Property | Description | Returns
    Configurations | Returns a TableData object, which is used to retrieve the Configurations of the specified Recipe. This is typically bound to a DataTable, ListBox or SelectionBox Page Controls element. | TableData
    CurrentName | Returns the name of the currently loaded Configuration. | String
    CurrentDescription | Returns the description of the currently loaded Configuration. | String
    Note: All returned properties are read-only.


Interacting with Recipes on a Page

You can display a list of recipe configurations using a ListBox and Button Controls elements to load a configuration.

Note: For more information about Recipes $ functions and properties, see the Recipes $ Functions and Properties topic.
  1. Add a ListBox to the Page.
  2. Bind the Source property to the desired Recipe configurations (e.g. $System.Recipes.RecipeName.Configurations).
  3. Add a Button to the Page, and set the Click Command property to the load method: System.Recipes.RecipeName.Load.
  4. This enables a new sub-property, configurationName. Bind this property to the Selected Value property of the ListBox (e.g. $Pages.Page.ListBox.SelectedValue).
  5. If you want the ability to modify the values of a configuration, you will want to save the changes. Add another Button, and set the Click Command property to the save method: System.Recipes.RecipeName.Save.

  6. This enables a new sub-property, configurationName. Bind this property to the CurrentName method: System.Recipes.RecipeName.CurrentName.

    Note: To make changes to values of the tags in the loaded Configuration, you will also need to have Controls elements on the Page, such as a Numeric Entry, that is bound to the tags in the Configuration.


Tasks

Tasks are the primary area where the project's data, image and vision tool processing will be created and managed. Tasks control the running and timing of the tools, allowing for serial or parallel processing.

A project can contain one or more Task, and each Task is comprised of one or more Blocks.

A Task can be triggered by an event (see Task Mode) or manually, after setting the Task Mode to Manual, using the following functions:

  • $Tasks.Task.RunAsync() (Recommended): This will run the task on a new thread and will return immediately.

  • $Tasks.Task.Run(): This will run the task synchronously on the current thread and Block until the task completes.
    Note: Do not use this method from the user interface (e.g. button click).
Note:
  • Manual triggers (i.e. $Tasks.<TaskName>.RunAsync()) will be ignored if the Task is already executing.
  • When the Task has been setup for Event triggers (Event, Timer Interval, etc.), the Task will always run on a separate, static thread.
  • Event triggers that are received while a Task is running will be queued.
  • For more information about triggering a Task, see the Task Mode topic.
  • It is not possible to abort or cancel a Task.

Task Execution Order

Tasks - Best Practices

Task

Task Mode


Task Execution Order

Tasks Execution Order

The following table details the execution order of a Task:

Task | Block
Task.Execute |
For each enabled Block\Sub Task: |
 | Copy values to input pins
 | Update tag inputs
 | Internal Block Execution
 | Update tag outputs
 | Record Block execution time
If an error is encountered, then execute Task.OnError |
Increment CountSinceLastGC |
IF CountSinceLastGC == GC Frequency, then execute GC.Collect |
Set Task.ExecutionTime |
Execute Task.OnComplete |


Tasks - Best Practices

The following are guidelines when configuring Tasks for your project.

  • For the best performance and results, Cognex recommends only using one Task per inspection; creating more than one Task per inspection is not recommended.
  • Instead of using more than one Task, use a Sub Task block.
  • Use if statements instead of exceptions, because exceptions will effect performance. For example, if a VisionPro Tool Block is configured with a CogIDTool that has Results[0] as an output, and the inspection fails to detect anything, calling Results[0] will result in an exception.
  • Do not directly access a Page element property from a Task (e.g. $Pages.Page.TextBox.Text); instead, bind the property (e.g. .Text) to an intermediate tag. Using the intermediate tag will help prevent performance and cross-thread issues.

  • While Task Mode supports a Continuous option, Cognex recommends that Continuous mode not be used for deployed applications. Instead of using Continuous mode, when acquiring from a Camera Device, set the camera's Trigger to Free Run, and the Task Mode to Event > ImageAcquired (e.g. $Devices.Camera1.ImageAcquired).

    Note: For more information, see the Acquiring Images Continuously topic.

  • Instead of manually polling a device, set a tag's Selected Path to the device.

    Note: For more information, see the Device Paths topic.

  • To poll an I/O device that is not listed under the Devices node of the Project Explorer, a High Precision Timer can be used.

    Note: For more information about configuring a High Precision Timer, see the Timers topic.
  • A Task may not be forced to stop.


Task

A Task is used to graphically configure and construct image processing devices, tools and operations by placing Task Blocks in a flow diagram.

By default, the blocks are executed serially, from left to right, starting with the block on the left-most side of the Task (1).

The order of execution is based on the position of the upper left corner of the block. Blocks placed in a Parallel Structure will execute in parallel (2). Blocks placed in a Group Region will execute all blocks within the group before executing the next block in the sequence (3, 3A, 3B and 4), or not execute, if a Group Condition Tag is applied (5).

While in Program Mode, to test a Task, press the Task execution buttons, Run All, Run Selected, Run From → End, or Run From → To, in the upper left corner of the Task Editor.

The total Time Taken to execute the Task is reported in the bottom bar below the flow diagram.

Tasks are under the Tasks > Task node of the Project Explorer; double-click the desired Task to open it in the Task Editor.

To test a Task, click the [image] button in the upper left corner of the Task Editor.

Note: As of release 4.0.0, 2.x project sequences are replaced with a sub task.
Note:

  • For more information about the Task execution buttons, see the Task Editor topic.

  • Best practice is to complete one full run of the task blocks before attempting to run a subset of task blocks.

  • You must use the Run All option before using the Run Selected, Run From → End, or Run From → To options if you have used any other component of the In-Sight Multi-Camera IDE prior to using the Task. This will ensure that any Task Block Input and Output pins, as well as tag values, are updated correctly.

  • For more information about placement of the blocks in a Task, see Task Block Positioning in the Task Editor topic.

  • While in Run Mode, a Task can be configured to execute all of the blocks in the Task, specific blocks or start the order of execution at one block to another specified block. For more information, see the $ Functions: Tasks topic.

  • To help define the execution sequence and improve performance, use the Structure Blocks and Regions.

  • The total Execution Time reported for the Task will be slightly greater than the sum of all the blocks in the Task (~1ms, depending on the system).

  • For keyboard shortcuts and navigation tips, please see the Task Editor Keyboard Shortcuts and Task Editor Navigation topics.

  • Tags in a Task are updated as the individual blocks referencing the tags are executed, i.e. tags associated with a Task block, either as an input and/or output, are read and/or written to immediately.

  • Since tags are similar to global variables, Cognex advises against configuring a project that allows a tag to be read and/or modified in more than one Task at a time. This can lead to a tag losing updates, depending on when and where the tag was read and/or modified.

  • The total Execution Time reported for the Task will be slightly greater than the sum of all the blocks in the Task (~1ms, depending on the system).
  • While multiple Tasks can be added to a Task, they will execute in an indeterminate order. Cognex recommends using Sub Task Blocks instead of more than one Task.
  • An individual Task within a Task cannot be triggered to execute independent of the other Tasks.
  • For keyboard shortcuts and navigation tips, please see Task Editor and its related subtopics.

Task Blocks

Script Blocks


Task Blocks

Devices, tools and operations are dragged and dropped from the Task Toolbox as Blocks. The Blocks can then be organized in a flow diagram, and data can be linked between the different devices, tools and operations.

Block structures are executed based on their position in the diagram (executing from left to right in the diagram). A Task Block is divided into inputs, the block itself, and outputs. During operation, the inputs are received, the Block executes, and once it has finished executing, the Block will update the outputs and any tags associated with them.

  • If a Block cannot be processed, it will be indicated by a red line.

    Note: When a Block has an output pin, it will only update when the Block executes. This means that if the output pin already has a value from a previous run, it will retain that value until the Block is successfullyrun again. This enables the ability to do things like use a Camera Acquire Block to get a new image, then disable the Block so subsequent acquisitions work with the previous image.

    • Working With Task Blocks

    Camera Blocks

    Communication Blocks

    Data Manipulation Blocks

    Data Storage Blocks

    Structure Blocks and Regions

    Vision Tool Blocks


Working With Task Blocks

The following topics describe task block properties and how you can use various graphical shortcuts, tips, and techniques to work with them more efficiently.

Task Block Properties

Bend Points for Task Editor

Block Pin Name Viewing

Block Pin Reordering

Block Reordering by Snap-to-Grid

Reordering Pins with the Configure Subtask I/O Dialog


Tool Blocks and Properties

Task Block Properties

Task blocks have several properties which you can set in Task Editor by selecting a block and checking the Properties window. This window contains the default properties of a Task block.

Figure 1: The Greater Than or Equal To block and its properties

In the Properties window, you can change these properties. You can provide value to them either static or an expression, bind them to tags, or change the name of the block itself. You can also extend the list of properties by right-clicking on the block and selecting Configure I/O. This menu item appears only for those blocks that are set as ConfigurableBlock on code level.

Figure 2: The default I/O set for the Greater Than or Equal To block

  • I/O: By default, this block has a Result Output pin, and two Value Input pins. The input and output options are mutually exclusive, one cannot be an input and an output pin parallelly (Figure 2).
  • Tag: You can mark either item as Tag. In this case, a tag is automatically created bound to the related item. You can find these tags in the Tag Browser under the relevant Task (Figure 3). Marking an item as Tag does not exclude the option of marking an item also as Input or Output pin, but it is also possible to mark an item only as Tag.
  • If an item is not I/O and not a Tag, then it becomes a Property and appears in the Properties window of the block (Figure 4).

Figure 3: I/O items marked as Tag

Figure 4: All I/O items set as properties of the block


Bend Points for Task Editor

Decrease the size and complexity of your task layouts while also increasing their usability by using bend points in your block connectors.

Using bend points, you graphically introduce flexibility to your block placement by bending and compacting your connector lines, enabling you to show more in a smaller space.

Task Layout not using Bend Points. Note the crossed connectors, crowded placement, and wasted space.

Task Layout using Bend Points. Note the traceable connectors, compact placement, and increased readability.

Add a Bend Point

Add a bend point to a connector by doing the following:

  1. Create a connector between two or more blocks.
  2. Hover your mouse over the connector until the line appears to thicken.

  3. Click on the connector while holding down the CTRL key and move the mouse up or down, creating a bend point in the connector. A small circle appears at the bend point.

Add a Bend Point to an Existing Bend Point

  1. Follow the steps in the procedure Add a Bend Point, above, to add a bend point to a connector.
  2. Select the circle marking the bend point you created.
  3. Hover your mouse over the connector. The connector appears to thicken.

  4. Right-click. A context menu appears with the menu item Create Bend Point.

  5. Select Create Bend Point. A second bend point is created, adjacent to the first bend point.

Remove Select Bend Points

Remove select bend points from a connector by doing the following:

  1. Hover your mouse over the circle marking the bend point you want to delete. The circle gets larger as you hover your mouse over it.
  2. Right-click on the circle marking the bend point you want to delete. The context menu appears.
  3. Select Remove Bend Point. The selected bend point is deleted.

Remove All Bend Points from a Connector

Remove all existing bend points from a connector by doing the following:

  1. Hover your mouse over one of the bend points on the connector that you want to delete. The circle marking the bend point gets larger as you hover your mouse over it.
  2. Right-click on the circle marking the bend point. The context menu appears.
  3. Select Remove All Bend Points. All bend points on the connector are deleted.

Remove All Bend Points But One from a Connector

Remove only select bend points from a connector by doing the following:

  1. Hover your mouse over the circle marking the bend point you do not want to delete. The circle gets larger as you hover your mouse over it.
  2. Right-click on the circle marking the bend point you do not want to delete. The context menu appears.
  3. Select Remove All Bend Points But This. All bend points on the connector, with the exception of the bend point you clicked, are deleted.


Block Pin Name Viewing

Block Pin Name Viewing allows you to preview the name and type of each pin. By pointing with your mouse to blocks, or while connecting pins while working in the Task Editor, you can preview the name and pin associated with each pin.

As you begin to drag a connection between pins, a visual overlay on top of the blocks displays the name and type of each pin.

Enable pin previewing through a setting in the Task Editor, as shown in the video.

Click here to launch in a separate window.

Enabling Block Pin Name Viewing

Before enabling or disabling Block Pin Name Viewing, ensure the following conditions are met.

  • Your project contains a task with at least one block

  • At least two blocks have input or output pins

Enable Block Pin Name Viewing by doing the following:

  1. Click Tools > Options
  2. Select Task Editor.
  3. Select Show Pin Info.
  4. Click Apply and OK.

Block Pin Name Viewing activates and displays information as you move the mouse around the Task Editor"¶ ¶

Previewing Pin Names By Making a Connection Between Pins

In the Task Editor, click and drag the output pin of one block to the input pin of another block.

If the connection is compatible, the connector will turn from red (non-compatible) to green (compatible). If the connection is not compatible, the connector will remain red, snap back to the input pin, and not connect.

For an example of this functionality, play the video.

Click here to launch in a separate window.

Previewing Pin Names by Pointing Your Mouse to a Task Block

To preview a pin name in the Task Editor, point your mouse to a block. As you do, the pin names fade in, becoming visible.


Pin reordering for Script Blocks, Subtasks and Subtask Input/Output Blocks

Block Pin Reordering

You can reorder pins graphically, in addition to using the Configure SubTask I/O dialog and the Script Definition Editor.

Reordering Pins by Shift-Clicking and Dragging

While working with blocks, you can reorder input and output pins by shift-clicking on the pin and dragging the it to the desired order of precedence on the block.

To reorder pins using this graphical shortcut do the following:

  1. Hold down the SHIFT key.
  2. With the SHIFT key still depressed, click on the pin you want to drag and reorder. When you click and hold, the pin connector (with tag argument2 [Boolean]) becomes red and white and resembles a target. This indicates the pin is selected and ready for reordering.

  3. Release the SHIFT key and drag the pin down to below the bottommost pin (argument1 [Int64]). As the pin is dragged, the pin head turns solid red.

  4. When you release the mouse button, the tagged pin argument2 [Boolean] is now ordered at lowest precedent (the bottom).


Block Reordering by Snap-to-Grid

Block Reordering Using Snap-to-Grid

You can create symmetrical, evenly-spaced layouts automatically with Snap-to-Grid.

When you enable Snap-to-Grid reordering, the system enforces a positioning algorithm while creating and moving blocks. The Algorithm calculates and optimizes placement based on the block's top-left point to ensure a symmetrical fit into the grid.

Why Use Snap-to-Grid Reordering?

When you enable Snap-to-Grid block reordering, you ensure no two blocks occupy the same X-axis location on the task grid, ensuring a clear, deterministic execution order.

Similarly, positioning multiple blocks on the same X-Axis is not recommended, as doing so may result an unintentional or non-deterministic execution order.

Snap-to-Grid reordering prevents and resolves this problem with the following features:

  • Vertical Warning Line — When using Snap-to-Grid Reordering, two (or more) blocks occupying the same X-Axis position within a task grid generate an orange vertical line appears as a warning. The absence of the orange vertical line on your task grid guarantees a deterministic execution order of the task blocks in your grid.

  • Auto-repositioning — When you reposition or add a block, the system automatically positions it to an available X-axis position.

Enabling Snap-to-Grid Reordering

Turn on this functionality by doing the following:

  1. If you haven't already done so, invoke the Task Editor. While in the Task Editor, locate the Toggle Grid icon in the Toolbar.

  2. Click the Toggle Grid icon. A checkered grid is superimposed on the regular Task Editor layout, converting the view from the image on the left below, to the image on the right below.


Reordering Pins with the Configure Subtask I/O Dialog

After creating a subtask block, right-click on the block and select Configure Subtask I/O. The Configure Sub Task Input/Output Pins dialog launches.

The input pins are listed in the left pane of the dialog; the output pins are listed on the right.

In the appropriate pane, select each pin Name and Type and move the pin up and down the list using the arrows, to change pin precedence.

Use the add, copy, and delete icons to add pins, duplicate selected pins, or delete selected pins.

When all pins are ordered to your satisfaction, click Accept.


Camera Blocks

Cognex Designer supports including one or more Camera Device and/or Image File Device directly into a Task. This allows you to include the image acquisition step as part of the Task.

Note: A camera cannot be connected to both an CogAcqFifoTool in a VisionPro Tool Block and as a Device in Designer.

Integrating Cameras

Setting Up a GigE Camera

Setting Up a Displacement Sensor

Simultaneous Multi-Camera Acquisitions


Integrating Cameras

  1. After a Camera device has been added to the project, it will appear in the Task Toolbox under Devices.
  2. To add the Camera device to a Task, go to the Toolbox and expand the Devices category.
  3. Drag and drop the desired Camera device onto the Task, where it becomes a Reference Block that can be linked to compatible Tool Blocks or Reference Blocks.

  4. Press the [image] Run button to execute the Task and acquire an image.


Setting Up a GigE Camera

Cognex Designer supports including GigE cameras directly into a Task. This allows you to include the image acquisition step as part of the Task.

  1. Connect the camera to the network and the power source.
  2. Use the Cognex GigE Vision Configurator utility to configure the camera.

  3. In Cognex Designer, in the Devices node of the Project Explorer, right-click Cameras and select Add > 'Camera' device.

    Note: If the camera is already listed, right-click on it and select Connect.

  4. This launches the Parameter Configuration dialog, where you provide the name, the device and the video format for the camera.

    Note: For more information about the Parameter Configuration dialog, see the Camera Device topic.
  5. Press the Accept button.
  6. Go to Tasks > Task > Task.

  7. In the Toolbox, your camera will be in the Devices node, with the name you specified.

  8. Drag and drop the desired Camera device onto the Task, where it becomes a Reference Block that can be linked to compatible Tool Blocks or Reference Blocks.

  9. Double-click the camera's block to configure the camera's Settings, Strobe & Trigger, Image Properties, GigE and Custom Properties, as well as focus and acquire images with the camera.

    Related Topics For more information, see the Acquiring From a Connected Camera section of the Configuring an Image Source topic in the VisionPro® Online Documentation.

  10. You can then link your camera's output image as an input to other blocks in the Task.

    Note: To poll a GigE feature of a camera, consider using the Device Paths of a tag. Or, alternatively, you can utilize GigE commands; for more information, see the Using GigE Commands with a Camera Device topic.
  11. Press the Run [image] button to acquire an image, and pass the image to the linked block.

Using GigE Commands with a Camera Device


Using GigE Commands with a Camera Device

You can also utilize the GigE commands to get, set and execute different features of GigE cameras. These commands can be used, for example, on startup to prepare the camera for acquisitions, on a Button to save changes to the camera, or in a command that needs to be run in a Task.

WARNING: Do not use these commands while a camera is acquiring; doing so may lead the camera to stop acquiring and require a system restart.
Note: Before using these commands, add Cognex.VisionPro to the Using statements.
var fifo = (ICogAcqFifo)$System.GetInternalObject("Devices.Camera0");
ICogGigEAccess gige = fifo.FrameGrabber.OwnedGigEAccess;
gige.ExecuteCommand ("SaveUserSet");

gige.SetIntegerFeature("Integer_Feature_Name", 53);
gige.SetDoubleFeature("Double_Feature_Name", 12.005);
gige.SetFeature("Feature_Name", "Some value as a string");

uint intValue = gige.GetIntegerFeature("Integer_Feature_Name");
double doubleValue = gige.GetDoubleFeature("Double_Feature_Name");
string stringValue = gige.GetFeature("Feature_Name");


Setting Up a DS 1000 Series Sensor

Setting Up a Displacement Sensor

Cognex Designer supports including Cognex Displacement Sensors directly into a Task. This allows you to include the image acquisition step as part of the Task.

  1. Connect the camera to the network and the power source.

    Note: See the DS1000 Quick Reference Guide for more information.

  2. In Cognex Designer, in the Devices node of the Project Explorer, right-click Cameras and select Add > 'Camera' device.

    Note: If the camera is already listed, right-click on it and select Connect.

  3. This launches the Parameter Configuration dialog, where you provide the name, the device and the video format for the camera.

    Note: For more information about the Parameter Configuration dialog, see the Camera Device topic.
  4. Press the Accept button.
  5. Go to Tasks > Task > Task.

  6. In the Toolbox, your DS sensor will be in the Devices node, with the name you specified.

  7. Drag and drop the desired Camera device onto the Task, where it becomes a Reference Block that can be linked to compatible Tool Blocks or Reference Blocks.

  8. Double-click the camera's block to configure the DS sensor's Settings, DS1000 Series, Strobe & Trigger, Calibration, GigE and Custom Properties, as well as focus and acquire images with the DS Sensor.

    Related Topics For more information, see the Acquiring Images from a DS1000 Series Sensor topic in the VisionPro Online Documentation.

  9. You can then link your camera's output image as an input to other blocks in the Task.

  10. Press the Run [image] button to acquire an image, and pass the image to the linked block.


Simultaneous Multi-Camera Acquisitions

For vision applications requiring multiple cameras, they can be configured to simultaneously process images in the same Task.

  1. Configure the Task Mode of the Task to trigger one of the camera's ImageAcquired Event (e.g. Devices.Camera1.ImageAcquired).

    Note:
    • Both cameras should be configured to acquire images from a hardware trigger. For information on configuring the Task Mode to the ImageAcquired Event, see the Hardware Acquisition Triggers topic.
    • Attempting simultaneous acquisitions through manual software triggers (e.g. $Devices.CameraName.Acquire) is not recommended. Use the Precision IO Configuration Editor to setup the camera triggers, instead.

  2. Place a Camera Block in the Task for both cameras.

  3. Now, when Camera1 is triggered to acquire an image, Camera2 should acquire, as well.


Communication Blocks

The Communication Blocks are used to configure serial, TCP/IP, Discrete I/O, Event Handling and Factory Protocol blocks.

COM and TCP/IP Blocks

Discrete I/O Blocks

Event Handling Blocks

Factory Protocol Blocks


COM and TCP/IP Blocks

These blocks are used to configure TCP/IP or serial port data.

Decode Byte Stream Data

Encode Byte Stream Data

Receive Data

Send Data


Decode Byte Stream Data

The Decode Byte Stream Data Block is used to convert a byte array to a string, based on the specified encoding.

The block has a single input pin, which accepts a byte array to decode, and a single output pin, which outputs the decoded string. When the block is executed, the input byte array is converted to a string, using the specified encoding, and the result string overwrites the output pin's content.

Setting | Description
Encoding | Sets the type of encoding to use. By default, Unicode (UTF-8) is selected.


Encode Byte Stream Data

The Encode Byte Stream Data Block is used to convert a string to a byte array, based on the specified string encoding.

The block has a single input pin, which accepts a string to encode, and a single output pin, which outputs the encoded byte array. When the block is executed, the input string is converted to a byte array, using the specified encoding, and the result byte array overwrites the output pin's content.

Setting | Description
Encoding | Sets the type of encoding to use. By default, Unicode (UTF-8) is set.


Receive Data

The Receive Data Block is used to receive byte array or string data, via TCP/IP or serial protocols. Using multiple buffers for each device, pins are set according to the buffer, when the Block runs, and then flushes the latest buffer. The Block can also be configured to consume all of the available data, and to hold the Task until all of the data has arrived.

Note: It is recommended that a Task Trigger should be defined, which fires whenever new data is received; select the device and the DataReceived trigger from the Event drop-down list. The trigger will occur when new data is received over the TCP/IP or serial port. See the Task Mode topic for more information.

During execution of the Task, when data is received via the specified device, the received data is pushed into a buffer. A separate buffer collection is used for each device, so if data is received while the device already has data in its buffer, the new data will be pushed into the next buffer.

When the block is executed, any data in the oldest buffer is formatted according to the specified Data Type and Encoding parameters, and then associated to the output pin. At this point, the oldest buffer is removed.

  • If the Consume Mode is set to All Buffers, all of the buffers will be consumed when the block is executed, versus the oldest buffer when set to One Buffer.
  • If the deployed mode is set to Don't Wait, the block will return data immediately available, even if no new data has been received.
  • If the deployed mode is set to Wait until Data received, the block will wait to return data until there is new data available, or the timeout expires.
Note: The Receive Data Block does not have any input pins. The output pin is determined by the Data Type parameter.

Setting | Description
Selected Device | Sets the device associated with the block, either a TCP/IP or RS232 device.
Data Type | Sets the data type, byte array or string. By default, string is set.
Encoding | Sets the type of encoding to use. By default, Unicode (UTF-8) is set. This setting is ignored if the Data Type is set to byte.
Deployed Mode | Specifies how the block will handle data. By default, the block is set to Don't wait, which specifies that the block will return the data in the buffer, even if new data is available. When set to Wait until Data is received, the block will wait until new data is available, or the Timeout expires.
Timeout (ms) | Specifies a timeout if the deployed mode is set to Wait until Data received.
Consume Mode | Specifies how the block will handle the data buffers. By default, the block is set to One Buffer, which specifies that the block will only consume the oldest buffer at execution.


Send Data

Sends a byte array or a string, via TCP/IP or serial protocols. The Block has a single input pin, and its type is determined by the Data Type parameter (Byte or String). This block does not have any output pins.

When the block is executed, the data is sent via the selected device.

Setting | Description
Selected Device | Sets the device associated with the block, either a TCP/IP or Rs232 device.
Data Type | Sets the data type, byte array or string. By default, string is set.
Encoding | Sets the type of encoding to use. By default, Unicode (UTF-8) is set. This setting is ignored if the Data Type is set to byte.


Discrete I/O Blocks

The Discrete I/O Blocks are used to read and write discrete I/O lines of a Cognex Communication Card, either on a PC or a Vision Controller.

Read IO Block

Write IO Block


Read IO Block

Read IO

The Read IO Block reads the lines of Input Bank 0, and the state of the Precision I/O interface, from the Cognex Communication Card, and assigns them to the block's output pins. The number of output pins are defined by selecting the number of visible output pins that can be configured, using the Select Visible Pins dialog.

Property | Description
Name | Specifies the name of the block.
Selected Device | Specifies the device (either a Cognex Communication Card or a Vision Controller) that will be associated with the block.
Visible Pins | Press the Edit button (or double-click the Block) to launch the Select Visible Pins dialog, where the number of output lines can be configured. By default, all of the output pins are visible.

Pin | Description
InputBank0Line0-7 | The lines of InputBank0, represented as a Boolean. Uses a 0-based index.
InputBank0 | The entire input bank, represented as an integer.
TimeStamp | The timestamp of when the input was read.
PrioState | The current status of the precision I/O interface. Note: This pin can be associated with a Schedule Event to schedule a precision I/O event.


Write IO Block

Write IO

The Write IO Block writes the given values of the output banks to the Cognex Communication Card. The number of input pins are defined by selecting the number of visible input pins that can be configured, using the Select Visible Pins dialog.

Property | Description
Name | Specifies the name of the block.
Selected Device | Specifies the device (either a Cognex Communication Card or a Vision Controller) that will be associated with the block.
Visible Pins | Press the Edit button (or double-click the Block) to launch the Select Visible Pins dialog, where the number of output lines can be configured. By default, all of the output pins are visible.

Pin | Description
OutputBank0Line1-15 | The lines of OutputBank0, represented as a Boolean. Uses a 0-based index.
Sensor1-2Trigger | The two editable lines of the DS1000 OutputBank0 as a Boolean. Uses a 1-based index. Note: These lines are only available when connected to a Vision Controller.


Event Handling Blocks

The Event Handling blocks are used to schedule and cancel events associated with the Precision IO Configuration Editor.

Cancel Event

Schedule Event


Cancel Event

The Cancel Event Block is used in conjunction with a Schedule Event and the Precision IO Configuration Editor, to cancel a scheduled event. This block is only able to cancel an event if it is manually scheduled by a Schedule Event, and cannot prevent a precision I/O event response from occurring if the response was automatically scheduled by the Cognex Communication Card if the cause event has been met. The event to cancel is identified by the block's input pin, which should be linked to a Schedule Event output EventToken.

Note: Allows the Cancel method of the CogPrioScheduledEventToken class to be used as a block.

Property | Description
Selected Device | Specifies the device (either a Cognex Communication Card or a Vision Controller) that will be associated with the block.


Schedule Event

The Schedule Event Block is used in conjunction with the Precision IO Configuration Editor, to schedule a precision I/O event to occur. The block's input pin is a CogPrioState type, called Relative Source, which can be used to schedule an event relative to a specific state (e.g. if the Schedule Type parameter is set to Time, the Schedule Value parameter is set to 200 milliseconds, and the relative source is set to 1000 milliseconds as the current time value, the event will be scheduled to occur at 1200 milliseconds). A CogPrioState object can be created with a Read IO; if a relative source is not provided, the event will be scheduled relative to the state when the block is executed.

Note: Allows the Schedule method of the CogPrioEvent class to be used as a block.

Property | Description
Name | Specifies the name of the block.
Selected Device | Specifies the device (either a Cognex Communication Card or a Vision Controller) that will be associated with the block.
Precision IO Event | Specifies the associated Precision IO event, which is defined in the Precision IO Configuration Editor (and can be launched by pressing Configure...).
Schedule Type | Specifies the type of scheduling to use, Time or Encoder (by default, Time is set). Note: Currently, Encoder is not supported, and if the block is configured to Encoder, it will fail to execute and the Task will stop when attempting to execute the block.
Schedule Value | Specifies how many milliseconds or encoder ticks from the previous state until the event occurs. Note: Currently, time values are the only supported value.


Factory Protocol Blocks

The Factory Protocol blocks are used to handle factory floor protocol communications as part of a Task.

Format PLC Input Buffer

Format PLC Output Buffer

Notify PLC Block

Read PLC Block


Format PLC Input Buffer

Used to extract values from a byte array, typically sent from a PLC.

You can specify a set of values, which will then be represented as an output pin. For each value, you can also define a starting index, a type, a name and size (though the type may determine the size). You can also address a single bit from a byte, and extract it as a Boolean value.

When the block is executed, the byte array will be parsed based on the values of the Data Format property (configured in the Format PLC Input Buffer Data Format Dialog), and the values of the output pins are overwritten with the newly extracted values.

Properties | Description
Name | Specifies the name of the block.
Data Format | Specifies the format of the output data, which is formatted using the Format PLC Input Buffer Data Format Dialog.

Format PLC Input Buffer Data Format Dialog


Format PLC Input Buffer Data Format Dialog

This dialog, which can be launched by either pressing the Edit button in the Properties or double-clicking the block, is used to define the data description for the Format PLC Input Buffer block. To add a pin, press the New Pin button in the top-right of the table.

Note: Several bits may be mapped into a byte, and it is possible to map and use all of the individual bits of a byte, one by one.

Setting | Description
Format According to FFP Protocol | Specifies whether or not PLC protocol formatting (FFP) will be applied to the data. When enabled, the specific PLC formatting defined in the Protocol selection will automatically be applied to the block.
Protocol | Specifies the type of PLC protocol (EtherNet/IP, PROFINET, SLMP or Custom) to apply, which determines the endianness and byte swapping that will be applied to the data. Select Custom to create a non-protocol specific formatting.
Endianness | Specifies the type of endianness to apply (Little Endian or Big Endian) when the selected protocol is Custom. This setting is automatically set for all other protocols.
Swap bytes in 16-bit words | Specifies whether or not to use byte swapping when the selected protocol is Custom. If enabled, the bytes are swapped for 2-byte words.
Name | Defines the name of the output pin.
Type

Defines the pin type:

PLC Data Type | Pin (.NET) Type | Length in Bytes (on the PLC) | Endianness Applied | Byte Swapping Applied
Single bit | Boolean | 1 | No | No
Single byte | Byte | 1 | No | No
16-bit signed integer | Short | 2 | Yes | Yes
16-bit unsigned integer | Integer | 2 | Yes | Yes
32-bit signed integer | Integer | 4 | Yes | Yes
32-bit unsigned integer | Long | 4 | Yes | Yes
64-bit signed integer | Long | 8 | Yes | Yes
64-bit unsigned integer | Decimal | 8 | Yes | Yes
32-bit floating point | Double | 4 | Yes | Yes
64-bit floating point | Double | 8 | Yes | Yes
ASCII Text | String | Various | No | Yes
Byte Array | Byte[ ] | Various | No | Yes
Byte Offset | Specifies the 0-based index of the data to parse in the byte array.
Length in Bytes | Specifies the length of the data, in bytes.
Bit Offset | Specifies the bit address.


Format PLC Output Buffer

Used to combine a set of variables into a byte array, which is typically sent to a PLC.

You can specify a set of values (configured in the Format PLC Output Buffer Data Format Dialog), which will be represented as an input pin. For each value, you can also define a starting index, a type, a name and size (though the type may determine the size).

When the block is executed, the values of the input pins are converted into bytes, and the result is converted into a one byte array. If there are missing bits or bytes in the output array, they are substituted with zeroes. The newly created byte array overwrites the existing value of the output pin.

Property | Description
Name | Specifies the name of the block.
Array Length | Defines the length of the array, in bytes.
Data Format | Specifies the format of the output data, which is formatted using the Format PLC Output Buffer Data Format Dialog.

Format PLC Output Buffer Data Format Dialog


Format PLC Output Buffer Data Format Dialog

This dialog, which can be launched by either pressing the Edit button in the Properties or double-clicking the block, is used to define the data description for the Format PLC Output Buffer block. To add a pin, press the New Pin button in the top-right of the table.

Note: A byte may be mapped into several bits, and it is possible to map and use all of the individual bits of a byte, one by one.

Setting | Description
Byte Array Length | Defines the array length property. This value is only editable if Automatic Array Length is disabled.
Automatic Array Length | Specifies whether or not the length of the output byte array will always be set to the smallest possible value. Disable to define a custom output byte array length.
Format According to FFP Protocol | Specifies whether or not PLC protocol formatting (FFP) will be applied to the data. When enabled, the specific PLC formatting defined in the Protocol selection will automatically be applied to the block.
Protocol | Specifies the type of PLC protocol (EtherNet/IP, PROFINET, SLMP or Custom) to apply, which determines the endianness and byte swapping that will be applied to the data. Select Custom to create a non-protocol specific formatting.
Endianness | Specifies the type of endianness to apply (Little Endian or Big Endian) when the selected protocol is Custom. This setting is automatically set for all other protocols.
Swap bytes in 16-bit words | Specifies whether or not to use byte swapping when the selected protocol is Custom. If enabled, the bytes are swapped for 2-byte words.
Name | Defines the name of the output pin.
Type

Defines the pin type:

PLC Data Type | Pin (.NET) Type | Length in Bytes (on the PLC) | Endianness Applied | Byte Swapping Applied
Single bit | Boolean | 1 | No | No
Single byte | Byte | 1 | No | No
16-bit signed integer | Short | 2 | Yes | Yes
16-bit unsigned integer | Integer | 2 | Yes | Yes
32-bit signed integer | Integer | 4 | Yes | Yes
32-bit unsigned integer | Long | 4 | Yes | Yes
64-bit signed integer | Long | 8 | Yes | Yes
64-bit unsigned integer | Decimal | 8 | Yes | Yes
32-bit floating point | Double | 4 | Yes | Yes
64-bit floating point | Double | 8 | Yes | Yes
ASCII Text | String | Various | No | Yes
Byte Array | Byte[ ] | Various | No | Yes
Byte Offset | Specifies the 0-based index of the data to parse in the byte array.
Length in Bytes | Specifies the length of the data, in bytes.
Bit Offset | Specifies the bit address.
Show as Pin | Specifies whether or not the parameter will be displayed as a pin.
Value | Specifies the value to use when the parameter is not displayed as a pin. This setting is disabled if Show as Pin is enabled.


Notify PLC Block

Notify PLC

The Notify PLC Block is used with events that a Cognex Communication Card or Vision Controller will use to communicate with the connected PLC. The number of input pins is dynamically generated based on the Notification Method Type parameter setting.

Related Topics For more information about the I/O Assemblies associated with Factory Floor Protocols, please see the CogNDM Class topic in the VisionPro Help file.

Properties | Description
Name | Specifies the name of the block.
Selected Device | Specifies the device (either a Cognex Communication Card or a Vision Controller) that will be associated with the block.
Notification Method Type | Specifies the notification method. Note: For more information about the Notification Method Type parameter selections, see the NDM Notification Functions topic.
Arguments | Specifies the current notification arguments, which are configured in the Notification Settings dialog.

Notification Settings


Notification Settings

The Notification Settings dialog can be displayed by pressing the Edit button of the Arguments parameter, or alternatively, double-clicking the Block. The dialog is used to configure the notification method, using the drop-down menu of the Notification Method parameter.

Note: For more information about the Notification Method parameter selections, see the NDM Notification Functions topic.

Once the notification method has been selected, a table will be created that displays the input arguments of the selected notification method.

The Show as Pin checkbox specifies whether or not to display the argument as an input pin on the block. If an argument is not represented as an input pin, its value can be set in the Value column.

Note: The Inspection Complete notification method is the only method that enables the Number of Columns parameter, which determines the number of visible AcquisitionIDn and CameraIndexn arguments.


Read PLC Block

Read PLC

The Read PLC Block is used to receive data from a PLC. On execution, the block reads the user data sent from the remote device to the vision system.

Note: For more information about the I/O Assemblies associated with Factory Floor Protocols, please see the CogNDM Class topic in the VisionPro Help file.

Properties | Description
Name | Specifies the name of the block.
Selected Device | Specifies the device (either a Cognex Communication Card or a Vision Controller) that will be associated with the block.


Data Manipulation Blocks

The Data Manipulation blocks are used to manipulate collections of data.

Collection Blocks


Collection Blocks

Collection Blocks are used for composing and decomposing data arrays, and accessing an index of a collection.

Compose Collection

Decompose Collection

Get by Index


Compose Collection

Creates a collection from a set of homogenous values. Each element of the collection is represented as an input pin and the created collection is represented as a single output pin. The size and the type of the collection is an editable property of the block . Users can show or hide the available input pins (Figure 1).

Note: The type of the created collection can be a different type of generic IListimplementation.

Figure 1: Compose Collection block settings

Setting | Description
Collection type
  • List
  • Array
Element type
  • byte
  • char
  • short
  • int
  • long
  • double
  • string
  • object
Collection size | The number of items in the collection.
Filter by Index | You can enter the index number for the element(s) you wish to see in the list. You can use comma or semicolon as delimiter (for example: 1,2,3 or 1;2;3), or intervals (for example: 1-3;4;6-8).
Visible Pins | You can check which elements should be visible (Figure 2).

Figure 2: The elements of an array marked as visible appear as input pins on the Task block.


Decompose Collection

As the opposite of Compose Collection, it splits an IListinto separate elements. Each element of the collection is represented as an output pin and the collection is represented as a single input pin. The size and the type of the collection is an editable property of the block. Users can show or hide the available output pins (Figure 1).

Figure 1: Decompose Collection block settings

Setting | Description
Element type
  • byte
  • char
  • short
  • int
  • long
  • double
  • string
  • object
Collection size | The number of items in the collection to be made.
Filter by Index | You can enter the index number for the element(s) you wish to see in the list. You can use comma or semicolon as delimiter (for example: 1,2,3 or 1;2;3), or intervals (for example: 1-3;4;6-8).
Visible Pins | You can check which elements should be visible (Figure 2).

Figure 2: The elements of an array marked as visible appear as output pins on the Task block.


Get by Index

Retrieves an element of an array, addressed by a specified index. The block has, by default, two input pins and an output pin. You can provide the collection and an index number as input and the block will provide the element with the given index from the collection.

The index can be both a pin or a block property:

Setting | Description
Element type
  • byte
  • char
  • double
  • int
  • long
  • object
  • short
  • string
Index | The index value for the element to get.


Data Storage Blocks

The Data Storage Blocks are used to add data to Databases and send and store images.

Database Writer

Image Recorder


Database Writer

The Database Writer Block is used to write data to Databases.

Writing to a Database from a Task


Writing to a Database from a Task

The Task provides a dedicated block for inserting rows into a table.

  1. From the Data node of the Toolbox, drag and drop a Database Writer block onto the Task.

  2. Configure which database table to write to by double-clicking the block to open the Database Writer Configuration dialog, and select the database table.

  3. Once the table has been selected, the block will generate input pins for each of the data columns in the table. The input pins can be linked to other blocks and tags, and every time the block executes, the values of all the input pins will be added into a new row in the table.


Image Recorder

The Image Recorder Block is used to store acquired images from Camera devices.

Saving Images with the Image Recorder Block


Saving Images with the Image Recorder Block

After adding Camera devices, the images that they acquire can be stored to specified directories using the Image Recorder Block.

  1. From the Toolbox > Data Storage category, drag and drop an Image Recorder block onto the Task.

  2. Double-click the block to open the Recorder Properties dialog, which is used to configure the input pins of the block.

  3. Configure the parameters of the dialog:
    1. The Recorder Type parameter should be set to the type of image being output by the Camera device that will be connected to the block.
    2. The Root Directory parameter is used to specify the location of the directory that will be used to store the images.

    3. The Filename Format parameter specifies the format that will be used to name the image files.

      Note: The Root Directory and Filename Format parameters are used to construct the recorded image's file name, e.g. Root Directory + Filename + Image File Extension (.bmp/.cdb).

    4. The Record Mode specifies how the image files will be written to disk.Synchronous specifies that the block will write the image to disk and wait until it has completed. Asynchronous specifies that the image will be placed into a queue (a maximum of 32 images can be queued; if the queue is full, images will be discarded) to be saved in a separate thread, while the block continues to record images.

      Note:

      If Asynchronous is selected as the Record Mode, the Image Recorder block should be placed as either the last block in the Task, or after the last modification (i.e. the last time that the image is either processed or operated on by another block) of the image in the Task. Since Asynchronous mode records the images on a different thread, and the block does not wait for the recording to complete, the Task will continue to execute. If, for example, the image is to be processed by another VisionPro Tool Block later in the Task, this may lead to the Designer application crashing, because accessing VisionPro images from different threads at the same time, is not supported.

      If it is not possible to either place the Image Recorder block at the end of the Task or after the last modification to the image, you can make a copy of the VisionPro image and record the copied image. You can copy a VisionPro image in script with the following statement: Cognex.VisionPro.CogSerializer.DeepCopyObject(InputImage);

  4. Press the Accept button to close the dialog.
  5. Link the desired Camera device to the Image Recorder block:
    1. Link the Camera's output Image to the Image Recoder block's Object input.

    2. Typically, the Root Directory and File Path input pins are left unlinked and use the root directory and file format specified in the Recorder Properties dialog, or are configured to a tag that will define the inputs.


Structure Blocks and Regions

The Structure blocks and regions allow you to organize and optimize the execution of your Task .

Group

Note

Now

Parallel

Sub Task


Group

Group Region

The Group region is used to organize blocks and their execution in a Task.

For example, if four Tool Blocks are laid out in a Task, as shown below, their execution will be from left to right, as follows: ToolBlock_0 > ToolBlock_1 > ToolBlock_2 > ToolBlock_3.

However, by placing two Group regions around the blocks, as shown below, their execution will now be: ToolBlock_0 > ToolBlock_2 > ToolBlock_1 > ToolBlock_3. The order of execution is changed because "Group" will execute the blocks contained within it before the blocks in "Group1" are executed.

By placing a Processing Parallel Regions around the two Group regions, the Tool Blocks in "Group" will execute sequentially on one thread, and the Tool Blocks in "Group1" will execute sequentially on another thread.

If a Parallel region was placed around all four Tool Blocks, but the Tool Blocks were not with Group regions, all of the Tool Blocks would execute in parallel.


Note

The Note block provides a way to add descriptive comments to a Task.

Drag and drop the Note onto the Task, then type a description into the Comment section of the properties.


Now

The Now block retrieves the current time from the PC, as a DateTime data type. This block can be used as an input pin to a Database Writer block, allowing inspection results to be tied to the time of inspection.


Parallel

In the Task Editor, the Parallel region allows you to draw a region around multiple blocks and have all of those blocks execute in parallel.

Below is an example of using a Parallel region to speed up the processing of two image processing tools.

Note:
  • Do not put a Parallel region inside another Parallel region.
  • When blocks are placed within a Parallel region, the blocks within the Parallel region are executed simultaneously; the left-to-right order of the blocks within the Parallel region does not affect the order of execution. Use a Group Region or a Sub Task block to control the order of execution if multiple blocks will be within a Parallel Region. For more information, see the Executing Blocks Inside a Parallel Region topic.

Executing Blocks Inside a Parallel Region

Processing Parallel Regions

Parallel Regions and Images as Links Versus Tags


Executing Blocks Inside a Parallel Region

Sometimes you want a few groups of blocks to execute in parallel. In this case, you will need to place each logical sequence of blocks within a Group Region or a Sub Task block to prevent them all from being executed at the same time, before their pins can be updated.

Note: For better performance, use a single Parallel region with multiple Group regions or Sub Task blocks, versus using a single Group region or Sub Task block with multiple Parallel regions.

In the above layout, when the Parallel region executes, all of the blocks within the Parallel region are executed at the same time. Designer will not check to see if there are dependencies, which means that "ToolBlock1" could execute before the result from "ToolBlock" is received, so "ToolBlock1" could execute on old data.

Instead, to control the execution flow, the blocks within the Parallel region should be either placed in Group regions or Sub Task blocks.


Processing Parallel Regions

Cognex Designer supports parallel processing with multi-core CPU's through the use of the Parallel region, which allows the processing of intensive applications to be optimized for fast execution.

  • The Parallel region is constrained by the number of processor cores on the PC, both for development and deployment. For instance, if your development/deployment PC only has two processor cores, you should only have two VisionPro Tool Blocks within a Parallel region. If the Parallel region contained three VisionPro Tool Blocks, the three blocks would not be executed simultaneously, because the PC only has two processor cores.
Note:
  • Disable hyper-threading, as the system might perform the process in parallel, but on the same physical core, hence negating any performance gains.
  • Test the performance of your project to determine whether or not the Parallel region has a positive impact on performance.


Parallel Regions and Images as Links Versus Tags

Parallel regions allow multiple blocks to be executed at the same time. This adds complexity, as different blocks can alter the image data or coordinate space from different threads, which can result in errors being thrown (seemingly at random). Due to this complexity, there are two different ways that image data can be passed into a Parallel region:

  1. When an image is linked into a Parallel region, it will result in the image being duplicated (aka cloned). Cloning has a slight overhead, so for very fast image processing operations, it may be faster to process sequentially. By using a link, the image will be fully cloned (pixel data and coordinate space tree), so each block will be acting on the image data independently.

    Cloning an image means that the Tool Blocks will no longer be acting on the same object, so information cannot be transferred between them. The data will need to be correlated by the user after exiting the Parallel region.

    Note: You may also need to join records from the separate images into one record.

  2. If an image tag is used as input for multiple VisionPro Tool Blocks within a Parallel region, Designer will automatically prevent parallel executions in an attempt to prevent cross-thread exceptions from occurring by locking the image to one block at a time.

    When using a tag to pass image data, the same image object will be acted on by all of the blocks in the region. However, this means that the blocks may not run in parallel, since one block waits for another to finish processing on the image tag.


Sub Task

The Sub Task block allows you to organize and simplify a complex Task by placing other blocks inside it. Unlike the Group Region, the Sub Task block nests other blocks within itself, with its own Input and Output pins, and its own separate tab in which the blocks within it can be configured and edited. Sub Task blocks can also be exported as Templates.

Like the full Task, the [image] button must be pressed to update the blocks within, and pressing the [image] button will take you to the Task containing the Sub Task.

The Task below is configured without any Sub Task blocks:

The same Task is then configured with two different Sub Task blocks:

Adding Blocks to a Sub Task

Configuring a Sub Task Block


Adding Blocks to a Sub Task

A Sub Task block can be created in two ways: dragging and dropping a Sub Task block into the Task from the Toolbox, or selecting one or more blocks in a Task and selecting Create Sub Task from the right-click menu.

Note: Sub Task blocks can be nested within other Sub Task blocks.

  • When dragging and dropping a Sub Task block into the Task from the Toolbox, a new, empty Sub Task will be created.

    Blocks can then be dragged and dropped into the Sub Task from the Toolbox. See the Configuring a Sub Task Block topic for more information about adding pins to the Sub Task input and output blocks.

  • Alternatively, blocks in a Task (or even another Sub Task) can be selected by either holding down the Ctrl Key and left-clicking the mouse on individual blocks, or dragging and holding the left-click button of the mouse over a selection of blocks. Then, right-click and select Create Sub Task to automatically populate a Sub Task.

    The selected blocks will be extracted from their current location, and placed into the Sub Task with all of their input and output pins intact.

    The Sub Task will also maintain any links that existed between the blocks in the Sub Task and the Task they were extracted from.

Note:

When extracting blocks, ensure that the order of execution (left-to-right) is maintained. The Designer application will warn you if you are creating an unresolved loop, however, you have the ability to override the warning message.

For example, if you had a set of blocks as shown below, and attempted to extract the Or and XOR blocks into a Sub Task:

You will create a broken loop, because the Or and XOR blocks rely on the execution of the Not1 block, which was not incorporated into the Sub Task.


Configuring a Sub Task Block

After a Sub Task block has been added to a project, input and output pins for the block can be configured.

  • If the Sub Task block was created from existing blocks, the input and output pins will have been automatically configured. The order of the pins can then be modified, and new pins can be added, and existing pins can be removed.
  • If the Sub Task block was added by from the Toolbox, the input and output pins will have to be configured by adding the desired pins.

To configure the pins of the Sub Task block, use the right-click menu while either selecting a Sub Task block in a Task, or selecting the input or output block of a Sub Task, and selecting Configure Sub Task I/O, which will launch the Configure Sub Task Input/Output Pins dialog.

Note: While in a Task containing a Sub Task block, you can either double-click the Sub Task block or select and choose Edit from the right-click menu to open the Sub Task block's Task Editor.

Configure Sub Task Input/Output Pins dialog


Configure Sub Task Input/Output Pins dialog

The Configure Sub Task Input/Output Pins dialog is used to add, delete and reorder the input and output pins of a Sub Task block.

When an empty Sub Task block is added to a project, the dialog will not be populated with either inputs or outputs, as shown below. You must add inputs and/or outputs (press the + button).

When a Sub Task has been created based on extracted blocks, the dialog will be populated with the inherited input and output pins, as shown below.

  • The pins can be renamed, reordered or removed, and new pins can be added, as needed.

    • Press the + button to add a pin.
    • Select a pin and press the x button to remove a pin.
    • Select a pin and use the up and/or down arrows to reorder the pin.

  • The names of the pins are auto-generated, with the first part of the name being the name of the block it will be connected to, and the second part is the name of the pin it is being connected to.

    When renaming a pin, the connection will be persisted as long as the Type stays the same. The pin's name must be unique, may only contain alphanumeric or underscore characters, and may contain a '.' character, but cannot start or end with it.

    Note: The Data Type Selector is used to configure the Type parameter.


Vision Tool Blocks

VisionPro Tool Blocks

Cognex Designer supports the addition of VisionPro CogToolBlocks to a Task. This allows users to include the image processing and vision algorithms as part of the Task.

Note:
  • This topic assumes that Cameras have been added and configured to pass images to the Tool Block.
  • A VisionPro Tool Block saved in a Designer project will not contain the input image. They are saved using the VisionPro serializer, using the CogSerializationOptionsConstants.Minimum parameter.
  1. To add a VisionPro CogToolBlock to a Task, go to the Toolbox and expand the Vision > VisionPro category.

  2. Drag and drop the Tool Block onto the Task, where it becomes a VisionPro Tool Block. By default, the Tool Block has a single input pin, which can be linked to compatible Reference Blocks, such as a Camera Reference Block, or other Tool Blocks. The linked block should provide the image that will be processed.

  3. After linking the Tool Block, press the [image] Run button to execute the Task and force the Tool Block to execute and acquire an image.
  4. Double-click the Tool Block to open the Designer Tool Block, which will open in a new tab beside the Task.
Related Topics

The following topics can be referenced in the VisionPro® Online Documentation:

  • Using a CogToolBlock
  • CogToolBlock Edit Control
  • QuickBuild - Working With Jobs
  • QuickBuild - Configuring Job Properties
  • QuickBuild - Adding Vision Tools

Adding VisionPro Tools

Adding Input and Output Pins to a Tool Block

Scripting with VisionPro Tool Blocks

Adding Tags to a Tool Block

VisionPro Tag Manager

VisionPro Script Editor

VisionPro Tool Block Graphics Options

Accessing VisionPro Multi-Threaded Aware Vision Tools


Adding VisionPro Tools

Vision tools are added and configured from within the VisionPro Tool Block, and utilizes the CogToolBlock to construct the vision processing steps.

Note:
  • If a CogToolBlock is going to be imported into a Designer project, ensure that the GC is disabled prior to being imported, because it cannot be disabled in Designer. For more information, see the Memory Management topics.
  • The number of VisionPro tools added inside a CogToolBlock affects the runtime performance of a Designer project. Before a VisionPro tool and/or a CogToolBlock is run, their input terminals need to be set, and it takes time as the new value propagates through tools in the CogToolBlock. A total of between approximately 0.2-0.4ms is added per tool connection in a CogToolBlock (though on rare occasions it can spike to between 3-8ms); the total overhead is directly proportional to the number of connections in a CogToolBlock (i.e. 10 tools = 2-4ms of overhead). The QuickBuild Job Editor does not report this time, nor is it included in the RunStatus.TotalTime property of a CogToolBlock.

  1. Double-click the Tool Block to open the Designer Tool Block, which will open in a new tab beside the Task. From this tab, pre-configured Tool Blocks can be imported, and configured Tool Blocks can be exported. In addition, the VisionPro Script Editor and VisionPro Tag Manger may be launched and you can also password-protect your ToolBlock.

    Note: If password protection is enabled, the Tag and Script buttons are disabled for the VisionPro ToolBlock. This setting persists when the ToolBlock is exported as a template as well. For more information on password protection, see the Creating a Vision Application: Using the Application Wizard topic in VisionPro Help | Application Development Guide.

  2. With the Designer Tool Block open, from the Toolbox, drag the desired vision tool between the [Inputs] and [Outputs], and connect the [Inputs] Image to the tool's InputImage.

  3. After adding the tool and linking the image, right-click the tool name and select Edit to open the QuickBuild Job Editor.

  4. Configure the vision tool using the QuickBuild Job Editor.

  5. Once the tool has been configured, return to the Task and add tags and link the Tool Block's input and output pins to the desired Reference or Tool Blocks.
Related Topics

The following topics can be referenced in the VisionPro® Online Documentation:

  • Using a CogToolBlock
  • CogToolBlock Edit Control
  • QuickBuild - Working With Jobs
  • QuickBuild - Configuring Job Properties
  • QuickBuild - Adding Vision Tools


Adding Input and Output Pins to a Tool Block

Within Cognex Designer, CogToolBlock [Inputs] and [Outputs] Terminals are used to define the Input and Output pins on the VisionPro Tool Block in a Task.

Note: In a VisionPro Tool Block, if a third-party DLL is referenced in either a script or Input/Output Terminals, the DLL must be either added into the Designer installation folder or into the Global Assembly Cache (GAC). If the third-party DLL will also be run in Quick Build, then the DLL will also need to be in the VisionPro installation folder or GAC, as well.
  1. Double-click the Tool Block to open the VisionPro Tool Block, which will open in a new tab beside the Task.

  2. To add Input/Output pins to the Tool Block, there are two options: using the Inputs/Outputs tab, or selecting either [Inputs] or [Outputs] in the Tool tab, and using the right-click menu. Both options call the same menus and Browse dialog.

  3. Select the desired Input/Output from the default menu options. If the desired type does not appear in the list, press the Browse button, and then navigate and select the desired Input/Output type from the list.

Related Topics

The following topics can be referenced in the VisionPro® Online Documentation:

  • CogToolBlock Edit Control - Inputs/Outputs Tab


Scripting with VisionPro Tool Blocks

Scripting can be utilized to interact with VisionPro Tool Blocks in two different ways: externally, through the Designer Script Editor, or internally using the VisionPro Script Editor.

The Designer Script Editor offers a simplified interface, while the VisionPro Script Editor is a more robust editor. The key difference between the two scripting mechanisms, however, is that the VisionPro Script Editor does not have access or knowledge of the Designer tags and objects, and does not support the $ Functions. Thus, the VisionPro Script Editor should only be used to create scripts inside the VisionPro Tool Block, whereas the Designer Script Editor can be used to interact internally with the Tool Block, or through other external interactions in the Task.

Capability | VisionPro Script Editor | Designer Script Editor
.NET Auto Complete | YES | YES
Class Creation | YES | NO
Script Creation | NO | YES
Tag Handling | NO | YES
Tag Renaming | NO | YES
Tag Search Functionality | NO | YES
Local Find and Replace | YES | NO
XML Documentation Tooltip | NO | YES

Scripting with VisionPro Tool Blocks and Designer Scripting

Scripting with VisionPro Tool Blocks and VisionPro Scripting


Scripting with VisionPro Tool Blocks and Designer Scripting

The Designer Script Editor can be used to create scripts that interact with VisionPro Tool Blocks. When writing the scripts, ensure that the correct VisionPro references are added to the project in the Script References dialog. For more information, please see Scripting and Configure VisionPro Tool Block Graphics.


Scripting with VisionPro Tool Blocks and VisionPro Scripting

The VisionPro Script Editor can be used to create scripts used within a VisionPro Tool Block in Designer. However, the VisionPro Script Editor cannot access the $ Functions used in the Designer Script Editor.

In order to interact with the Designer tags from the VisionPro Script Editor, add additional [Inputs] and [Outputs] to the Vision Pro Tool Block prior to opening the VisionPro Script Editor. Reference these [Inputs] and [Outputs] in the VisionPro Script Editor, and assign the tool block's input and output pins to their appropriate tags in the Task.

The process of execution is:

  • Read the value from the input tag.
  • Load the VisionPro Tool Block.
  • Set the VisionPro Tool Block's input pin to the value associated with the input tag.
  • Execute the VisionPro Tool Block.
  • Set the VisionPro Tool Block output pins to the value associated with the output tag.

In this manner of execution, the tag and variable in the VisionPro script are not "linked"; the tag and variable values are populated once the VisionPro script has finished executing. For example, if the output value "OutputTime" is set in the VisionPro script, the tag will not be updated until after the entire VisionPro Tool Block has finished executing.

Note:
  • For more information about adding [Inputs] and [Outputs], please see the Adding Input and Output Pins to a Tool Block topic.
  • For more information about assigning tags, please see the Adding Tags to a Tool Block topic.
  • This version of the VisionPro Script Editor only supports the C# Advanced Script language.
  • In a VisionPro Tool Block, if a third-party DLL is referenced in either a script or Input/Output Terminals, the DLL must be either added into the Designer installation folder or into the Global Assembly Cache (GAC). If the third-party DLL will also be run in Quick Build, then the DLL will also need to be in the VisionPro installation folder or GAC, as well.

  1. With the Tool Block open, press the Edit Script button to launch the VisionPro Script Editor.

  2. Create the script and ensure that it compiles correctly before closing the editor.
Related Topics

The following topics can be referenced in the VisionPro® Online Documentation:

  • Scripting in QuickBuild - Using the VisionPro Script Editor
  • Using a CogToolBlock - Scripting with a CogToolBlock


Adding Tags to a Tool Block

Tags are the means in which data is exchanged between a Tool Block and the rest of the application. There are two different methods that may be used to assign tags to a Tool Block. One method is to use the VisionPro Tag Manger, which will create nested tags within the Task > Tool Block structure. The other method is to add tags to the Input/Output pins of the Tool Block in the Task, which will pass the tags to the top level of the Designer Tag Manager.

Note: Tags created using the VisionPro Tag Manager are not available in the Designer Tag Manager.

Adding Tags to a Tool Block Using the Designer Tag Manager

Adding Tags Using the VisionPro Tag Manager


Adding Tags to a Tool Block Using the Designer Tag Manager

There are two different methods that may be used to add tags to a Tool Block in a Task, using the Designer Tag Manager.

  1. One option is to add the tags to the Tag Manager directly, and then right-click the pin of the Tool Block and select Assign To Tag. Navigate to the desired tag and press the Accept button.

    Note: Please see the Adding Tags topic for more information about adding tags directly to the Tag Manager.
  2. The other option is to right-click the pin of the Tool Block, and select Assign to New Tag. Enter a name for the tag and press the Accept button. The new tag will now appear in the Tag Manager, as well.


Adding Tags Using the VisionPro Tag Manager

The VisionPro Tag Manger is used to assign tags to a tool in a Tool Block.

  1. With the Tool Block open, press the Edit Tags button to launch the VisionPro Tag Manager.

  2. Select a property from the left-pane; if it can be added as a tag, the Tag Name field will be outlined in green, otherwise, it will be in red and the property will not be allowed to be added. Press the right-arrow button to add the property as a tag.

  3. To add additional properties to the available choices, select either All (unfiltered) or Expanded from the Browse drop-down menu.

  4. Once all of the desired tags have been added, press the Accept button.
  5. The tags will now be added to the Tool Block, and are nested within Tasks > Task > Task > VisionProToolBlock > TagName.
Note: Tags created using the VisionPro Tag Manager are not available in the Designer Tag Manager.


VisionPro Tag Manager

VisionPro Tag Manger

The VisionPro Tag Manager is used to add, configure and edit tags associated with VisionPro Tool Blocks.

To launch the VisionPro Tag Manager, press the Edit Tags [image] button on the VisionPro QuickBuild Job Editor toolbar.


VisionPro Script Editor

The VisionPro Script Editor is used to add, configure and edit scripts associated with VisionPro Tool Blocks.

To launch the VisionPro Script Editor, press the Edit Scripts [image] button on the VisionPro QuickBuild Job Editor toolbar.


VisionPro Tool Block Graphics Options

Each VisionPro Tool Block can be configured to disable or enable the Record Graphics and Composite Graphics. For the best performance at runtime, Cognex recommends disabling both Record Graphics and Composite Graphics.

Record Graphics

To edit the Record Graphics setting for a VisionPro Tool Block, double-click the Tool Block and select the appropriate option from the drop-down menu in the Properties window:

Note:

The time to create a record is not indicated in the CogToolBlock Edit Control or RunStatus.TotalTime, unless the edit control is open and the Show Composite Graphics checkbox is enabled. If performance is a concern, choose Disabled, because when one of the Enabled options is selected, it may cause the following:

  • A record may need to duplicate the input image;
  • A record may need to perform complex, and time-consuming, drawing functions on an image (e.g. drawing boundaries around a blob);
  • A record executes on the UI thread, so timings may be unpredicatable.
Setting | Description
Disabled | For the best runtime performance of the Tool Block, disable the setting. Sample Time: ~25ms
Enabled (Copy Image) | Choose this option if you want to display the record and/or perform post-processing on different threads. Sample Time: ~70ms
Enabled (No Copy) | Choose this option if you want to use the record for further processing on the same thread. Sample Time: ~60ms

Composite Graphics

To edit the Composite Graphics setting for a VisionPro Tool Block, double-click the Tool Block and select the Graphics tab of the CogToolBlock Edit Control.

When the project is deployed, for the best performance, disable Show Composite Graphics, because when enabled, it will force the Create Records function to run (see the above table for the approximate impact to the Tool Block execution when enabled).

Related Topics

The following topics can be referenced in the VisionPro® Online Documentation:

  • About Tool Records
  • Using the Graphics Tab


Accessing VisionPro Multi-Threaded Aware Vision Tools

Some VisionPro vision tools are multi-thread aware, and can be programmatically enabled to operate on threads. This can be accessed via script, such as the following example (the script has a Using statement of Cognex.VisionPro):

CogVisionToolMultiThreading.Enable = true;
CogVisionToolMultiThreading.ThreadCountMode = CogVisionToolMultiThreadingThreadCountModeConstants.HardwareDefined;

This option enables multi-threading on a VisionPro vision tool level (e.g. a CogBlobTool), which is different than the Processing Parallel Regions, which creates a multi-thread on the Designer Task Block level. For example:

  • A PC with a two-core processor, with two VisionPro Tool Blocks in a Processing Parallel Regions. Designer will use two threads and execute each block on independent threads, using the two available cores, which means that multi-threading the individual vision tools will be unlikely to yield better results.
  • A PC with a two-core processor, with two VisionPro Tool Blocks, and a Parallel Region is not being used. The Task is executed on a single thread, so if the vision tools are multi-threaded, they will be able to take advantage of the extra processor core.
Note: This option is useful if a Processing Parallel Regions cannot be used. However, also note that not all VisionPro vision tools will benefit from this option. Please refer to the VisionPro® Online Documentation for more information on multi-thread aware vision tools.


Script Blocks

The following topics describe various graphical shortcuts, tips, and techniques to work more efficiently with script blocks.

Working With Script Blocks


Working With Script Blocks

The following topics describe script block properties and how you can use various graphical shortcuts, tips, and techniques to work with them more efficiently.

Block Pin Reordering

Auto-Pin Creation for Scipt Blocks

Reordering Pins with the Script Definition Editor


Auto-Pin Creation for Script Blocks

While working with script blocks, you can auto-create pins by dragging your mouse between blocks.

What Is Auto-Pin Creation?

In prior releases, when dragging a block's output pin, you could only connect it to a previously existing input pin.

Auto-pin Creation allows you to drag an output pin onto a Script Block and, in doing so, create a new input pin of the appropriate type as the bottommost pin on the script block.

Pins can be generated automatically even for Script Blocks that have not been initialized. Dropping a pin on such a Script Block automatically initializes the block.

Using Auto-Pin Creation by Dragging Output Pins

Use auto-pin creation by dragging an output pin to a block. A colored feedback line extends outwards toward the script block.

The new pin's name is derived from the name of the source block and the source pin, concatenating and separating with an underscore. All spaces in the name are converted to underscores. If a pin with the generated name already exists in the destination block, the smallest integer will be appended to the end of the generated name where the generated name is not yet in use.

For example, if a pin is generated from an output block named MyToolBlock and a pin named Index, the name of the newly generated pin will be MyToolBlock_Index. If a pin with this name already exists in the destination block, the name will be MyToolBlock_Index1.


Reordering Pins with the Script Definition Editor

After creating a script block, right-click on the block and select Reconfigure Script I/O. The Script Definition Editor opens.

Select arguments and move them up or down the Arguments list, using the up and down buttons.

Use the add and delete icons to add and delete selected arguments from the list.

When all arguments are ordered to your satisfaction, click Accept.


Task Trigger Modes

Task Mode

The Task Mode dialog is used to define the way that a Task is triggered. A Task has five different trigger modes, which can be set by right-clicking on the Task in the Project Explorer and selecting Task Mode.

By default, the Task is setup to execute manually when a script calls the $Tasks.{TaskName}.Run() function.

Control | Description
Manual | Specifies that the Task execution is controlled by the user. The Task can be executed by calling the Run() or RunAsync() method on the Task.
Event | Specifies that the Task should execute when the selected event occurs. A list of available events are shown in the drop down list.
Multi-Event | Specifies a set of events that must occur before the Task is executed.
Timer | Specifies that the Task should execute at a user-defined interval (milliseconds).
Continuous | Specifies that the Task should run continuously. Note: For details on the concept of a continuous task or continuous vs. manual acquisition, see the Acquiring Images - Manual Vs. Continuous topics for more information.

Enabling/Disabling a Trigger at Runtime

Hardware Acquisition Triggers


Enabling/Disabling a Trigger at Runtime

You can enable or disable the Task trigger at runtime by writing to the $Tasks.{TaskName}.TriggerEnabled tag.

This tag sets whether or not the Task should respond to the configured event, or allow the user to execute the Task manually.

Disabling Trigger Buffering While a Task is Running


Disabling Trigger Buffering While a Task is Running

To disable trigger buffering while a Task is executing:

  1. At the beginning of the Task, add a Script block with the following code:

    //Tells the task to ignore any incoming triggers from the camera
$Tasks.Task.TriggerEnabled = false;

  2. From the Project Explorer, right-click the Task and from the menu, select Script > On Complete.

    Configure the On Complete Script with the following code:

    var acqFifo = $System.GetInternalObject("Devices.Camera1") as Cognex.VisionPro.ICogAcqFifo;
if (acqFifo != null)
{
 acqFifo.Flush(); //Clear any images in the AcqFifo queue.
}
//Re-enable the task so that it responds to triggers again.
$Tasks.Task.TriggerEnabled = true;


Hardware Acquisition Triggers via an Event

Hardware Acquisition Triggers

A Camera Device can be configured to perform an acquisition by being triggered by another hardware device, such as a photoelectric sensor (aka photo eye), via either the Event or Manual setting of the Task Mode. This in turn can be used to execute a Task.

Note:

If your camera is configured to use a hardware acquisition trigger, and you are experiencing extra acquisitions or missed triggers, determine if there is noise (i.e. the signal “bounces” or “rings”) on the I/O lines. If this is occurring, either adjust the MinTriggerWidth or MinTriggerPeriod settings of the camera, or configure the DebounceDuration of the Cognex Communication Card.

For more information on the MinTriggerWidth, MinTriggerPeriod and DebounceDuration settings, reference the following topics in the VisionPro Online Documentation:

  • ICogAcqTriggerFilter.MinTriggerWidth Property
  • ICogAcqTriggerFilter.MinTriggerPeriod Property
  • CogPrio.DebounceDuration Property

Hardware Acquisition Triggers via an Event

Hardware Acquisition Manual Triggers

Performing Overlapped Acquisitions


Hardware Acquisition Triggers via an Event

A Camera Device can be configured to perform an acquisition by being triggered by another hardware device, such as a photoelectric sensor (aka photo eye), via the Event setting of the Task Mode. This in turn can be used to execute a Task.

To execute a Task when a camera is triggered via hardware:

  1. In the OnStartup script (or a User Scripts), add the following code:

    $Devices.Camera1.TriggerModel = CogAcqTriggerModelConstants.Auto;
$Tasks.Task.TriggerEnabled = true;

  2. Configure the Task Mode property of the Task:

    1. From the Project Explorer, right-click the desired Task and select Properties from the menu.

    2. In the Task Mode dialog, select Event and Devices.<CameraName>.ImageAcquired.


Hardware Acquisition Manual Triggers

A Task can be executed manually if the Camera Device is configured to acquire from a hardware trigger, and the Task Mode is set to Manual.

  1. A Button element is added on a Page.
  2. In this scenario, the Button is named "Online/Offline", and is used to acquire images via a hardware trigger while Online, and Offline would be used to manually acquire images, change acquisition settings, review past images, etc.

  3. The OnClick script of the Button is used, with the following code, so the Task can be executed manually, and the Camera block will manually acquire an image:

    $Devices.Camera1.TriggerModel = CogAcqTriggerModelConstants.Manual;
$Tasks.Task.TriggerEnabled = false;


Performing Overlapped Acquisitions

A Task can also be configured to perform overlapped acquisitions when a Camera Device is set to be triggered via a hardware device. In this scenario, the Camera will continue to acquire images while the Task is running; each image that is acquired while the Task is running will be queued in the CogAcqFifo. As soon as the Task completes its execution, it will run again, based on the next queued image. The Task will execute once for each ImageAcquire Event that has occurred.

In this scenario, it is important to ensure that the Task processing time is, on average, faster than the amount of time between images. In addition, the $Devices.<CameraName>.NumReady tag is useful in determining how many images are waiting to be processed.

Related Topics

The following topics can be referenced in the VisionPro® Online Documentation:

  • Acquiring Images with GigE Vision Cameras
  • CogAcqFifoTool Class


Web Pages

Web Pages are used to create a Human Machine Interface (HMI) user interface (UI) for Cognex Designer. These can be displayed on an Internet Web Browser (Internet Explorer version 11 and Google Chrome version 54 or later), using HTML5.

HMI gives operators the ability to visualize data (images, graphics and/or data), and interact with the vision system. Web Pages allow the application developer to create a run-time display that shows only pertinent project data.

When designing your HMI, consider what parameters should be configurable, the level of interaction the operator will be responsible for, and the layout and presentation of the interface.

Web Page

Web Page Elements

Multiple Web Pages

WebPages HMI Scripting


WebPage

A WebPage is used to build a single page of an HMI UI, using the Web Page Editor. The desired interactive elements are dragged and dropped onto the WebPage from the WebPage Toolbox, and then bound to tags (which are managed in the Tag Manager), or the element's script points are used to write custom JavaScript code for the element.

To test a WebPage, place the project in deployed mode (the WebPage does not work while in Program Mode).

Note:

  • This product supports the ability to create multiple standard Web Pages for a project, each containing their own set of HMI controls. However, only one standard Web Page may be displayed at a time. This means that when a new standard Web Page is opened, the previous Web Page will be closed. Additional Web Pages can be added as popup windows, either static or moveable, and multiple pop-up Web Pages can be added to a standard Web Page.

    For more information, see the Multiple WebPages topic.

  • There is also only one default WebPage, and this will be the WebPage that loads when the HMI is opened the first time. For more information, see the WebPage Properties topic.
  • Scripts associated with a Web Page are executed on the UI thread, and long running scripts could cause the UI to temporarily freeze.

WebHMI: Functional Overview, Compatible Types, and an Example

WebPage Right-Click Menu

Webpage Toolbar

WebPage Properties


WebHMI: Functional Overview, Compatible Types, and an Example

Using the WebHMI, you deploy applications that can be accessed with any browser connected to the machine that the application was deployed on.

This section presents:

  • Highlights of the WebHMI feature
  • What types can be hosted on Web instances, as opposed to in Cognex Designer C# applications

  • An example of a Web hosting application using WebHMI and Cognex Designer.

WebHMI Performance Considerations

  • Running a Web Server (as adding any additional system resource) adds to system workload and requires extra system resources. However, assuming enough processors are available, system performance for running Cognex DesignerTasks should not be affected. The number of clients should not affect a Task's performance, assuming CPU usage is not maximized.
  • Running a web browser on the PC where the deployed applications is executed may result in varying Task execution time. If this is of significant concern, we recommend that the WPF HMI is used for web deployment, rather than WebHMI

  • At this time, we do not recommend using WebHMI in applications where performance is of a mission critical nature. Using WebHMI may induce fluctuations in task times due to the management of extra workloads needed at random intervals.

Note: See Deploying a Cognex Designer Projectfor information regarding deployment behavior specific to WebHMI.

WebHMI: A Functional Overview

WebHMI Applications: Compatible Types

WebHMI: A WebHMI Application


WebHMI: A Functional Overview

Using WebHMI, you create a web page to host your Cognex Designer applications on internal (secured) networks.
WebHMI is not intended to be a replacement for WPF HMI.

In the case of WebHMI, the deployed application acts as the web server. Others can connect to this web server using a web browser (a web client) over the internal network, assuming necessary firewall ports have been opened on the machine where the project was deployed.

An instance of a Web Server can be prevented from starting because:

  • The port specified (in WebHMI Settings) is being used by another application.

  • Your web server instance is unregistered.

Either of these conditions may result in display of a warning page or a start-up error indicating that the web server failed to start.

Follow these procedures to ensure your Web Server instance is registered to the correct port and starts successfully.

Note: Ensure you are aware of applicable WebHMI: A Functional Overview when using WebHMI.

Register and Enable a Web Server Instance

WebHMI applications are hosted on port 80 by default.

Using the Project Settings dialog box, complete these steps to ensure proper configuration of your Web Service instance.

  1. In the left-pane Explorer, navigate to System > Settings and double-click Settings. The Project Settings dialog opens.
  2. In the Project Settings dialog, select WebHMI.
  3. Select Enable Web Server.
  4. Enter the Port number you want to host Web Services, or accept the default of Port 80.
  5. While logged-in as Administrator, click Register Port.
  6. Optionally, change the default User Directory that is selected when users work with the WebHMI interface.
  7. If finished, click Apply and OK. If you want to enable authentication, however, proceed to the steps in Enabling Authentication for WebHMI, below.

Enable Authentication and Configure Permissions

When hosting and creating Web pages and services with WebHMI, you can choose whether or not to enable authentication.

When you enable authentication, you create a secured environment that requires users to log-in with a selected user name and password when they use the WebHMI hosted application.

To define user names and passwords, along with access privileges, use the procedure below to work with the User Configuration dialog box, accessible from System > Users in the Explorer pane.

You associate each Username and Password with an integer of your choice which you enter in the CurrentAccessLevel field.

The CurrentAccessLevel field has no built-in permissions. You programmatically define permissions by using CurrentAccessLevel to enable and disable controls on web pages.

To enable authentication for a Web Server instance, do the following:

  1. Follow the steps in Enabling a Web Server by Registering/Editing Port Number, above, to open the Project Settings dialog.
  2. In the Project Settings dialog box, select Enable Built-in Authentication.
  3. Optionally, enhance security by defining an inactivity timeout setting, which specified the number of time in minutes that the WebHMI session can remain active before lock-out by the log-in dialog. To set a timeout value, do the following:
    1. Select Inactivity Timeout.
    2. Enter the timeout limit value in minutes in the (min) drop-down box, or use the arrows on the right-side of the box to advance or decrement the value by one minute.
  4. Click Apply and OK.
  5. In the left-pane Explorer, double-click System > Users to open the User Configuration dialog box.
    1. Select the Authentication Mode you want to use, either Active Directory or Standard.
    2. Define each Usernames, along with associated Passwords and CurrentAccessLevel that you want to assign to the user. After you complete each user's entry, press ENTER. A blank row will appear. When you finish adding all users, proceed to the next step.
    3. Optionally, define other fields besides CurrentAccessLevel. To do this, click Define User Properties. The User Field Editor dialog box opens. In the User Field Editor, a default field entry exists that defines CurrentAccessLevel as Data Type of Integer with a Default Value of 0. Do not delete this default field unless you plan to define another field instead of CurrentAccessLevel in the User Configuration dialog and authentication code you will create. Define any other tags you plan to work with. Use the plus icon (+) to add tags, the pencil icon to edit field values, and the X icon to delete tags. When finished, click Save to save the field entries you have defined,

Type Limitations in JavaScript Web HMI

When creating JavaScript for Web HMI, be aware that only specific types are compatible in Web HMI instances. The range of data types available in C# are not available in Web HMI.

In summary:

  • WebHMI Pages only use JavaScript
  • WPF HMI Pages only use C#
  • Tasks only use C#.

For an overview of type compatibility in Web HMI, compared to native C# applications, see WebHMI: Type Compatibility .

Displaying Records, Graphics and Tables Using WebHMI

You can host most display data or applications created with Cognex Designer on a Web Page using WebHMI. For a detailed description of these steps, see An End-to-End WebHMI Application.

  1. Register and Enable a Web Server instance using the procedure above.
  2. Optionally, enable authentication and configure permissions using the procedure above.
  3. Create an application with Cognex Designer and verify that it runs successfully in Test Mode.
  4. Using the Toolbox, create a Display, a Recorded Image Viewer instance, a Database, or a Table
  5. Bind the function, property, or query to the Display, Viewer, Database, or Table. See An End-to-End WebHMI Application.


WebHMI Applications: Compatible Types

WebHMI: Type Compatibility

WebHMI control properties can be bound to $tags of the following types:

The following can be bound from the C# Runtime to the WebHMI, and from the WebHMI to the C# Runtime.

  • Bool
  • String
  • DateTime - Note that DateTime cannot be used in a table (type of DataSet)
  • byte, sbyte, short, ushort, int, uint, long, ulong, float, double)

The following can be bound only from the C# Runtime and received by the WebHMI. The WebHMI cannot send these values to the runtime.

  • DataSet (Usually from a database query, for example $Databases.new_database.MyTable.SelectAll.DataSet )

  • TableData (Used in a listbox to bind recipe configurations and localization languages)

  • ICogImage and ICogRecord

Data Compatibility between WPF and WebHMI

As depicted in the graphic, WPF HMI can exchange any data type using the C# Runtime.

By contrast, the WebHMI clients can exchange limited data types with the runtime using JavaScript, depending on the types being passed. Web Client 1 can receive images, graphics and table data (datasets) from the runtime. Web Client 2 passes the four primitive types to the C# runtime and back.

Notice that Web Client 1 and Web Client 2 cannot directly exchange data as each is its own separate instance, unaware of the other.


WebHMI Example: Hosting a WebHMI Applications

An End-to-End WebHMI Application

Before attempting to create a WebHMI WebPage, familiarize yourself with WebHMI: Type Compatibility .

Any application you can create with Cognex Designer can be hosted on a WebHMI WebPage, providing the rules of type compatibility are followed.

To create your WebHMI application, do the following:

  1. Register and Enable a Web Server.
    1. In the left-pane Explorer, navigate to System > Settings and double-click Settings. The Project Settings dialog opens.
    2. In the Project Settings dialog, select WebHMI.
    3. Select Enable Web Server.
    4. Enter the Port number you want to host Web Services, or accept the default of Port 80.
    5. While logged-in as Administrator, click Register Port.
  2. Enable authentication for your application.
    1. In the Project Settings dialog box, select Enable Built-in Authentication.
  3. Optionally, enhance security by defining an inactivity timeout setting, which specifies the number of time in minutes that the WebHMI session remains active before lock-out by the log-in dialog. To set a timeout value, do the following. If you do not want to set a timeout value, proceed to the next step.
    1. Select Inactivity Timeout.
    2. Enter the timeout limit value in minutes in the (min) drop-down box, or use the arrows on the right-side of the box to advance or decrement the value by one minute.
  4. Click Apply and OK.
  5. Add users and configure permissions.
    1. In the left-pane Explorer, double-click System > Users to open the User Configuration dialog box.
    2. Select the Authentication Mode you want to use, either Active Directory or Standard.
    3. Define each Usernames, along with associated Passwords and CurrentAccessLevel that you want to assign to the user. After you complete each user's entry, press ENTER. A blank row will appear. When you finish adding all users, proceed to the next step.

    For information about customizing fields for use when programming security applications based on access level, see WebHMI: A Functional Overview

  6. If you haven't already done so, create an application with Cognex Designer and verify that it runs successfully in Test Mode. For this example, we'll display an image from a PatMax example created with VisionPro. Visit the Cognex Corporation Downloads page and search for Cognex Designer sample projects that use PatMax.
    1. Create a web page and add a Display object.
      1. In the left-pane Explorer, create a WebPage by double-clicking WebPages > WebPage.
      2. From the Toolbox, drag the Display block onto your WebPage. The Display object appears on your web page.

      If the Display object does not appear, verify that your Web Server registered properly on Port 80 and that Port 80 is not in use by another application.

  7. Bind the Display object to the Image(vprorecord) created by the PatMax application.
    1. Select the Display object on your WebPage.
    2. In the Properties pane, in Frequently Used > Source, click the double-arrow icon. The Expression Builder opens.

    3. In the Expression Builder, click Tag Selector.
    4. Navigate to your Camera or Image File device and select the Image(vprorecord) tag. Click Accept.
    5. In the Expression Builder, click OK.
    6. On the Cognex Designer menu, click Project > Start Test Mode.

    The image bound to tag Image(vprorecord) is displayed on the WebPage in the Display object.


WebPage Right-Click Menu

WebPage Right-Click Menu provide shortcuts to executing multiple, complex command as well as eliminating the need to create scripts in order to call a single $ Functions: WebPages HMI

 Edit: Opens the highlighted WebPage in the Web Page Editor.
Export: The highlighted WebPage will be exported as a Template. See the Exporting Items topic for more information.
Protect: Applies password protection to the highlighted WebPage. See the Project Component Password Protection topic for more information.
Delete: Removes the highlighted WebPage from the project. This action cannot be undone.
Rename: Renames the highlighted WebPage. Any references to the WebPage in scripts will need to be updated after the rename operation.
Properties: Opens the WebPage Properties.
Scripts: Provides access to the two event scripts, OnShow and OnHide, associated with the highlighted WebPage.


Webpage Toolbar

WebPage Editor Toolbar

The Web Page Editor toolbar allow single-click access to common actions such as aligning elements or bringing selected elements to the front. The toolbar actions are also accessible through the Edit menu.

Note:
  • The WebPage toolbar can be customized by moving and resizing it.
  • Icons will appear grayed out when their corresponding functions are not available in the current context.
WebPage Toolbar
Undo

Undo the last action.
Redo

Redo the last action.
Delete | Deletes the selected elements.
Cut | Cut the selected elements. Often used in conjunction with Paste.
Copy

Copy the selected elements or files to the clipboard. Often used in conjunction with Paste.
Paste

Paste elements that were cut or copied.
Lock | Toggle lock/ unlock selected elements in place.
Export | Export the current WebPage as a template.
Replace Tags | Opens the Replace Tags dialog window. Replaces the tags of a selected control element.
Equal Horizontal | Aligns equal horizontal spacing between three or more selected elements.
Equal Vertical | Aligns equal vertical spacing between three or more selected elements.
Remove Horizontal | Removes horizontal spacing between selected items.
Remove Vertical | Removes vertical spacing between selected items.
Equal Sizes | Makes two or more elements equal in size to the first element selected.
Equal Heights | Makes two or more elements equal in height to the first element selected.
Equal Widths | Makes two or more elements equal in width to the first element selected.
Send to Back | Changes Z-Order of an element - sends element to the back.
Send Backwards | Changes Z-Order of an element - sends element backwards one index position.
Bring Forward | Changes Z-Order of an element - sends element forward.
Bring to Front | Changes Z-Order of an element - sends element to the front.
Group Controls

Groups multiple elements together.

Note:
  • When multiple elements are grouped together, their individual element Properties are no longer accessible. Instead, they are replaced by Group Properties, which allows you to specify a name for the Group, and X and Y coordinate values of the grouped elements.
  • To adjust and edit the Properties of individual elements in a Group, first double-click the Group, then select individual elements to adjust their Properties. Press the ESC key to complete the edits.
  • When an element with a published property tag is placed in a Group, the path name of the element changes to include the name of the Group. For example, WebPages.WebPageName.GroupName.SelectionBoxName.Content. For a full list of elements with published properties, see the WebPages Element Property Tags topic.
Ungroup Controls

Undoes the binding of a Group of elements.

Note: When elements with a published property tag are in a Group and are then ungrouped, the element's name will be changed. For example, WebPages.WebPageName.GroupName.SelectionBoxName.Content becomes WebPages.WebPageName.SelectionBoxName.Content
Align Left | Aligns two or more elements along the left edge.
Align Right | Aligns two or more elements along the right edge.
Align Top | Aligns two or more elements along the top edge.
Align Bottom | Aligns two or more elements along the bottom edge.
Align Center | Aligns two or more elements along the vertical center line.
Align Middle | Aligns two or more elements along the horizontal middle line.
Toggle Grid

Turns on a grid overlay to help with positioning and layout of elements on the page.

Note: The Toggle Grid option applies to all WebPage Editor tabs in the IDE. For example, if there are multiple WebPage Editor tabs in the project (WebPage, WebPage1, WebPage2, etc.), when Toggle Grid is activated for one WebPage Editor tab, it will be activated for all of the WebPage Editor tabs.


WebPage Properties

The WebPage Properties are used to control how the HMI UI is displayed (their size and position), its appearance, and whether or not it will be displayed on start-up. To set the Properties, right-click on the WebPage in the Project Explorer.

Each WebPage can be accessed through the following tag: $WebPages.[WebPageName].[TitleName]

Page Properties | Description
Size
Width | Defines the width of the displayed WebPage.
Height | Defines the height of the displayed WebPage.
Appearance
Title | Defines the name that will be displayed in the browser's tab when the WebPage is open. When the title is left blank, the default name of the WebPage (as defined in the Project Explorer) will be displayed. Unlike the WebPage name, the Title does not have to be unique, and can contain spaces and special characters.
Background | Defines the background color of the WebPage.
Border Color | Defines the border color of the WebPage.
Border Size | Defines the size of the WebPage border. Set to 0 to turn off the border.
Behavior
Mode

Defines how the WebPage will be displayed:

Mode | Description
Standard | Defines the WebPage as a standard browser page. Note: The Mode setting is disabled when a WebPage is enabled as a Startup Page.
Popup | Defines the WebPage as a stationary popup window. When selected, the WebPage will be displayed on top of the standard page. If a popup page is open, and a new popup page is opened, the previously open popup page will be closed. Note: The default WebPage cannot be set as a Popup.
Moveable Popup | Defines the WebPage as a movable popup window. When selected, the WebPage will be displayed on top of the standard page. If a popup page is open, and a new popup page is opened, the previously open popup page will be closed. Note: The default WebPage cannot be set as a Moveable Popup.
Fit to screen

Defines whether or not the WebPage should be displayed at its defined Width and Height, or if it should fit in the size of the browser.

Note: When the Mode is set to Popup, this option is disabled.
Startup Page

Defines whether or not the WebPage will be the default startup WebPage (by default, the Mode is set to Standard). Only one WebPage can be configured as the Startup Page.

Note: The Mode setting is disabled when a WebPage is enabled as a Startup Page.

Binding Properties

WebPages Element Property Tags


Binding Properties

Bindings are used to animate a Web Page, and are created between a project tag and a parameter of the interactive Web Page element. For example, using a Label to display the value of a numeric variable.

When an element is selected in the Web Page, the element's parameters are displayed in the Properties window. If a parameter has an arrow ( [image]) icon beside it, it can be bound to a tag. Once bound, the icon will change to indicate whether the binding flows only one direction (into the element Property) or both ways (into and from the element Property).

The [image] icon indicates a one-way binding. These generally refer to bindings between an expression or an association, where the value of the expression and/or association will be written into the Property.

The [image] icon indicates a two-way binding. These generally refer to bindings to a tag, where the value is written into the Property, and the value will also update the value of the tag. For example, if you have a CheckBox element and the Checked Property is bound to a tag, when the project is in deployed mode and the CheckBox is checked or unchecked by a user, the tag's value will be updated based on the user interaction. When the project exits deployed mode, the tag will display the state of its last interaction, i.e. if it was checked, it will display True.

  1. Click on the [image] icon to launch the Expression Builder.

  2. Use the Expression Builder to create an expression that is connected to the element property. Once the expression has been created, the [image] icon will change to either [image] or [image], depending on the type of binding.

    Note:
    • During development of a project, if a binding has become invalid, it will change to: . A binding can become invalid if a Property was bound to a tag, and that tag is deleted. For example, if an element's Border Size Property was bound to a tag with an integer data type, and the tag is deleted, the binding icon will indicate that the binding is no longer working.
    • If a binding becomes invalid while in deployed mode, a warning message will be displayed in the Output window.

  3. When Cognex Designer is running, changes in the expression will update the Web Page control, and for some input controls, updating the Web Page control will cause the expression to update.

    Note: Expressions associated with an element's bindings remain functional even when the control is disabled. This is a conventional way to display read-only data. If you would like to disable your expression at the same time the control itself is disabled, plan your expression accordingly. For example, create a Boolean tag which gives back True when the control is enabled and False when the control is disabled and use it in an if statement with your expression, or move the expression to a script and manage when it is run from there. For more information, see the Binding Visibility To Tags topic.

Binding Associations

Binding Visibility To Tags


Binding Associations

Binding Associations are used when there is no direct way of converting a tag value to a property, i.e. converting a Boolean value to a color. Associations allow you to create a mapping table that specifies the value to use for a given tag. Associations can also be used to convert from an integer to a color, a Boolean to a string, and/or a string to a color.

For example, a Rectangle can be added to a Web Page, and its Line Color parameter could be set as an association to a Boolean result, where False would indicate Red and True would indicate Green.

  1. To create an association, add a Rectangle to the Web Page.
  2. In the Rectangle Properties, click the beside [image] the Line Color parameter to launch the Expression Builder.

  3. Press the Tag button.

  4. Select a tag that returns a Boolean result.

  5. Press the Associations button to create the conversion association.

  6. This will launch the Binding Associations dialog.

  7. Uncheck the checkbox, and from the color drop-down menu, select Red for False, then press the Add button.

  8. Check the checkbox, and from the color drop-down menu, select Green for True, then press the Add button.

  9. Press the Accept button to complete the association.

  10. Put the Page in deployed mode, and the Rectangle's Line Color should be Green when the result returns True, and Red when it returns False.


Binding Visibility To Tags

The standard way to control visibility of Web Page elements is to create tags and use the Visible property of the elements.

Note: Dynamically creating controls is not supported.

For example, on a Web Page, there is a Data Inputs On/Off CheckBox and a collection of Numeric Entry elements that are used to adjust values.

The Numeric Entry elements should disappear when the CheckBox is unchecked.

  1. Add a CheckBox and Numeric Entry elements that you want to hide.

  2. In the Tag Manager, create a tag called hidden.controls; it should be Boolean type, set to True by default (in this example Truemakes the element visible).

  3. Select a Numeric Entry element and bind its Visible property to hidden.controls.

    1. Click the [image] next to Visible.

    2. In the Expression Builder, bind the property to $hidden.controls and then click OK.

    3. The [image] icon indicates that the Visible property is now bound to $hidden.controls.

  4. Select your CheckBox and select On Changed from the Properties.

  5. In the CheckBox.change script, enter the following: $hidden.controls = !$hidden.controls;

  6. To test that it works, put your project in deployed mode, and uncheck the CheckBox; the Numeric Entry elements should disappear when unchecked.


WebPage Elements

Each WebPage is composed of different elements, which are dragged and dropped onto the WebPage from the WebPage Toolbox or from the Template Browser. Configure each element by setting its Properties. The element Properties are grouped into categories, and the most commonly configured Properties are listed at the top, in the Frequently Used section.

Once an element or multiple elements have been placed on the WebPage, you can interact with them by using either the WebPage Editor Toolbar or the WebPage element right-click menu. Simply select the element, then choose an option.

Note: Multiple elements can be selected by either holding down the Ctrl key and clicking on the desired elements, or clicking on an empty area of the WebPage and dragging the mouse over the desired elements.

Charts

Controls

Graphics


Charts

The Charts elements are used to display data from a project in a Bar Chart, Pie Chart or Trend Chart.

The Bar, Pie and Trend Charts share the following Properties:

  • Content Property

    This is used to pass the data that will be used to chart. The property must be set to a DataSet Data Type, either through binding the Content property to a DataSet tag or WebPage Elements Event Handler Scripts. When the data is updated, the chart will be re-evaluated and redrawn.

    Note: See the WebPages HMI Scripting topic for information regarding the differences between using the DataSet as a tag or as an Event Handler script.

  • Show Legends

    Determines whether or not the chart legends will be displayed with the chart. When enabled (by default it is enabled), while the project is in deployed mode, if a user hovers over the chart with a mouse, the legend will display information about the chart in relation to the placement of the mouse, as shown below.

    Chart in deployed mode

  • Visible Columns

    Determines which columns will be displayed in the chart. By leaving this property blank, all the available columns in the DataSet will be displayed by default.

    To select specific columns to be displayed, enter the column name. If adding multiple columns, a semicolon must be placed between each column name (e.g. X ; Y ; Height ; Width).

Chart Description
Bar

The Bar Chart is used to display comparisons between categories of data.

The Bar Chart includes the following Chart specific Properties:

Property Description
X Axis Column

Specifies the X axis column name (as a String data type) by referencing a column of the DataSet that should be used as the X axis markers. Enter the name of the column from the referenced DataSet. When a column of the DataSet is configured as the X axis, that column will no longer be a part of the chart data.

Note: If a name is not specified, a series of numbers will be generated.
X Axis Label

Specifies a descriptive name that will be displayed on the chart's X axis.
X Axis Label Visible

Specifies whether or not the X Axis Label is displayed. This property value is a Boolean data type.
Y Axis Label

Specifies a descriptive name that will be displayed on the chart's Y axis.
Y Axis Label Visible

Specifies whether or not the Y Axis Label is displayed. This property value is a Boolean data type.
Y Range Max

Specifies the maximum value (as a Double data type) for the chart's range. This property allows you to restrict the visible range of the chart, even if some of the values may not fall within the range defined by the Max and Min values.
Y Range Max Enabled

Specifies whether or not the Y Range Max property value (Boolean data type) is used to establish the maximum limitation for the chart. When it is enabled (by default, it is disabled), the Y range maximum will be established by the Y Range Max property value.

Note: If either of the Y Range Max Enabled or Y Range Min Enabled properties are enabled, the Y Range Max and Y Range Min property values will be used.
Y Range Min

Specifies the minimum value (as a Double data type) for the chart's range. This property allows you to restrict the visible range of the chart, even if some of the values may not fall within the range defined by the Max and Min values.
Y Range Min Enabled

Specifies whether or not the Y Range Min property value (Boolean data type) is used to establish the minimum limitation for the chart. When it is enabled (by default, it is disabled), the Y range minimum will be established by the Y Range Min property value.

Note: If either of the Y Range Max Enabled or Y Range Min Enabled properties are enabled, the Y Range Max and Y Range Min property values will be used.
Pie

The Pie Chart is used to display a numerical proportions of data in a circular representation. The values in the Pie Chart are aggregated values of referenced DataSet columns; it presents a visual representation of the ratio between values. The values are generated by adding and summing all the items in a DataSet column, and then presenting a ratio of those values.

The Pie Chart only includes the two common Chart Properties, Show Legends and Visible Columns.
Trend

The Trend Chart is used to display trends in data over time.

The Trend Chart includes the following Chart specific Properties:

Property Description
Enable Lower Region

Specifies whether or not the lower boundary in the chart is enabled (this property value is a Boolean data type). This can be useful to visually determine a range of values that are incorrect.
Enable Upper Region

Specifies whether or not the upper boundary in the chart is enabled (this property value is a Boolean data type). This can be useful to visually determine a range of values that are incorrect.
High Region Divider Caption

Specifies a description (as a String data type) that will appear on the Upper Region of the chart; by default, it is set to "Perfect Score"). This can be useful to describe what the values falling in this range represent.

Lines Enabled

Specifies whether or not the lines for the Lower Region and Upper Region will be drawn on the chart (this property value is a Boolean data type). This also controls whether or not the captions will be displayed, and the center line will be drawn.
Low Region Divider Caption

Specifies a description (as a String data type) that will appear on the Lower Region of the chart; by default, it is set to "0 Score"). This can be useful to describe what the values falling in this range represent.

Lower Bound

Specifies the value (as a Double data type) that defines the low range of the chart begins.
Upper Bound

Specifies the value (as a Double data type) that defines the high range of the chart begins.
X Axis Column

Specifies the X axis column name (as a String data type) by referencing a column of the DataSet that should be used as the X axis markers. Enter the name of the column from the referenced DataSet. When a column of the DataSet is configured as the X axis, that column will no longer be a part of the chart data.

Note: If a name is not specified, a series of numbers will be generated.
X Axis Label

Specifies a descriptive name that will be displayed on the chart's X axis.
X Axis Label Visible

Specifies whether or not the X Axis Label is displayed. This property value is a Boolean data type.
Y Axis Label

Specifies a descriptive name that will be displayed on the chart's Y axis.
Y Axis Label Visible

Specifies whether or not the Y Axis Label is displayed. This property value is a Boolean data type.
Y Range Max

Specifies the maximum value (as a Double data type) for the chart's range. This property allows you to restrict the visible range of the chart, even if some of the values may not fall within the range defined by the Max and Min values.
Y Range Max Enabled

Specifies whether or not the Y Range Max property value (Boolean data type) is used to establish the maximum limitation for the chart. When it is enabled (by default, it is disabled), the Y range maximum will be established by the Y Range Max property value.

Note: If either of the Y Range Max Enabled or Y Range Min Enabled properties are enabled, the Y Range Max and Y Range Min property values will be used.
Y Range Min

Specifies the minimum value (as a Double data type) for the chart's range. This property allows you to restrict the visible range of the chart, even if some of the values may not fall within the range defined by the Max and Min values.
Y Range Min Enabled

Specifies whether or not the Y Range Min property value (Boolean data type) is used to establish the minimum limitation for the chart. When it is enabled (by default, it is disabled), the Y range minimum will be established by the Y Range Min property value.

Note: If either of the Y Range Max Enabled or Y Range Min Enabled properties are enabled, the Y Range Max and Y Range Min property values will be used.


Controls

The WebPage Controls are used to insert interactive HMI elements.

Note:

All of the Controls elements have these Event handler script points (a few Controls elements have additional Event handler script points, which are indicated in their description):

  • On Mouse Enter
  • On Mouse Leave
  • On Mouse Move

For more information about the Event handler script points, see the WebPage Elements Event Handler Scripts topic.

Element | Description
Button

The Button element is used for such actions as jumping to another WebPage, causing a Task to run, interacting with region graphics, or a Button function.

The Button Properties include the Click Command property, which provides a pre-defined list of available actions to which to bind the press of the Button.

Note: For more information, see the Button Click Command Property topic.

The Button element has one additional Event handler script point:

  • On Clicked
Note: The On Clicked script point will execute every time a user presses the Button. If both the Click Command and On Clicked script point are set, the Click Command has precedence, and will execute before the On Clicked script.
CheckBox

The CheckBox element contains an interactive checkbox and a label beside the checkbox. To configure the appearance and placement of the label, use the Properties in the Text section (the Text Padding property determines the amount of spacing between the checkbox and the text).

The CheckBox element also has three additional Event handler script points:

  • On Changed
  • On Checked
  • On Unchecked
DataTable

The DataTable element provides a read-only table for displaying tabular data. The Content property can be set to a DataSet Data Type tag, allowing tabular data to be displayed during deployed mode.

The DataTable element has three additional Event handler script points:

  • On Data Change
  • On Mouse Up
  • On Mouse Down
DateTime Entry

The DateTime Entry element provides a means to show and/or enter a date and/or time via the HMI.

The DateTime Entry element has one additional Event handler script point:

  • On Changed
FormattedLabel

The FormattedLabel element is used to add text to your project. While in Program Mode, the FormattedLabel element provides an HTML5 text editor to format the text in the element. Simply double-click the element and begin adding text (you can either type and format directly in the element, or copy and paste the content from another word processing application).

This element can be used to add instructions or details about your project. The Text property can be bound to a tag, which can then be updated based on another part of the project, such as a User Script.

While in deployed mode, the FormattedLabel element is read-only.

Note:
  • If formatted text is copied and pasted from another word processing application into the FormattedLabel element, the formatting that was applied in the other application may or may not be preserved.
  • The FormattedLabel element does not have any Event handler script points.
Image | Inserts a display for a static image, such as a logo or graphic, which is added through the Resources option. Set the Source property to the Resource.
Label

Inserts a control for displaying text.

The Label element also has two additional Event handler script points:

  • On Mouse Up
  • On Mouse Down
ListBox

Inserts a control for displaying and interacting with a table of data.

The ListBox element also has three additional Event handler script points:

  • On Selection Changed
  • On Mouse Up
  • On Mouse Down
MultilineTextBox

Inserts a control for entering multiple lines of text. The Text property can be bound to a tag, which can then be updated based on another part of the project, such as a User Script.

The MultilineTextBox element has three additional Event handler script points:

  • On Text Change
  • On Mouse Up
  • On Mouse Down
Note: The Multiline TextBox element does not support the input of a password during deployed mode. You must use a TextBox for that capability.
MultiStatus

Inserts a control for graphically displaying the status of an Integer value of another WebPage Controls element, or an Integer Tag in the project, that is bound to the element's Value property. This element can be used to represent a binary representation of an Integer value, a history of results or the states of the Precision I/O lines in a project.

The MultiStatus element has three additional Event handler script points:

  • On Value Change
  • On Mouse Down
  • On Mouse Up

The MultiStatus control's numbering is zero-based, and you can define the first bit to be displayed by setting the Start Bit (default is 0). The control determines the order of the displayed bits by first applying the Start Bit property, and then the value of the Reverse Order property.

The following illustration indicates how the control's settings can be used to display different bit values:
Numeric Entry

Inserts a control for entering numeric values; the values can be entered directly, or use the up and/or down arrows.

The NumericEntry element also has an additional Event handler script point:

  • On Value Change
Panel

Inserts a panel that can be used to place other HMI elements on top of, which can be used to help visually organize elements and act as a container for multiple elements.

Note:
  • If the Enable property of the Panel is disabled (unchecked), all of the elements on the Panel will also be disabled.
  • When an element with a published property tag is placed on a Panel, the path name of the element changes to include the name of the Panel. For example, WebPages.WebPageName.PanelName.CheckboxName.Checked.
ProgressBar

Inserts a control to display the progress of a process, by selecting a user-defined Minimum and Maximum (starting and end points) properties, and the Value property to monitor. These properties can either be bound to tags or hard-coded. The progress of the value is determined based on the ratio of the Value property to the Minimum and Maximum properties (starting and end points).

Note: The ProgressBar element does not have any Event handler script points.
RadioButton

Inserts an interactive two-state button that can be either checked or unchecked, and a label beside the button. To configure the appearance and placement of the label, use the Properties in the Text section (the Text Padding property determines the amount of spacing between the button and the text).

The RadioButton element also has three additional Event handler script points:

  • On Changed
  • On Checked
  • On Unchecked
SelectionBox

Inserts a drop-down list control.

The SelectionBox element also has three additional Event handler script points:

  • On Selection Changed
  • On Mouse Up
  • On Mouse Down
Slider

Inserts an interactive numerical value selector control, which allows users to graphically select a numerical value by sliding a control to the desired value.

The Slider element has one additional Event handler script point:

  • On Value Change
Status

Inserts a control to graphically display the status of an integer value in the project, by binding the Value property to either a Tag or another value in the project. In addition, text, colors and icons can be added to help define the status being displayed.

When monitoring the Value:

  • > 0 = Positive
  • 0 = Zero
  • < 0 = Negative

The Status element has three additional Event handler script points:

  • On Value Change
  • On Mouse Down
  • On Mouse Up
TextBox

Inserts a control for entering text. The Text property can be bound to a tag, which can then be updated based on another part of the project, such as a User Script.

The Password property can be enabled to transform the TextBox into a password entry TextBox, where the characters will be replaced with asterisks.

The TextBox element has three additional Event handler script points:

  • On Text Change
  • On Mouse Up
  • On Mouse Down

Button Click Command Property


Button Click Command Property

Assigning the Click Command property defines the action that will be taken when the Button is pressed during deployed mode. When the Button element is added, the selected Click Command property enables different configurable properties, depending on the different elements on the WebPage and the desired actions.

Button Click Command - Devices

Button Click Command - HMI

Button Click Command - System

Button Click Command - Tasks

Button Click Command - User Scripts

Button Click Command - WebPages


Button Click Command - Devices

The Click Command property can be associated with the following Devices interaction:

Note:
  • These interactions can also be called via a script. For more information, see the WebPages HMI $ Functions topics.
  • See $ Functions: Devices for more information on the Devices function listed below.
Click Command Description Arguments (with Data Type) Return Type
Devices.CameraName.FlushImages

Removes all images from the controller image buffer of the selected camera (specified with CameraName), preventing queued images from being returned by the subsequent executions of corresponding Acquire blocks assigned to CameraName.

Note:
  • If the Trigger Mode of CameraName is set to Internal, then the next execution of the Aquire block will trigger a new image on the camera.
  • If the Trigger Mode is set to Camera, FFP or some precision IO event, then calling this function discards images that may have been acquired but not yet consumed by any Acquire blocks.

N/A

 N/A


Button Click Command - HMI

The Click Command property can be associated with the following HMI interactions:

Note: These interactions can also be called via a script. For more information, see the WebPages HMI $ Functions topics.
Click Command | Description | Arguments (with Data Type)
HMI.CloseDialogPage

Closes the active dialog page.

 N/A

HMI.GetControlProperty

Fetches the specified property of the specified control element.

Note: Cognex recommends using the published property, when available, instead of using this command.
  • controlname: String, specifying the name of the control element.
  • propertyname: String, specifying the name of the property.
HMI.GetPageBackgroundColor | Fetches the background color the webpage specified with the "pageName" argument. | "pageName": The name of the webpage, specified as a string.
HMI.GetPageBorderColor | Fetches the border color of the webpage specified with the "pageName" argument. | "pageName": The name of the webpage, specified as a string.
HMI.GetPageHeight | Fetches the height of the webpage specified with the "pageName" argument. | "pageName": The name of the webpage, specified as a string.
HMI.GetPageTitle | Fetches the title of the webpage specified with the "pageName" argument. | "pageName": The name of the webpage, specified as a string.
HMI.GetPageWidth | Fetches the width of the webpage specified with the "pageName" argument. | "pageName": The name of the webpage, specified as a string.
HMI.Login

Logs in to the HMI webpage with the specified username and password.
  • username: String, specifying the name of the user used for login.
  • password: String, specifying the password of the user used for login.
HMI.Logout

Logs out of the HMI webpage.

 N/A

HMI.SetControlProperty

Sets the property (specified with the propertyName argument) of the control element (specified with the controlName argument) to a new value (provided with the newValue argument).

Note: Cognex recommends using the published property, when available, instead of using this command.
  • controlName: String, specifying the name of the control element.
  • propertyName: String, specifying the name of the property to set.
  • newValue: Integer, double, boolean or string, specifying the new value of the property to set.
HMI.SetFocusOn

Sets the focus on the control element specified with the controlName argument.

controlName: String, specifying the name of the control element to focus.
HMI.ShowError

Shows the error specified with the message and title arguments.
  • message: String, specifying the text of the error to show.
  • title: String, specifying the title of the error to show.
HMI.ShowInformation

Shows the information message specified with the message and title arguments.
  • message: String, specifying the text of the message to show.
  • title: String, specifying the title of the message to show.
HMI.ShowLogin

Shows the login process.

 N/A
HMI.ShowMessage

Shows the message specified with the message argument.

message: String, specifying the message to show.
HMI.ShowPage

Shows the page specified with the pageName argument.

pageName: String, specifying the name of the web page to show.
HMI.ShowQuestion

Shows the question specified with the message and title arguments.
  • message: String, specifying the text of the question to show.
  • title: String, specifying the title of the question to show.


Button Click Command - System

The Click Command property can be associated with the following System interactions:

Note:
  • These interactions can also be called via a script. For more information, see the WebPages HMI $ Functions topics.
  • See $ Functions: System for more information on the System functions listed below.
Click Command Description Arguments (with Data Type) Return Type
System.DateTime.GetNtpEnabled

Checks if NTP servers are used to set the system time.

 N/A Boolean value, returning true if NTP servers are used to set the system time.
System.DateTime.GetNtpServers Fetches the list of NTP servers configured for use. N/A

Array of strings, listing the configured NTP servers.
System.DateTime.GetNtpUseDhcp

Checks if DHCP is used to locate NTP servers that are used to set the system time.

 N/A

Boolean, returning true if DHCP is used to locate NTP servers.
System.DateTime.GetSupportedTimeZones Returns a list of timezones supported. The contents of the returned list depend on the value of the tzFilter argument.

tzFilter: Hexadecimal number, specifying the filter used to fetch the list of timezones. Its available values are as follows:

  • 0x01: List popular timezones.
  • 0xFFFFFFFF: List all supported timezones.

Array of strings, listing the timezones supported by the system.
System.DateTime.GetTimeZone

Returns the timezone setting.

 N/A

String indicating the current timezone.
System.DateTime.Now

Returns the current date, stored as milliseconds since 1970 in UTC.

 N/A

Date, indicating the current date stored as milliseconds since 1970 in UTC.

Note: This is the same internal representation that is used by the javascript Date object.
System.DateTime.SetNtpEnabled

Enables or disables the usage of NTP servers to configure the system time.

 enabled: Boolean, can be true or false. True enables the usage of NTP servers. N/A
System.DateTime.SetNtpServers

Sets the list of NTP servers used by the system to configure date and time.

servers: Array of strings, specifying the IP address or URL of the configured NTP server(s).

 N/A
System.DateTime.SetNtpUseDhcp

Sets whether DHCP is used to locate NTP servers that are used to set the system time.

enabled: Boolean, can be true or false. True enables the usage of DHCP.

 N/A
System.DateTime.SetSystemClock

Sets the current date.

zone: The date, stored as milliseconds since 1970 in UTC.

Note: This is the same internal representation that is used by the javascript Date object.
 N/A
System.DateTime.SetTimeZone

Sets the specified timezone to be used.

date: String, specifying the name of the configured timezone (as listed in the list of timezones).

 N/A
System.GetUpTimeMilliseconds

Returns the uptime in milliseconds (but with microsecond accuracy).

 N/A

Double, indicating controller uptime in milliseconds (but with microsecond accuracy, hence the fract-digits).
System.Log.Write

Records a log message, which is read and displayed by the output window dialog of Cognex Designer. The recorded log - presuming Cognex Designer is running - will be recorded to the system log output file as well, available in the following location by default:
  • message : String, specifying the log message to record.
  • logLevel : Integer, specifying the severity of the log message. Its value must be between 0-3, corresponding to the following severity levels:
    • 0: Verbose
    • 1: Info
    • 2: Warning
    • 3: Error
    Note: Log messages set to Verbose severity (that is, 0) will not be shown in the Cognex Designer system log.
 N/A


Button Click Command - Tasks

The Click Command property can be associated with the following Tasks interactions:

Note:
  • These interactions can also be called via a script. For more information, see the WebPages HMI $ Functions topics.
  • See $ Functions: Tasks for more information on the Tasks functions listed below.
  • The Tasks.Task.RunBlocks $ function cannot be used with the Click Command property, but can be used with WebPage Elements Event Handler Scripts
Click Command | Description | Arguments (with Data Type) | Return Type
Tasks.TaskName.Run()

Executes the Task specified by the TaskName argument.

N/A

 N/A
$Tasks.TaskName.RunBlocksFromTo("fromBlock", "toBlock")

Specifies the execution of specific Task Blocks within the Task, with a starting Task Block (specified with the fromBlockName argument) and an ending block (specified with the toBlockName argument). With this option, the starting block and all blocks between the starting block and the ending block are executed. Blocks to the left of the starting block and blocks to the right of the ending block will not be executed.
  • fromBlock: String, specifying the "name" of the specified Task Block to start the execution within the Task.
  • toBlock: String, specifying the "name" of the specified Task Block at which to end the execution within the Task.
 N/A
$Tasks.TaskName.RunBlocksToEnd("fromBlock") | Specifies a Task Block (with the fromBlock argument) that will be the starting point of the execution of the Task. The Task Block specified by fromBlock and all the blocks to its right will be executed. | fromBlock: String, specifying the "name" of the specified Task Block to start the execution of the Task. | N/A
Tasks.TaskName.RunSingleBlock("singleBlock") | Executes a Task Block (specified with the singleBlock argument) within the Task. | singleBlock: String, specifying the "name" of the specified Task Block within the Task to execute. | N/A


Button Click Command - User Scripts

The Click Command property can also be associated with User Scripts configured for the vision project. This is useful for code that is used to interact with components and/or perform executable operations.

Note: If the project has any user scripts listed in the Scripting -> User Scripts node of the Project Explorer window, they will also be listed in the Click Command drop-down list in alphabetical order, among the default Button Click Command - Devices, Button Click Command - HMI, Button Click Command - System, Button Click Command - Tasks, and Button Click Command - WebPages functions.


Button Click Command - WebPages

The Click Command property can be associated with the following WebPages elements, allowing you to interact with the image and/or elements:

Note:
  • To enable these interactions, a Display or Recorded Image Viewer element must be on the WebPage.
  • These interactions can also be called via a script. For more information, see the WebPages HMI $ Functions topics.
Click Command | Description | Property Parameters (with Data Type)
WebPages.WebPage.Display.Pan | Provides the ability to move the image horizontally and vertically. X and Y coordinates can be specified. | x: Double, y: Double
WebPages.WebPage.Display.PanTo | Provides the ability to move to a specific pixel location, horizontally and vertically, within the image. X and Y coordinates can be specified; the center of the graphic will be at the specified coordinates. | x: Double, y: Double
WebPages.WebPage.Display.Rotate90CCW | Rotates the image 90° counter-clockwise. | N/A
WebPages.WebPage.Display.Rotate90CW | Rotates the image 90° clockwise. | N/A
WebPages.WebPage.Display.ZoomIn | Provides the ability to zoom in the image. | N/A
WebPages.WebPage.Display.ZoomOut | Provides the ability to zoom out of the image. | N/A
WebPages.WebPage.Display.ZoomToFill | Provides an automatic scaling option to scale the image will fill the entire display area. | N/A
WebPages.WebPage.Display.ZoomToFit | Provides an automatic scaling option to scale the image as large as possible, while still displaying the entire image. If the aspect ratio of the display area differs from the image, this option will result in either horizontal or vertical blank areas within the display. | N/A
WebPages.WebPage.Display.ZoomToFixed | Provides a manual scaling mode option in which the scale factor between the image and display is fixed, independent of the display size. | N/A
WebPages.WebPage.RecordedImageViewer.NextImage | Moves the selection to the next image in the File Selector list of the Recorded Image Viewer. | N/A
WebPages.WebPage.RecordedImageViewer.PreviousImage | Moves the selection to the previous image in the File Selector list of the Recorded Image Viewer. | N/A
WebPages.WebPage.RecordedImageViewer.Refresh | Reloads all images from the directory specified in the Directory property of the Recorded Image Viewer. | N/A


Graphics

The Graphics elements are used to insert ellipses, lines and/or rectangles onto a Web Page.

Note: See the Binding Associations topic for information about incorporating these elements into a Web Page.
Element | Description
Ellipse | This inserts an ellipse onto the Web Page.
Line | This inserts a line onto the Web Page. Arrowhead adornments can be added by checking the Begin Arrow and/or End Arrow checkboxes, and the size of the arrowheads can be modified by adjusting the Line Width property. Note: The Line does not have any script points.
Rectangle | This inserts a rectangle onto the Web Page.


Multiple WebPages

When creating an HMI for your project, you can add several Web Pages to ease navigation and group elements in logical sequences.

For example:

  • A "master" WebPage, with links to all the subsequent Web Pages for different steps of the inspection and/or configuration.
  • A "settings" WebPage. This pop-up can be launched via a Button element, then you can configure the settings and close the pop-up when you are finished.
  • A custom logon WebPage, where access to controls and settings can be controlled via a pop-up.
  • An "alert" pop-up WebPage, for instances where a setting or control is in an error state. For instance, with a Data Change Scripts (WebHMI) configured for a tag (e.g. $isError), in which if $isError is set to True, a warning pop-up would be displayed.

Navigating Multiple WebPages


Navigating Multiple WebPages

For projects with multiple WebPages, a Button and/or a SelectionBox element can be added to navigate between the Web Pages.

  • Button

    The Button element is the simplest method for navigating between multiple WebPages.

    1. Add a Button to a WebPage and set the Click Command property to HMI.ShowPage.
    2. This will automatically add the pageName property; set it to the name of the WebPage to be displayed.
    3. Add a descriptive name to the Text property.

  • SelectionBox

    For projects with several WebPages, the SelectionBox provides a drop-down menu which can be used to easily select the desired WebPage.

    1. Add a SelectionBox to a WebPage.
    2. Write a simple script for the On Selection Changed script point; e.g. $HMI.ShowPage($WebPages.[WebPageName].SelectionBox.Value).

    3. Configure the Content property.

      1. Click on the ... button in the Content property, which will launch the List Editor dialog.
      2. The Name column contains the name that will be displayed in the drop-down menu.
      3. The Value column contains the name of the WebPage.


WebPages HMI Scripting

The WebPages HMI scripting is based on JavaScript and supports HTML5.

WebPage HMI scripting is composed using the Script Editor, and has the following characteristics:

  • Executes in a Web browser, and only execute when the project is in deployed mode.
  • Tags are stored at the beginning of the script; if the tag value is updated by another component of the system while the WebPage HMI script is being executed, that change will not affect the tag’s value within the WebPage HMI script. After the WebPage HMI script completes, the updated tag value will be written back to the tag, and will overwrite any other changes to the tag while the WebPage HMI script was executing.

  • The execution of $ Functions and the updating of tags within WebPage HMI scripts are asynchronous to the Cognex Designer project. For processes that are tied to controlling parts of the application, bundle the commands in scripts that execute on the controller, such as Data Change Scripts or User Scripts.

    Note: The User Scripts can be called by using the Button Click Command - User Scripts property.

  • For actions that only affect the HMI, use the WebPage Elements Event handler scripts. If the action requires an immediate update, use a Promise within the code. Promises should be used to get the return values of a WebPage script, and then execute any dependent script code.

    Note: For more information about using promises, see the WebPages JavaScript Promises topic.

There are two methods for interacting with WebPage Elements and using a project in deployed mode via script:

  • Data Change Scripts (WebHMI)

    These scripts are used to monitor and perform actions when tags associated with WebPages are modified or change state.

    Note: These tags are listed in the WebPages Element Property Tags topic.

  • WebPage Elements Event Handler Scripts

    These scripts are used with WebPage Elements Events, such as On Mouse Enter, On Mouse Up, On Changed, etc.

The WebPages HMI scripting can interact with:

  • The properties of WebPage Elements, which are published as Tags (WebPages Element Property Tags), and WebPage HMI-related tags (WebPages Tags).

    This allows you to access elements' properties, such as a Slider element's Value property or a TextBox element's Text property, using tags.

    For example:

    $MyTag = 45;
    console.log($MyErrorMessageTag);
    $WebPages.WebPage.TextBox.Text = "new text";
    $WebPages.WebPage.DataTable.Content = { Header: ["Header1"], Data: [ ["test"], ["test2] ] }
    $WebPages.WebPage.DataTable.Content = new TableData(["Header1"], [ ["test"], ["test2"] ] )
    Note: The two DataTable examples produce the same result.

  • $ Functions require the use of a promise if you want to use the return value.

  • The "static" HMI $ functions ($ Functions: WebPages HMI) and the individual element's $ functions and properties.

Note:

  • For more in-depth information about the JavaScript programming language, please consult the following (Internet access is required):

    • Mozilla JavaScript Guide
    • Mozilla JavaScript Language Reference
    • "JavaScript: The Definitive Guide" by David Flanagan
  • For more information about script execution, and the differences in where they execute, see the Scripts Execution topic.

WebPage Elements Event Handler Scripts

WebPages HMI $ Functions

WebPages $ Display Functions

WebPage Sample Scripts


WebPage Elements Event Handler Scripts

WebPage Elements Events handler script points are used to create custom JavaScript code for HMI operator interactions with Controls elements while a project is in deployed mode. These interactions could be events such as a Button On Clicked, a CheckBox On Checked, a Numeric Entry On Value Changed, or a TextBox On Text Change.

  1. To add script to an element's Event, press the [image] button next to the specific event handler in the Properties pane. This will open the Script Editor.

  2. Compose the relevant code. For example:

    var cameraName = "cam0";
    $SetCameraSetupPaths(cameraName);


WebPages HMI $ Functions

$ Functions: WebPages HMI

The HMI $ functions provide flexibility and additional functionality compared to using a tag and binding association, and are designed to interact with a project during deployed mode, via JavaScript code in a Button element's OnClicked script point, for example. WebPage Right-Click Menu eliminate the need to create a script on a UI control to call a single $ function.

The WebPages HMI $ functions are "static" HMI functions, and are used to programmatically interact with the entire WebPages infrastructure, versus being associated with a single element or WebPage.

Most of these functions are not asynchronous (that is, they are evaluated in the web browser not in the product), however, the functions associated with the WebPage (such as GetPageTitle, GetPageWidth, etc.) should be treated as though they are asynchronous to handle their return values.

Several functions return a Promise object because JavaScript is asynchronous, and callbacks (that is, Promises) must be used to use the returned value.

All functions act on a per web session basis. In other words, they don’t affect other web sessions, or the WPF HMI.

HMI.CloseDialogPage() : Void
Returns Void
Arguments

N/A
Description

Closes the active dialog page.

$HMI.GetControlProperty(controlname,propertyname : String) : Any
Returns Any
Arguments
  • controlname: String, specifying the name of the control element.
  • propertyname: String, specifying the name of the property.
Description

Fetches the specified property of the specified control element.

Note:
  • Cognex recommends only using this function when an element does not have a published property tag. For a complete list of the published element property tags, see the WebPages Element Property Tags topic.
  • Use this function to access an element property that is not published as a tag. All element properties (for Controls, Graphics) can be accessed via the $HMI.SetControlProperty() and $HMI.GetControlProperty() functions. The properties of the elements are the same as those exposed in the Web Page Editor, minus the white space between the names (so instead of Border Color, it is BorderColor, for example).

$HMI.Login(username,password : String) : Void
Returns Void
Arguments
  • username: String, specifying the name of the user used for login.
  • password: String, specifying the password of the user used for login.
Description

Logs in to the HMI webpage with the specified username and password.

Note: This function does not return whether the login and/or logout has been successful. To evaluate the result, use a Data Change Scripts (WebHMI) script referencing the CurrentUser tag.

$HMI.Logout() : Void
Returns Void
Arguments

N/A
Description

Logs out of the HMI webpage.

Note: This function does not return whether the login and/or logout has been successful. To evaluate the result, use a Data Change Scripts (WebHMI) script referencing the CurrentUser tag.

$HMI.SetControlProperty(controlName,propertyName : String, newValue : Integer, double, Boolean, String) : Boolean
Returns Boolean
Arguments
  • controlName: String, specifying the name of the control element.
  • propertyName: String, specifying the name of the property to set.
  • newValue: Integer, double, boolean or string, specifying the new value of the property to set.
Description

Sets the property (specified with the propertyName argument) of the control element (specified with the controlName argument) to a new value (provided with the newValue argument).

Note:
  • Cognex recommends only using this function when an element does not have a published property tag. For a complete list of the published element property tags, see the WebPages Element Property Tags topic.
  • Use this function to access an element property that is not published as a tag. All element properties (for Controls, Graphics) can be accessed via the $HMI.SetControlProperty() and $HMI.GetControlProperty() functions. The properties of the elements are the same as those exposed in the Web Page Editor, minus the white space between the names (so instead of Border Color, it is BorderColor, for example).
  • The function will return true if the property setting is successful, otherwise it will return false.

$HMI.SetFocusOn(controlName : String) : Void
Returns Void
Arguments

controlName: String, specifying the name of the control element to focus.
Description

Sets the focus on the control element specified with the controlName argument.

Note: This function should be used with a specific control element; the specified element will have focus when the function is called.

$HMI.ShowError(message,title : String) : Promise
Returns Promise
Arguments
  • message: String, specifying the text of the error to show.
  • title: String, specifying the title of the error to show.
Description

Shows the error specified with the message and title arguments.

$HMI.ShowInformation(message,title : String) : Promise
Returns Promise
Arguments
  • message: String, specifying the text of the message to show.
  • title: String, specifying the title of the message to show.
Description

Shows the information message specified with the message and title arguments.

$HMI.ShowLogin() : Boolean
Returns Boolean
Arguments

N/A
Description

Shows the login process.

Note: This function does not return whether the login and/or logout has been successful. To evaluate the result, use a Data Change Scripts (WebHMI) script referencing the CurrentUser tag.

$HMI.ShowMessage(message : String): Promise
Returns | Promise
Arguments

message: String, specifying the message to show.
Description | Shows the message specified with the message argument.

$HMI.ShowPage(pageName : String): Void
Returns Void
Arguments

pageName: String, specifying the name of the web page to show.
Description

Shows the page specified with the pageName argument.

$HMI.ShowQuestion(message,title : String): Promise
Returns | Promise
Arguments
  • message: String, specifying the text of the question to show.
  • title: String, specifying the title of the question to show.
Description | Shows the question specified with the message and title arguments.


WebPages JavaScript Promises

In JavaScript, the Promise notation is used in computation of asynchronous functions. A Promise can be in three states: pending, fulfilled or rejected. It can take two arguments: a results handler and an error handler either will be called only once and will return a value after the asynchronous function has finished. This allows for chaining multiple calls which will execute sequentially. It is also required when the result of a function is needed, for example when assigning the result to a variable as in the example below.

Example: When assigning the result of an asynchronous function to a variable, use the .then() syntax:

$System.GetUptimeMilliseconds().then(function(result){$mytime_test = result});

Instead of:

$mytime_test = $System.GetUptimeMilliseconds();

Example: Error cases can also be handled by specifying a second argument with a callback function:

asyncCallToDesigner(parameters).then(function(result) {
    //handle result here
},
function(error) {
    //handle error here
});

Note:

  • When handling error callbacks, a JavaScript error object will be passed. For more information, see the Error topic (requires Internet access).
    •

  • The then callback is not required; it is only needed to handle the result of an asynchronous call. In addition, within the then, error handling is not mandatory.
    •

  • The parameter names in the function callbacks can be arbitrary names, not just result or error. Parameters are not mandatory; you can run a function, instead.
    •


Custom JavaScript Types and Classes

Note: Tags of type Cjs* are not supported. These tags are only supported in JavaScript scripts.

The following types and classes can be used with the WebPage scripts:

  • CjsColor

    This is a class that is used to represent an ARGB color value.

    There are four member variables:

    • A - Alpha
    • R - Red
    • G - Green
    • B - Blue

    The constructor accepts parameters in the above listed order; which, as shown in the following example, results in a CjsColor Red color:

    var color = new CjsColor(255, 255, 0, 0)

  • CjsDateTime

    This type holds a standard JavaScript object, and has two properties and classes.

    Properties:

    • DateObject - Returns the JavaScript date object.

    • ISOString - Returns the date as an ISO 8061 string.

      Note: For more information about the ISO 8061 standard (requires internet access).

    Constructors:

    • CjsDateTime(date: string) - Creates a CjsDateTime object from a datetime string, based on the ISO 8061 standard.
    • CjsDateTime(date: Date) - Creates a CjsDateTime object from a standard JavaScript date object.

  • CjsViewRotationAngle

    This is an enum:

    enum CjsViewRotationAngle {
    Clockwise0 = 0,
    Clockwise90 = 1,
    Clockwise180 = 2,
    Clockwise270 = 3
}

  • CjsZoomType

    This is an enum:

    enum CjsZoomType {
    Manual = 0,
    Fit = 1,
    Fill = 2
}

  • TableData

    This is an object that holds data for DataTable, ListBox and SelectionBox Controls elements, and it has two properties and one constructor.

    Properties:

    • Header - A string array, containing the header text.
    • Data - A 2D array of strings that contain the text of the TableData.

    The constructor accepts the properties in the following order:

    var a = new TableData([“Header1”], [[“Row1”], [“Row2”], [“Row3”]])


WebPages $ Display Functions

The following $ functions can be called via script when a Display element is on a WebPage:

Function | Property Parameters (with Data Type) | Description
$WebPages.WebPage.Display.Pan | x: Double, y: Double | Provides the ability to move the image horizontally and vertically. X and Y coordinates can be specified.
$WebPages.WebPage.Display.PanTo | x: Double, y: Double | Provides the ability to move to a specific pixel location, horizontally and vertically, within the image. X and Y coordinates can be specified; the center of the graphic will be at the specified coordinates.
$WebPages.WebPage.Display.Rotate90CCW |  | Rotates the image 90° counter-clockwise.
$WebPages.WebPage.Display.Rotate90CW |  | Rotates the image 90° clockwise.
$WebPages.WebPage.Display.ZoomIn |  | Provides the ability to zoom in the image.
$WebPages.WebPage.Display.ZoomOut |  | Provides the ability to zoom out of the image.
$WebPages.WebPage.Display.ZoomToFill |  | Provides an automatic scaling option to scale the image will fill the entire display area.
$WebPages.WebPage.Display.ZoomToFit |  | Provides an automatic scaling option to scale the image as large as possible, while still displaying the entire image. If the aspect ratio of the display area differs from the image, this option will result in either horizontal or vertical blank areas within the display.
$WebPages.WebPage.Display.ZoomToFixed |  | Provides a manual scaling mode option in which the scale factor between the image and display is fixed, independent of the display size.


WebPage Sample Scripts

The following illustrate some code snippets that can be used with WebPages:

$HMI Functions

  • Switching to another WebPage

    $HMI.ShowPage("PageName");

  • Getting the width of a WebPage ("MyPage") and saving it into a tag ($page.width)

    $page.width = $HMI.GetPageWidth("MyPage");

  • Log in to a controller with a user named 'admin' and a password of 'asd'

    $HMI.Login("admin", "asd");
    Note: This function does not return whether the login and/or logout has been successful. To evaluate the result, use a Data Change Scripts (WebHMI) script referencing the CurrentUser tag.

  • Getting the Red value of an element's ("1stButton") background color and saving the value to a tag ($element.color)

    $element.tag = $HMI.GetControlProperty("1stButton", "BackgroundColor").R;

  • Setting the properties of an element

    $HMI.SetControlProperty("Slider1", "Max", 300);
    $HMI.SetControlProperty("Button2", "BackgroundColor", new CjsColor(255, 128, 128, 128));

  • Using the CjsDateTime class

    $WebPages.WebPage.DateTimePicker.Value = new CjsDateTime(new Date(2016, 10, 03, 12, 0, 0));
    $WebPages.WebPage.DateTimePicker.Value = new CjsDateTime("1993-01-02T10:10:00Z");

  • Using the TableData class

    $WebPages.WebPage.DataTable.Content = new TableData(["FirstHeader", "SecondHeader"], [["Row1", "Text"], ["Row2", ""], ["Row3", "234457"]]);

  • Raising a Question dialog and using the resulting answer

    $HMI.ShowQuestion("message", "title").then(function(result) {
    if (result) alert("Yes has been clicked");
    else alert("No has been clicked");
}, function(result) {
    alert("Dialog was closed without Yes or No");
});

  • Showing a message and logging out a user if they click "Yes"

    $HMI.ShowMessage("Clicking Ok will log you out","Logout").then(function() {
    $HMI.Logout();
}, function() {
    console.log("User closed the dialog, do nothing");
});

  • Displaying a simple message, without using the returned value

    $HMI.ShowMessage("Hello", "Title");
    Note: See WebPages JavaScript Promises for more information about JavaScript Promises and the .then() syntax.

$System Functions

  • Log the uptime into the Web browser's console log

    $System.GetUptimeMilliseconds().then(function(ms) {
    console.log("System is up for " + ms + " milliseconds")
});

  • Log an error message: If a tag ($mytag) is False, and a Slider's value is above 80, this is an error scenario which necessitates setting some values to 0 and issuing a log message

                        // log message and setting values to zero
if($myTag == false && $WebPages.WebPage.Slider.Value > 80) {
    $System.Log.Write("Error; setting all values to 0");
    $WebPages.WebPage.Slider.Value = 0;
    $WebPages.WebPage.NumericEntry.Value = 0;
}

  • Query the current system log filter level, and set it to 1 if it less than 1

    $System.Log.GetFilter().then(function(res) {
    $myTag = res;
    if (res < 1) {
        $System.Log.Write("Setting filter level to 1.", 1);
        $System.Log.SetFilter(1);
    }
});


Pages

Pages are used to construct a Human Machine Interface (HMI) user interface (UI). Cognex Designer supports the ability to create multiple versions of a Page, each containing their own set of HMI controls. The Page Editor lets you create a UI for your application.

Note: Please consult the Page Editor topic for an overview and descriptions of the keyboard shortcuts, navigation and position control.

Page


Page

A Page is used to build an HMI UI. Drag and drop the desired interactive elements onto the Page from the Page Toolbox, and then link the elements to tags used in a Task.

Note: Scripts associated with a Page are executed on the UI thread, and long running scripts could cause the UI to temporarily freeze.

Page Toolbox

Page Properties

Binding Properties

Touch Screen Interfaces

Pages - Best Practices


Page Toolbox

The Page Toolbox contains the interactive elements that will be used to construct an HMI UI. Drag and drop elements from the User Controls, Graphics, Media and Vision categories to construct a customized, interactive HMI UI.

User Controls

Graphics

Media

Vision


User Controls

The User Controls category contains interactive elements that are used to display and interact with data in the project. These include elements such as a Button, ListBox, Numeric Entry and a TextBox, which can be used to construct interactive controls that can be used by operators during runtime.

To add and configure an element, drag and drop the element from the Toolbox, and then configure the element's Properties.

Note: For more information about configuring the various parameters of the element's Properties to a tag, please see the Binding Properties topic.
Control | Description
Bar Graph | Displays a Bar to visualize a range of values.
Button | Displays a Button where the click event can be handled by the user.
CheckBox | Enables the user to select or clear the associated option.
DateTimeEntry | Enables the user to select an exact date and time.
Label | Displays text in a configurable content.
ListBox | Displays an item selector which enables the user to select an item from a list populated from a database query.
NumericEntry | Enables the user to enter a numeric value.
PasswordBox | Displays a text box where passwords can be entered.
RadioButton | Enables the user to select a single value from a predefined option list.
SelectionBox | Allows the user to select an item from a predefined list.
Slider | Enables the user to choose between a range of values by sliding a small bar.
Table | Displays a Table control which can be used to display the result of a database query.
TextBox | Displays a control where the user can enter text.

ListBox and Table User Controls with Project Tables

Using a ListBox with an Alarms Table


ListBox and Table User Controls with Project Tables

The ListBox and Table User Controls have the ability to be used interactively with Alarms, User Configuration and Recipes tables. The following queries and column values can be used:

Query Column
Runtime.Users.GetUsers
  • Username
  • Password
  • AccessLevel
System.Alarms.*,
  • TimeTriggered
  • Priority
  • Name
  • Description
  • CurrentMessage
  • State
  • Group
System.Recipes.*,
  • Name
  • Description


Using a ListBox with an Alarms Table

The example below illustrates how to configure a ListBox to show the contents of an Alarms table:

  1. In the Alarm Editor, create three alarms with the following priorities:

    • alarm1: 2
    • alarm2: 3
    • alarm3: 1

  2. In a Page, add a ListBox and two Labels.

  3. Select the ListBox and apply these values to the following properties:
    • Display Column: Name - The value of this column is displayed in the ListBox for the alarm items (a.k.a the name you provided for each alarm; for the available columns, see the table above)
    • Source: Systems.Alarms.All - The table from which the items are enumerated. In this case, we created three alarms that belong to the System.Alarms list.
    • Value Column: Priority - The value of the column you wish to be displayed in the second label.

  4. Select the first label and give the following value as its Text property: Selected alarm's priority is:

  5. Select the second label and click the grey dot next to its Text property. In the Expression Builder, provide the following tag: $Pages.Page.ListBox.SelectedValue

    This will bind the value (Priority) of the Value Column property of the element selected in the ListBox and display it as this label's Text property.

  6. To check the application, click the Test Mode button. Select the alarms and check their priorities displayed in the label.


Graphics

The Graphics category contains elements used to create lines, shapes and a panel to display graphics and customize the look of the HMI UI.

To add and configure an element, drag and drop the element from the Toolbox, and then configure the element's Properties. These elements can also be used to indicate changes in state by utilizing Binding Associations.

Note: For more information about configuring the various parameters of the element's Properties to a tag, please see the Binding Properties topic.
Control | Description
Bezier Segment | Displays an adjustable Bezier curve.
Ellipse | Displays an ellipse shape.
Line | Displays a straight line.
Panel | Displays a Raised or Inset panel.
Rectangle | Displays a rectangle shape.


Media

The Media category contains two elements to display an image or a video player. Before adding these elements, configure Resources to make the image and/or video available to the element.

To add and configure an element, drag and drop the element from the Toolbox, and then configure the element's Properties.

Note: For more information about configuring the various parameters of the element's Properties to a tag, please see the Binding Properties topic.
Control Description
Image

Displays an image from the Resources or from an Image file.

How to use it with Resources:

  1. Provide the image file as a resource. See the Resources and Using the Resource topics.
  2. Place an Image control on your page and select it by clicking on it.
  3. In the Properties section, select your resource from the Source (Resource) drop-down list.

How to use it with an image file directly:

  1. Place an Image control on your page to select it by clicking on it.
  2. In the Properties section, provide the path to the image file in the Source (File) field.
Video Player

Allow users to embed video files inside the application.

How to use it with Resources:

  1. Provide the video file as a resource. See the Resources and Using the Resource topics.
  2. Place a Video control on your page and select it by clicking on it.
  3. In the Properties section, select your resource from the Source (Resource) drop-down list.
  4. Optional: Place a Button on your Page and in the Properties section, assign the following click command to it: Pages.Page.VideoPlayer.Play. This button can start the video when you start test mode.

How to use it with a video file directly:

  1. Place a Video control on your page and select it by clicking on it.
  2. In the Properties section, provide the path to the video file in the Source (File) field.
  3. Optional: Place a Button on your Page and in the Properties section, assign the following click command to it: Pages.Page.VideoPlayer.Play. This button can start the video when you start test mode.


Vision

The Vision category contains elements that can be used to display VisionPro images, as well as interactive controls for the VisionPro Job Editor and Tool Blocks.

  • The VisionPro Display is used to display images output from a Camera Device or a VisionPro Tool Block.
  • The VisionPro Display 3D is used to display images output by the Cognex DS1000 Series Sensor.
  • The VisionPro Display Status Bar enables the user to access information from the display.
  • The VisionPro Tool Editor displays the tool edit for a specific type of tool (PatMax, ID, etc.)
  • The VisionPro ToolBlock Editor displays a tool block edit control.

To add and configure an element, drag and drop the element from the Toolbox, and then configure the element's Properties.

Note: For more information about configuring the various parameters of the element's Properties to a tag, please see the Binding Properties topic.

VisionPro Display

VisionPro Display 3D

VisionPro Display Status Bar 3D

VisionPro Display Status Bar

VisionPro Tool Editor

VisionPro ToolBlock Editor


VisionPro Display

The VisionPro Display inserts a CogDisplay on the Page, and is used to display images output by a Camera Device or Image File Device, or an image output by a VisionPro Tool Block.

Related Topics For more information about the CogDisplay, see the Displaying an Image and CogDisplay Class topics.

To configure a VisionPro Display, after adding it to the Page, using the Expression Builder, set the Subject property to the desired Device or tool. For example, if configuring the display for a Camera Device, the Subject property would be bound to $Devices.<DeviceName>.Image; if configuring for a Tool Block, it would be bound to $Tasks.Task.Task.ToolBlock.LastRun.<ToolName>.InputImage.

Note:

  • In the figure above, the main VisionPro Display has been configured with a VisionPro Display Status Bar and a Button to display information about the image being displayed and to acquire new images.

    Note: For more information about configuring the VisionPro Display to display acquired images, see the Display an Acquired Image topic.

    In addition, a TextBox and another Button have been added to save the images, and a filmstrip was built to display the previously captured images.

    Note: For more information about saving images and creating a filmstrip, see the Saving Images andCreating a Filmstrip topics.
  • In addition to the configurable properties, the VisionPro Display also has three script points to use as events, On Mouse Down, On Mouse Move and On Mouse Up.

  • The following exposed methods are also helpful when using the VisionPro Display:

    Fit(bool): Uses the current ScalingMethod to find the largest zoom value that allows the entire image to be visible in the display. If true, the image is scaled and panned so that all graphics are visible too. This parameter is ignored if there are no graphics or if the graphics all lie within the bounds of the image.

    Note: This method persists until a new image is loaded.

    Save(bool fitImage, string filename): Takes a screen capture of what is currently being displayed and saves it to a file. The image format is determined by the extension of the filename provided. If fitImage = True, the returned bitmap contains the full unscaled image, with graphics annotations clipped at the image boundaries. If fitImage = False, the returned bitmap contains exactly what is visible in the display. The image is scaled and panned as it currently appears in the display, and graphics annotations are clipped at the display boundaries.

    Note: When using the Save method, the path name and filename are required. For more information about saving images, see the Saving Images topic.


VisionPro Display 3D

The VisionPro Display 3D inserts a VisionPro Cog3DDisplayV2 display on the Page. It supports ICogVisionData objects, which are output by a Cognex Displacement Sensor (DS1000 or DS900 Series Sensors).

To configure a VisionPro Display 3D, after adding it to the Page, using the Expression Builder, set the Subject property to the desired ICogVisionData in a tag, or directly to desired Device's Image. For example, if configuring the display for a DS1000 Series Sensor Camera Device, the Subject property would be bound to $Devices.<DeviceName>.Image.

When the VisionPro Display 3D is in runtime or in Test Mode, a right-click menu is enabled, which allows the user to fit the view, reset the view, or save the image (a Save As dialog will be launched when selected).

Also while in Test Mode, press the center wheel button of the mouse to tilt and rotate the 3D image, and zoom in and out of the image.

Methods | Description
HasError() | This property gets set when the image processing fails, for any reason. Changing the subject or calling the Clear or Add methods will clear the error flag. This is a read-only property.
AddVisionData()

Parameters: ICogVisionData visionData

This function is used to add Vision Data during runtime, without the need to change the Subject property. This method allows you to add a single Vision Data object to the display; if the Vision Data object can be processed, it will appear on the display. If there is an error, Designer will log a warning-level log item, and set the HasError property to true. Using this function will not clear the 3D display, but it will reset the HasError flag.
AddGraphics()

Parameters: Cog3DGeometryGraphicBase geometryGraphic, Cog3DVisionDataGraphicBase visionDataGraphic string groupName

This function is used to add a graphic during runtime, without the need to change the Subject property. This method allows you to add a single graphic object to the display; if the graphic object can be processed, it will appear on the display. If there is an error, Designer will log a warning-level log item, and set the HasError property to true. Using this function will not clear the 3D display, but it will reset the HasError flag.

Adds the given geometry graphic to the Display and associates it with the given VisionData graphic. If the geometry graphic is null, only the VisionData graphic is added to the display. If the group name is ignored, or null is passed in, the default group will be used, instead.

Note: A NonSupportedException may be thrown if the application cannot create a Cog3DVisionDataGraphicBase representation for the Vision Data.
Clear()

This function removes every item from the display, and resets the HasError flag.
Note:
  • In the figure above, the VisionPro Display 3D has been configured with a VisionPro Display Status Bar 3D to display coordinate information about the image being displayed.
  • In addition to the configurable properties, the VisionPro Display 3D also has five script points to use as events, On Mouse Down, On Mouse Move, On Mouse Up, On Mouse Enter and On Mouse Leave.

  • For additional scripting capabilities, the underlying VisionPro Cog3DDisplayV2 can be accessed, using the following:

    var myDisplay3D = $System.GetInternalObject("Pages.Page.VisionProDisplay3D") as Cog3DDisplay;
  • The VisionPro Display 3D does not support displaying 2D images as height maps; these types of images will not be displayed and a warning will be shown, instead.
  • The VisionPro Display 3D does not work when using a Windows Remote Desktop Connection. Third party options, such as VNC® or TeamViewer, may be used.

  • The VisionPro 3D tools do not output graphics that can be directly output by a VisionPro Display 3D; the graphics must be handled via script. For more information about constructing a VisionPro Display 3D to display the graphics of VisionPro 3D tools, see the Displaying 3D Images and 2D Tool Graphics topic.


VisionPro Display Status Bar 3D

The VisionPro Display Status Bar 3D inserts a VisionPro Cog3DDisplayV2StatusBar on to the Page, which provides information about the image in the display to which it is configured. When the mouse hovers over the image, it provides information about the X, Y and Z values where the cursor is located.

To display the status information, set the Selected Display property to a 3D display object (for example, Pages.Page.VisionProDisplay3D).


VisionPro Display Status Bar

The VisionPro Display Status Bar inserts a CogDisplayStatusBarV2 to the Page, which provides information about the selected space for the display, the coordinates of the cursor pointer (in the selected space), the zoom level in the referenced display, and the value of the pixel at the cursor pointer location.

To display the status information, set the Selected Display property to the display (for example, Pages.Page.VisionProDisplay).


VisionPro Tool Editor

The VisionPro Tool Editor is used to insert an interactive edit control for a specific VisionPro tool, such as a CogBlobTool, CogCaliperTool or CogIDTool, which allows the operator to interact with the tool during runtime.

Related Topics For more information about the VisionPro tools, see the topics in the Control Reference section.

In order to have the VisionPro tool's editor control available, it must first be added as a tag:

  1. Go to the desired tool's Tool Block in the Task, and double click the Tool Block to open the ToolBlock Edit Control.

  2. Press the Edit Tags button.

  3. From the VisionPro Tag Manager, select the desired tag and press the arrow button to add it to the list of tools on the right.

    Note: For more information about adding VisionPro tags, see the Adding Tags Using the VisionPro Tag Manager topic.

  4. Go back to the Page, and, using the Expression Builder, set the Subject property to the tool, i.e. $Tasks.Task.Task.ToolBlock.CogBlobTool.


VisionPro ToolBlock Editor

The VisionPro ToolBlock Editor inserts a VisionPro ToolBlock Edit Control into a Page, which provides operators access to a CogToolBlock.

Related Topics For more information about the VisionPro ToolBlock, see the ToolBlock Edit Control and Using a CogToolBlock topics.

In order to have the VisionPro ToolBlock Edit Control available, it must first be exposed as a tag:

  1. Go to the desired Tool Block in the Task, and double click the Tool Block to open the ToolBlock Edit Control.

  2. Press the Edit Tags button.

  3. From the VisionPro Tag Manager, enable the Expose ToolBlock checkbox.

  4. Go back to the Page, and, using the Expression Builder, set the Subject property to the tool, i.e. $Tasks.Task.Task.<ToolBlockName>.ToolBlock.
Note:

  • To save edits made to the ToolBlock during runtime, there are two options: manually saving changes to the .vpp file, or using a recipe.

    Manually Saving Changes

    1. Add a Button element, and for the Button's On Click script, use the following script (if the script needs to be called from different places within the project, create and use a User Script instead of the Button's On Click script):

      Cognex.VisionPro.CogSerializer.SaveObjectToFile($Tasks.<TaskName>.<TaskName>.<BlockName>.Toolblock, "C\\Toolblock.vpp")

    2. To load the ToolBlock at startup, use the following script for the OnStartup script:

      $Tasks.<TaskName>.<TaskName>.<BlockName>.Toolblock = (Cognex.VisionPro.CogSerializer.LoadObjectFromFile("C:\\Toolblock.vpp");

    Using a Recipe

    1. Create a new Recipes, and add the ToolBlock tag to the recipe.

    2. Add a Button element, and for the Button's On Click script, use the following script (if the script needs to be called from different places within the project, create and use a User Script instead of the Button's On Click script):

      $System.Recipes.Recipe.Save("Default","");

    3. To load the ToolBlock at startup, use the following script for the OnStartup script:

      $System.Recipes.Recipe.Load("Default");
  • When making changes to the ToolBlock at runtime, the list of inputs and outputs should not be changed. Making changes to the inputs and outputs could result in a link being broken in the Task, and stop the Task from executing correctly.
  • For the best performance during runtime deployment, Cognex recommends that users be prevented from accessing any Pages with a VisionPro ToolBlock Editor. Simply disabling the Visible property will not work; the Page that contains the VisionPro ToolBlock Editor must be closed, because they both execute on the same UI thread, so timing is not predictable. For example, a VisionPro ToolBlock Editor on an inactive Page would take ~25ms, while a VisionPro ToolBlock Editor on an active Page would take ~90ms, as would a VisionPro ToolBlock Editor with the Visible property disabled.


Page Properties

The Page Properties are used to control how the HMI UI is displayed (their size and position), its appearance, and whether or not it will be displayed on start-up.

Note: If negative X and/or Y Position values are specified, when the HMI UI is deployed, portions of the UI may not be visible. The Page may be visible during Test Mode, but it will not be visible when deployed.

Each Page can be accessed through the following tag: Pages.{PageName}.Title.

Page Properties - Behavior Mode

Page Properties Display Methods


Page Properties - Behavior Mode

The Page Properties Behavior Mode parameter controls how the Page will be displayed on the HMI UI.

Behavior Mode | Description
Normal | The Page is simply drawn on the HMI. If a page is Startup page then it must be a Normal page.
Pop-up | Creates a static window that displays the contents of the Page.
Moveable Pop-up | Creates a moveable pop-up window.
Startup Page | The Page will be displayed automatically when the application starts.


Page Properties Display Methods

These are the methods used to control the way pages are displayed.

Display Method | Description
ShowPage(string pageName, double xOverride, double yOverride) | Makes the given Page visible to the HMI. Optional parameters are supplied to change the X and Y position of the Page.
ClosePage(string pageName) | Closes the specified Page.


Binding Properties

Bindings are used to animate a Page, and are created between a project tag and a parameter of the interactive Page element. For example, using a Label to display the value of a numeric variable.

When an element is selected in the Page, the element's parameters are displayed in the Properties window. If a parameter has a grey arrow ( [image]) next to it, it can be bound to a tag.

  1. Click on the grey dot to launch the Expression Builder.

  2. Use the Expression Builder to create an expression that is connected to the control property. In the image above, the expression is a simple tag expression. A more complicated expression can be created, if necessary. Once the expression has been created, the grey dot will change to green to show that the binding is connected.

    Note: if a binding has become invalid (i.e. the tag it was once bound to is deleted), it will become a green circle with a red cross through it.

  3. When Cognex Designer is running, changes in the expression will update the Page control, and for some input controls, updating the Page control will cause the expression to update.

    Note:
    • Expressions associated with a control's bindings remain functional even when the control is disabled. This is a conventional way to display read-only data. If you would like to disable your expression at the same time the control itself is disabled, plan your expression accordingly. For example, create a Boolean tag which gives back True when the control is enabled and False when the control is disabled and use it in an if statement with your expression, or move the expression to a script and manage when it is run from there.

    • Binding updates are throttled to one update, per binding, approximately every 33ms (or roughly 30fps).

      • A Page control will only receive the latest binding's value. For example, if $MyTag was bound to a NumericEntry, and the value was changed from 5 to 10 and then 15 very quickly (faster than 33ms), the NumericEntry will only receive 15 as the updated value.
      • The update speed will be adjusted dynamically if the time taken to update a frame takes longer than approximately 33ms.

One-Way Binding

Binding Associations

Binding Visibility To Tags


One-Way Binding

Some Page elements have a two-way binding nature. These controls can both read/write to the tag they are bound to, for example when a TextBox receives a new value, it may send the value back to the source tag where the value came from. To prevent any accidental value updates, there are two options:

  1. Set the element's IsReadOnly property, which makes its binding one-way, i.e. it can receive updates, but will not write any changes back to the tag.

  2. Use a Label which is always read-only.

Two-way controls with the IsReadOnly option:

  • TextBox
  • SelectionBox
  • NumericEntry
  • DateTimeEntry

Two-way controls without the IsReadOnlyoption (i.e. the updated value issue can still occur with these controls).

  • Slider
  • RadioButton
  • PasswordBox
  • CheckBox


Binding Associations

Binding Associations are used when there is no direct way of converting a tag value to a property, i.e. converting a Boolean value to a color. Associations allow you to create a mapping table that specifies the value to use for a given tag. Associations can also be used to convert from an integer to a color, a Boolean to a string, and/or a string to a color.

For example, an Ellipse can be added to a Page, and its Color parameter could be set as an association to a Boolean result, where False would indicate Red and True would indicate Green.

  1. To create an association, add an Ellipse to the Page.
  2. In the Ellipse Properties, click the grey dot beside the Color parameter to launch the Expression Builder.

  3. Press the Add Tag button and select a tag that returns a Boolean result.

  4. Press the Associations button to create the conversion association. An Invalid Type dialog will be presented, press the Yes button to continue.

  5. Uncheck the Add Association Checkbox, and then press the Add [image] button.

  6. From the color drop-down menu, select Red for False.

  7. Press the Add button again, and from the color drop-down menu, select Green for True. Press the Accept button to complete the association.

  8. Put the Page in Test Mode, and the Ellipse should be filled with the color Green when the result returns True, and Red when it returns False.


Binding Visibility To Tags

The standard way to control visibility of Page elements is to create tags and use the Visible property of the elements.

Note: Dynamically creating controls is not supported.

For example, on a Page, there is a Toggle Visibility button and a collection of elements that have been constructed to create a dial, which is used to adjust a value. The dial should disappear when the button is clicked.

  1. Create a button and an HMI element that you want to hide.

  2. In Tag Manager, create a tag called tg_Hidden. It should be Boolean type, True by default (in this example Truemakes the element visible).

  3. Select your HMI element and bind its Visible property to tg_Hidden.

    1. Click the grey dot next to Visible.

    2. In the Expression Builder, bind the property to $tg_Hidden and then click OK.

    3. The green dot marks that Visible property is now bound to tg_Hidden.

  4. Right-click your button and select On Mouse Click.

  5. In the Button.OnClick script, enter the following: $tg_Hidden = !$tg_Hidden;

  6. To test that it works, put your project in Test Mode, and press the button.


Touch Screen Interfaces

Cognex Designer Page elements provide options for use on a touch-screen user input device.

  • The Numeric Entry control provides a Key Pad Pop-up property that can be configured to show a Keypad on a single or double-click entry.

  • The Textbox control provides the same functionality, but with a Keyboard.


Pages - Best Practices

The following are guidelines when creating Pages for your project:

  • When constructing a Page, construct it with the goal of allowing them to be exported as Templates.

    • Use meaningful names for each element on the Page.
    • Use a naming convention for your standard Pages, e.g. "Overview", "Results", "Results_Details", "Settings", "Settings_Camera", "Diagnostics", etc.
  • When constructing a project with multiple Pages, consider creating a single navigation pane, so navigation instructions do not have to be duplicated.
  • For the Page Properties Display Methods (ShowPage/ClosePage) methods, use $Pages.{Page}.PageName to get the path of the page instead of using a hardcoded string (e.g. "Pages.{MyPage}").

  • Do not call Task.{Task}.Run() from a UI, such as on a Button click command. Instead, use Task.{Task}.RunAsync().

    • The Run() call is a blocking call, and the UI will appear "frozen" until the Task completes, which may cause Windows to interpret your application as unstable, and then request to close it.
    • It may also cause the Cognex Designer program to lock up.

  • Page elements, properties and methods (e.g. $Pages.{Page}.TextBox.Text) should only be used on the Main/UI Thread, and not on another thread, such as a Task.

    • Instead of accessing an element from another thread, bind the element to an intermediate tag, which will prevent cross-thread and performance issues.

    • If it is necessary to access a Page element on a Task thread, see the Update a VisionPro Display From a Task topic.

      Note: There is a performance penalty when accessing a Page property from another thread.

  • When constructing a Button that will be used to launch an Open/Save file dialog, ensure that the pipe character (|) is placed in the correct location between the {display text} and the {filter} (e.g. {display text} | {filter}). The script below illustrates the proper use of the character (the script is used with the OnClick script of a Button in the FunctionSample ToolBlockEditor Page):

    string vppFilename = $FileSystem.ShowSaveFileDialog("Save ToolBlock", initialDirectory, "NewToolBlock", "VisionPro VPP|*.vpp");


Scripting

Cognex Designer provides a powerful scripting environment using Microsoft C# .NET. You can write standard C# .NET code and have it execute within the Cognex Designer environment.

Note: This document does not describe how to use C#, and assumes that the user has a basic understanding of C# programming.

Cognex Designer provides two simple language extensions that allow the C# scripting to access Cognex Designer tags (A) and functions (B):

  1. Cognex Designer uses a special $ character to access tags. To read or write from a tag in a script:
    $BooleanValue = False;
    $IntegerValue = 10;
    $StringValue = "Hello";

  2. Functions use the $ sign as well. Alternatively, you can drag 'n drop from the Tag & Function browser tool window. Recognized functions will be highlighted in the Script Editor.

Note: Published (Cognex Designer or Plugin) methods with 'out' parameters cannot be compiled within a script. For more information, see the Use Methods With "out" and "ref" Parameters topic.

WebPages HMI Scripting

WebPage Elements scripts are used to program the script points for handling WebPage Element events, such as a Button's On Clicked event. These scripts execute in the Web browser running the HMI.

Scripting - Best Practices

Scripts Execution

JavaScript Overview

Logging

$ Functions

Adding References and Using Statements

User Scripts

Data Change Scripts

Data Change Scripts (WebHMI)

DataSet Data Type

Key Scripts

Script Example

Accessing VisionPro Objects from Script

Scripting Tips in a Task

Keypad and Keyboard Script Functions


Scripting - Best Practices

This topic covers best practices when implementing scripts in a project.

  • Data Change Scripts are executed as a blocking function on a thread that changes a tag's value. For example, if a tag is in a Task, and the tag's value changes in the Task, the Data Change Script will block the Task while the script executes.

  • Make sure to utilize Using statements to help keep your script text readable. Using statements allow the compiler to automatically attempt to prefix your code.

    For example, instead of the following code:

    Cognex.VisionPro.Display.CogRecordDisplay display2 = $System.GetInternalObject("Pages.Page.ImageDisplay") as Cognex.VisionPro.Display.CogRecordDisplay;
Cognex.VisionPro.ICogRecord currentRecord = $Tasks.Task.Task.VisionProToolBlock.CogPMAlignTool.CreateCurrentRecord();

    Add Cognex.VisionPro and Cognex.VisionPro.Display as Using statements, the code can be rewritten as follows:

    CogRecordDisplay display2 = $System.GetInternalObject("Pages.Page.ImageDisplay") as CogRecordDisplay;
ICogRecord currentRecord = $Tasks.Task.Task.VisionProToolBlock.CogPMAlignTool.CreateCurrentRecord();
    Note: For more information, see the Calling External Code and Using Statements topic.
  • Most global static functions (e.g. $System.Log.Write) are thread safe.

  • In a "void" script, if you attempt to "return;" before the last line of code, you must instead use "return null;". Simply using "return;" in this scenario will result in a compile error (e.g. "Line 3: An object of a type convertible to 'object' is required.").


Scripts Execution

WebPage HMI Scripts

These are the WebPages HMI Scripting scripts, such as a Button's On Click event handler script.

For scripts that execute in a web browser:

  • Code is edited in the Script Editor.
  • Tags are stored at the beginning of the script; if the tag value is updated by another component of the system while the WebPage HMI script is being executed, that change will not affect the tag’s value within the WebPage HMI script. After the WebPage HMI script completes, the updated tag value will be written back to the tag, and will overwrite any other changes to the tag while the WebPage HMI script was executing.

  • The use of Promises within the code is supported, and can be used to get the return value of a script and execute any dependent script code.

    Note: Currently, the Script Editor will not raise compile errors when JavaScript code uses Promises in controller scripts. Likewise, the editor will not raise warnings in HMI Web Scripts where the use of $ Functions with a Promise may be preferred. For more information on Promises see the WebPages JavaScript Promises topic.

  • The execution of $ Functions and the updating of tags within WebPage HMI scripts are asynchronous to the project being run. There are two different mechanisms for handling asynchronous script execution:

    1. For processes that are tied to controlling parts of the application, bundle the commands in scripts that execute on the controller, such as Data Change Scripts or User Scripts.
    2. Promises can be used to not only force an order of execution, but can also be used to handle values returned from commands executed on the controller. For example, if you wanted to perform a diagnostics check on the controller before displaying a message which is dependent on the returned diagnostic status, or performing an action on the camera that must be completed before operators are allowed to interact with the HMI.


JavaScript Overview

Provided within this overview are brief sections detailing the important aspects of the JavaScript language for use with applications.

Note:

The information provided in this overview topic is intended for users already familiar with the basic principles of programming.

For more in-depth information about the JavaScript programming language, please consult the following (Internet access is required):

  • Mozilla JavaScript Guide
  • Mozilla JavaScript Language Reference
  • "JavaScript: The Definitive Guide" by David Flanagan

WebHMI and Type Compatibility with C# Applications

For information about WebHMI, see WebHMI: Functional Overview, Compatible Types, and an Example.

For an overview of data type compatibility between WebHMI JavaScript and native C# applications, see WebHMI: Type Compatibility .

JavaScript Restrictions when Using WebHMI

  • JavaScript is only allowed for use within the WebHMI.
  • JavaScript is only executed on the Web client. JavaScript is not executed on the Cognex Designer Task.
  • JavaScript is not available as a User Script or Script Block.
  • C# scripting is not available in the WebHMI.
  • $API properties and functions from the WebHMI are not available to WPF HMI, and vice-versa. For example, a user can't change the WPF HMI's page from the WebHMI.

  • Existing WPF Forms controls are not available in WebHMI.

Basic Lexical Structure

The implementation of JavaScript follows version 5 of the open standard approved by the European Computer Manufacturer’s Association, also known as ECMAScript 5 (ECMA5). It utilizes the Unicode 3 (or later) character set (UTF-8), and is similar to C, C++, C# and Java syntax in the following ways:

  • The language is case-sensitive, which requires language keywords, variables, function names and other identifiers use a consistent capitalization of letters.
  • Identifiers are used to name variables and functions, and must begin with a letter, an underscore (_) or a dollar sign ($). Digits are not allowed at the beginning.
  • Compound statements are contained within curly braces ({}).
  • White space is ignored, thus allowing cleanly formatted code that is easy to read and understand.

  • Semicolons (;) separate statements, and while these are optional at the end of a line, they are highly recommended to explicitly demarcate the end of a statement.

    If statements are on separate lines, they can be omitted. However, JavaScript always interprets line breaks as a semicolon, so never insert a line break between return, break or continue and the expression that follows those keywords.

Comments

There are two styles of denoting comments in JavaScript: two forward slashes (//) at the end of a line denote comments, and any characters within /* and */ are also treated as comments (/* JavaScript comments */).

The following illustrates the two styles of denoting comments:

/* JavaScript comments */
var x; // Look like Java, C# and
     // C++ comments
/*
* And they can occupy
* multiple lines.
*/
Note: Comments can be removed through minification.

Supported JavaScript Types when Using WebHMI

The following types are supported when writing JavaScript for WebHMI: Functional Overview, Compatible Types, and an Example.

Primitive Types

  • Boolean
  • char
  • byte
  • sbyte
  • int16
  • uint16
  • int32
  • uint32
  • int64
  • uint64
  • integer
  • single
  • double (real)
  • String
  • DataSet
  • Note: No other types can be transferred or interpreted by the WebHMI or JavaScripts.

Primary Runtime Types

Primary Runtime Types encompass all objects described in the section Developing a Cognex Designer Project. For example, Tags, Tasks, Pages, and Devices are all objects you can use to program with JavaScript using Cognex Designer’s API.

There are some restrictions when using Primary Runtime Types. WebHMI and JavaScript types. For example, if you have $Tag of type CogPMAlignPattern, you cannot access that tag in a WebPage for binding or in a JavaScript script. This $Tag will be accessible, however, in the C# scripts for the WPF HMI, Tasks, and User Scripts.

For binding in a WebPage, ICogImage and ICogRecord will be available to bind to the Display controls’ source property, but cannot be accessed via JavaScript.

Image Types

For images, only the following types can be displayed on the HMI.

  • ICogImage
  • CogImage8Grey
  • CogImage24
  • PlanarColor
  • ICogRecord
  • CogRecord
  • Note:
    • No 3D graphic support is available.
    • Objects derived from these classes will not work.
    • Image tags are not accessible from JavaScripts.

Variables

Variables are used to define a symbolic name for an object or a value, and allows it to be referred to by its symbolic name. Within JavaScript, there are two types: primitive types and object types. Every variable refers to a primitive value (number, string, true/ false, null or undefined) or an object, which is defined as a non-primitive value.

Variables are declared with the var keyword, as shown in the examples below:

            var aBc, zz32;
var q = "abc", r = 'f';
var p = true, q = false;

Variable Scope

Variables are either scoped globally or functionally. A variable declared outside of any functions has a global scope and is available to all code within the Script module in which they are declared. A variable declared in a function is available only within the body of the function.

Objects and Arrays

In JavaScript, any non-primitive value is considered to be an object; a property that has a name and a value, which can either be a primitive value or another object. While an object is essentially an unordered collection of named values, an array is an ordered collection of numbered values.

Object Properties

Within JavaScript, objects are dynamically typed:

  • Every object is a dictionary of properties.
  • Each property is a name-value pair.
  • Properties are added and removed at run time.

Properties are inherited from a prototype object:

  • As if each new object is a copy of its prototype.
  • The prototype may in turn derive from a prototype of its own.

Property Syntax

JavaScript uses two types of syntax for defining property access. The following syntax should be followed for properties (with either type, the expression before or after the dot or square bracket is evaluated first):

  • Dot notation:

    a.prop = 123;	// Adds a property

    b = a.prop;	// 123

                            delete a.prop;	// Removes the property

    c = a.prop;	// undefined

  • Square brackets with a name and/or string:

    a ["break 1"] = 123	// Adds a property

    b = a["break 1"];	// 123

    nm = "break 1";	// Can use a variable

    c = a[nm];		// 123

                            delete a[nm]		// Removes the property

Object Literal Syntax

To create a new object, use a comma-separated list of name:value pairs, as shown below:

            var myrectangle = {
    width: 100, height: 50,
    "return": {a:1, b:2, c:3},
    getArea: function() {
       return this.width * this.height;
    }
};

Arrays

Within JavaScript, arrays are just like regular objects, but use numerical property names, as shown below.

Note: The length property is one plus the highest numbered element.
            var a = []; 	// Empty
var b = [9.5, "Fred", true];
var c = b[1];	// "Fred"
var d = b["1"]// "Fred"
var e = b[9]	// undefined
b[3] = 2;	// adds 1 element
b.newProperty = "hello"

Built-in JavaScript Classes

The following are examples of built-in JavaScript classes.

  • Array: sort, reverse, concat, slice, push, pop, shift, unshift
  • Math: abs, min, max, sqrt, ceil, floor, sin, cos, tan, asin, acos, atan
  • String: indexOf, match, replace, split, substring, toUpper, toLower, trim
  • Date: new Date(), toString, add, subtract

Numbers

JavaScript represents all numbers using the 64-bit floating-point format defined by the IEEE 754 standard. When a number appears in a JavaScript program, it’s referred to as a numeric literal. The following illustrates how JavaScript represents numbers and numeric literals:

  • Base 10: 1, 47, 3.14, -24e-13
  • Base 16: 0x7fff

String Literals

The following are examples of string literals used in JavaScript:

            "Hello I'm Fred"
'I am "Sam", I am'
"Hello\t \"World \" \x0D \u000A"
"Hello \big \world" (EC5)

Functions

A function is a special kind of object, which has executable code associated with it, and can be invoked to run that code and return a value. Functions, like arrays, behave differently than objects, and have a special language syntax for working with them. Most importantly, they are true values, and programs can treat them like regular objects.

Functions are defined using the function keyword, and arguments and return are optional. The following forms are equivalent:

            function  sum(x, y) {
  return x + y;
}
var sum = function (x, y) {
  return x + y;
}

Variadic Functions

Within JavaScript, any function can take a variable number of arguments; the arguments keyword is an array of the current function’s arguments. The following demonstrates this:

            function sum() {
  var i, total = 0;
  for (i=0; i < arguments.length; i++) {
    total += (+arguments[i]);
  }
  return total;
}
var z = sum(1,2, "3.14");	// 6.14
  • Its own arguments and variables.
  • Its parent function’s variables.
  • As properties of the global object.

Expressions and Operators

The following are the common expressions and operators used in JavaScript:

  • Primary: (x) x.y f(x,y,z) a[x]
  • Unary: +x –x !x ++x –x x++ x-- ~x32
  • Multiplicative: * / %
  • Additive: - + (+ is also used for string concatenation)
  • Shift32: << >> (sign extend) >>> (zero extended)
  • Relational: < > <= >= (alphabetical for strings)
  • Equality: == != === !== (strict equality/inequality)

  • Bitwise32

    • AND: &
    • OR: |
    • XOR: ^
    • Conditional AND: &&
    • Conditional OR: ||
    • Conditional if: ?:
  • Assign: = *= /= %= += -= &= ^= |= <<= >>= >>>=

Type Conversion

Values are converted automatically whenever needed (and if possible), and operators are left-associative. When converting, be aware of weak equality statements, such as the following:

            if ("4" == 2 * 2)	// true
if ("4" === 2 * 2)	// false

“False” values convert to false (undefined, null, 0, -0, NaN, “”), and all other values convert to true (if (“false”) {…} // true).

typeof Operator

The typeof operator returns a string identifying the type of its operand:

Value | typeof value ==
Null | “null”
Undefined | “undefined”
Any number (NaN) | “number”
A string | “string”
True/False | “boolean”
Any function | “function”
Any object | “object”

if Statement

Within JavaScript, if statements use the same syntax as C:

            if (x>0) {
  y = Math.Sqrt(x);
}
else if (x == 0) {
  y = 0;
}
else
  y = undefined;	// braces optional
            // (but recommended)

switch Statement

Within JavaScript, switch statements are similar to C, but are also able to use strings, as well:

 switch (name) {
  case "Fred":
    processFredReport();
    break;
  case "Sam":
  case "Samantha":
    processSamReport();
    break;
  case 911:	// also matches "911"
    emergencyAlert();
        // Fall through (discouraged)
  default:
    return "Unable to process report!";
}

Looping

There are several methods to create loops within JavaScript.

  • For

                        for (var x = 0; x < 100; x++) {...}

  • While

                        while (!inputFile.isAtEnd()) {...}

  • Do While

                        do {...} while (foundItem==0);

  • For/in

                        for (var propName in myObject) {...}
    Note: The property order is not guaranteed.

  • Break

    This is used to exit the enclosing loop:

                        if (foundRecord) break;

  • Continue

    This is used to begin the next loop iteration:

                            if (skipThisItem) continue;

Exceptions

Exceptions are used to indicate that an exceptional condition or error has occurred. A throw signals that an error occurred, while the try/catch/finally statement is used by JavaScript to handle an exception or error.

Throwing Exceptions

The following demonstrates how to throw an exception within JavaScript:

            if (area <= 0) {
  throw new Error("area must be positive");
  --or--
  throw 'Invalid argument';
  --or--
  throw radius * 3.14;	// not normally used but legal
}

Try/Catch/Finally Block

The try clause defines the block of code that contains the exception to be handled, and is followed by either a catch or finally clause. These two are optional, however, the try block must be followed by at least one of them. The following illustrates how to handle an exception or error in JavaScript:

            try {
  sendAllOutput(stream);
}
catch(ex) {				// optional (but one is required)
  console.log (ex);
}
finally {				// optional (but one is required)
  stream.close();
}

Regular Expressions

The following are examples of regular expressions commonly used in JavaScript.

            var x1 = new RegExp("[a-z].*");
            var x2 = /[a-z].*/;

The test method returns true on a match:

valid = x1.test(input);

The exec method returns multiple results:

            var x3 = /Tool\d*;
while (r = x3.exec(text))
{
  console.log("Found" + r[0] +
    "at" + r.index +
    "now at" + x3.lastIndex);
}

Strict Mode

Strict mode of ECMAScript5 executes strict code using the “use strict” directive. This implements a restricted subset of the language which fixes a few deficiencies and provides stronger error checking and increased security.

Follow the following guidelines to implement strict mode:

  • Begin the script with "use strict";.

  • All variables must be declared with var.

    In non-strict mode, assigning an undeclared variable adds it to the global object while strict mode will throw an error and prevents accidentally creating a global variable.

  • The with statement is not allowed.

  • For function invocations (not methods) this === undefined.

    In non-strict code, this === invokes the global object.

Note: For more information on Strict Mode visit the w3school website topic JavaScript Use Strict (internet access required.)


Logging

Logging, or event logging, is a useful method of gaining meaningful information about the state of the application during deployed mode. For example, it can be used to log information about the project, such as project handling, camera discovery, state information or custom messages generated by a user's JavaScript code.

There are several ways to log messages while in deployed mode:

  • Logging to the Output window or a Browser's Console

    The JavaScript console.log() function is used for info-level log messages. The log() function is a built-in JavaScript function that is visible in the Cognex DesignerOutput window and a Web browser's console log. This log will also be routed to the controller's log system, so it is saved onto the controller.

    The controller $ Functions: System function, $System.Log.Write(), is used for implementing different log levels (error and warning). These logs are displayed in the Output window, but will not be shown in a Web browser's console log.

  • Logging to a File

    The controller $ Functions: System functions, $System.File.WriteText() or $System.File.AppendText(), can be used to log text information directly to a file on the public file system on the controller. All file paths used are relative to the public file system. Any directory can be used on the public file system, but if it does not exist, it will not be created. The user can create directories via an FTP connection to the controller.

    These functions are also callable from JavaScript and via WebPage Elements Event Handler Scripts.

    Additional System functions are available which allow one to check if a file exists, $System.File.Exists(), or delete an existing file, $System.File.Delete().

    Note:
    • Logging to a file adds the additional overhead of file IO operations (open-write-close) and increases execution time when compared to logging to memory.
    • Files within the public file system are not considered project data, except for the content of the specific project directories under the Projects subdirectory. Care must be taken to avoid inadvertently overwriting the files of another project


$ Functions

The "dollar functions" are those functions (and respective properties) that are included (and published) in the Cognex Designer API. Consider the dollar sign as a namespace, except that you do not have to put a point after it like in the case of the other namespaces (e.g. System.Diagnostics).

Basically, what you find in the Toolbox can be also accessed if you press $ in the Script Editor. If you attach, for example, a communications card, then the Toolbox will be populated with the relevant functions which you can now access either from there or by pressing $. Toolbox contents are dynamic, depending on where you are (e.g. in the Task Editor, or Page Editor, etc.).

$ Functions: Components

$ Functions: Databases

$ Functions: Devices

$ Functions: File System

$ Functions: HMI

$ Functions: Pages

$ Functions: System

$ Functions: Tasks

$ Functions: WebPages HMI


$ Functions: Components

Function | Property
 | Components.[Clock].Time - datetime
Components.[DiskMonitor].Refresh() |
 | Components.[DiskMonitor].Capacity – double
 | Components.[DiskMonitor].FreeSpace – double
 | Components.[DiskMonitor].IsRunning – bool
 | Components.[DiskMonitor].PercentFree – double
 | Components.[DiskMonitor].PercentUsed – double
 | Components.[DiskMonitor].UsedSpace – double
 | Components.[InactivityMonitor].IdleTime – Timespan
Components.[ShiftRegister].Add(item) |
Components.[ShiftRegister].Clear() |
 | Components.[ShiftRegister].Item0 → ItemN
Components.[Timer].Start() |
Components.[Timer].Stop() |
 | Components.[Timer].IsRunning - bool
 | Components.[Timer].OverrunCount - int


$ Functions: Databases

Function | Property
Databases.[Database].[Table].AddRow(col_values) |
Databases.[Database].[Table].Update(keyval,col_values) |
Databases.[Database].[Table].[Query].Run() |
 | Databases.[Database].[Table].[Query].Parameters.[Param]
 | Databases.[Database].[Table].[Query].Results.RowCount
 | Databases.[Database].[Table].[Query].Results.[Column].RowN


$ Functions: Devices

Function | Property
Devices.[Camera].Acquire() |
 | Devices.[Camera].IsConnected – bool
 | Devices.[Camera].Exposure – double
 | Devices.[Camera].Image – cogimage
 | Devices.[Camera].IsSimulation – bool
 | Devices.[Camera].NumberPending – int
 | Devices.[Camera].NumerReady – int
 | Devices.[Camera].TriggerMode - CogAcqTriggerModelConstants
Devices.[ImageFile].Acquire() |
 | Devices.[ImageFile].IsConnected – bool
 | Devices.[ImageFile].Image – cogimage
 | Devices.[ImageFile].IsSimulation – bool
Devices.[RS232].Flush() |
Devices.[RS232].Reconfigure() |
Devices.[RS232].Write(text) |
Devices.[RS232].WriteData(byte[]) |
 | Devices.[RS232].IsConnected – bool
 | Devices.[RS232].IsSimulation – bool
Devices.[TCPServer].Broadcast(text) |
Devices.[TCPServer].SendTo(object,message) |
 | Devices.[TCPServer].IsConnected – bool
 | Devices.[TCPServer].IsSimulation – bool
Devices.[TCPClient].Flush() |
Devices.[TCPClient].Send(text) |
 | Devices.[TCPClient].IsConnected – bool
 | Devices.[TCPClient].IsSimulation – bool


$ Functions: File System

Function | Property
FileSystem.DeleteFilesOlderThan(folder,time,rootOnly) |
FileSystem.ShowFolderDialog() |
FileSystem.ShowOpenFileDialog() |
FileSystem.ShowSaveFileDialog() |


$ Functions: HMI

Function | Property
HMI.ClosePage(pageName) |
HMI.ShowKeyboard(initialText, zoom) |
HMI.ShowKeypad(initialValue) |
HMI.ShowMessage(message) |
HMI.ShowError(errorMessage) |
HMI.ShowInformation(informationMessage) |
HMI.ShowPage(pageName) |
HMI.ShowQuestion(question) |
HMI.Invoke(functionName,args) |


$ Functions: Pages

Function | Property
 | Pages.[Page].IsActive
 | Pages.[Page].Name
 | Pages.[Page].Title
 | Pages.[Page].[Checkbox].State - bool
 | Pages.[Page].[DateTimeEntry].Value - DateTime
Pages.[Page].[VProDisplay].Fit(fitGraphics) |
Pages.[Page].[VProDisplay].Save(filename) |
Pages.[Page].[Display3D].Fit() |
 | Pages.[Page].[ListBox].SelectedIndex - int
 | Pages.[Page].[ListBox].SelectedVallue - object
Pages.[Page].[VideoPlayer].Pause() |
Pages.[Page].[VideoPlayer].Play() |
Pages.[Page].[VideoPlayer].Stop() |
 | Pages.[Page].[PasswordBox].Password - string
 | Pages.[Page].[Slider].Value - double
Pages.[Page].[Table].GetSelectedRow() |
Pages.[Page].[Table].ManualUpdate() |
 | Pages.[Page].[Table].RowCount - int
 | Pages.[Page].[Table].SelectedRowIndex - int
 | Pages.[Page].[Textbox].Text - string


$ Functions: System

Function | Property
System.AuditTrail.Log(category, message) |
System.Alarms.Acknowledge(alarmName) |
System.Alarms.AcknowledgeAll() |
 | System.Alarms.AnyActive - bool
 | System.Alarms.AnyUnacknowledged – bool
 | System.Alarms.[Alarm].CurrentMessage – string
 | System.Alarms.[Alarm].Description - string
 | System.Alarms.[Alarm].Group - string
 | System.Alarms.[Alarm].IsAcknowledged – bool
 | System.Alarms.[Alarm].IsActive – bool
 | System.Alarms.[Alarm].Name - string
 | System.Alarms.[Alarm].OffMessage - string
 | System.Alarms.[Alarm].OnMessage - string
 | System.Alarms.[Alarm].Priority - int
 | System.Alarms.[Alarm].State – string
 | System.Alarms.[Alarm].StateCode - int
 | System.Alarms.[Alarm].TimeTriggered - DateTime
System.Devices.SetSimulationDevice(deviceName, simulationDeviceName) |
System.Log.Write(string message) |
System.Log.WriteException(string message, exception) |
System.Shutdown() |
System.Debug.Break() |
System.GetInternalObject(string path) |
 | System.Info.DevModeEnabled – bool
System.Info.GetUptimeMilliseconds() |
 | System.Info.ProjectPath - string
System.Invoke(functionName,args) |
System.InvokeAsync(functionName,args) |
System.Recipes.[Recipe].Contains(name) |
 | System.Recipes.[Recipe].CurrentDescription - string
 | System.Recipes.[Recipe].CurrentName - string
System.Recipes.[Recipe].Load(name) |
System.Recipes.[Recipe].Remove(name) |
System.Recipes.[Recipe].Save(name,description) |
System.Tags.ReadTag(tagName) |
System.Tags.WriteTag(tagName,tagValue) |
System.Users.AddUser(username,password,args) |
 | System.Users.CurrentUsername – string
System.Users.ChangePassword(username,password) |
System.Users.DeleteUser(username) |
System.Users.Login(username,password) |
System.Users.Logout() |
System.Users.UserExists(username) |


$ Functions: Tasks

Function | Property
Tasks.[Task].Run() |
 | Tasks.[Task].ExecutionTime – double
 | Tasks.[Task].HasError - bool
 | Tasks.[Task].IsRunning - bool
 | Tasks.[Task].TriggerEnabled - bool
 | Tasks.[Task].[Task].ExecutionTime – double
 | Tasks.[Task].[Task].HasError - bool
 | Tasks.[Task].[Task].IsRunning - bool
Tasks.[Task].RunAsync() |


Adding References and Using Statements

Adding References

Cognex Designer scripting is based on C# .NET, thus functions can be called from external .NET libraries.

  1. When you are editing a script, go to the Properties tool windows and click the ... button to edit the references.

  2. This opens the Script References dialog, as shown below:

  • Project References: Displays a list of all the DLLs that are referenced in the project, for all scripts in the project.
  • Local References: Displays a list of all the DLLs the script being currently edited references.
  • Discovered References: Provides a list of the common DLLs that can be referenced.
  • The Add File button allows the user to add custom .NET DLLs/assemblies that are not contained in the Discovered References list. An Open File dialog will be opened, where you can navigate to the desired DLL/assembly file.
Note: When an external reference is added to a script, it will be loaded into the application. If you change the external reference (e.g. add a new type to the custom DLL, or change an existing type), the changes will not be reflected until Designer is restarted.

Calling External Code with Using Statements


Calling External Code with Using Statements

Calling External Code and Using Statements

When calling code from an external DLL, you will need to use the full namespace of the functions that you want to use.

You can also define Using statements for your project. To add a Using statement, click on the drop-down indicator and type in the drop-down box.

While not necessary, they help simplify the process of specifying namespaces. For example, if your script references certain DLLs, like a VisionPro DLL (e.g. Cognex.VisionPro.Core.dll), by specifying Using statements for the namespace (e.g. Cognex.VisionPro and/or Cognex.VisionPro.PMAlign), you can use types from these namespaces with their "short" name (e.g. if you wanted to create a new PMAlign pattern object, using CogPMAlignPattern pattern = new CogPMAlignPattern();).

However, if you do not provide a Using statement for the CognexPMAlignPattern namespace, the "short" name code (CogPMAlignPattern pattern = new CogPMAlignPattern();) will not compile. You would have to use the "full" name, i.e. namespace + class name (e.g. Cognex.VisionPro.PMAlign.CogPMAlignPattern pattern = new Cognex.VisionPro.PMAlign.CogPMAlignPattern();).


User Scripts

Cognex Designer User Scripts are defined functions that can be called from other scripts in the project, which allows users to create reusable code that is easy to understand.

Note: User Scripts are re-entrant, i.e. the same script can be executed at the same time, across different threads.

Creating a User Script

Organizing User Scripts


Creating a User Script

Create a User Script

This topic provides an example for creating a user script.

  1. To create a User Script, right-click on the User Scripts node in the Project Explorer and select New Script, which will launch the Script Definition Editor. You will then be asked to specify the Name, Arguments (inputs) and the Return Type (output).

  2. In this example we are creating a Script called MyTestScript.
  3. It has two input arguments: string message and int count. The script will return a string variable.
  4. Once you click Accept, Cognex Designer will open the Script Editor for this script.

  5. Once the script has been saved, it can be called from another script, as shown below.

    string resultText =  MyTestScript("Hello",99 );


Organizing User Scripts

User Scripts can be organized into folders to make it easier to manage when there are a large number of scripts.

  1. To add a folder, right-click on the User Scripts node in the Project Explorer and select New Folder.

  2. This will create a new folder in the User Scripts node.
  3. You can then drag and drop scripts into this folder.


Data Change Scripts

Data Change Scripts are scripts that are executed whenever a tag value changes.

  1. To add a new script, under Scripting in the Project Explorer, right click on the Data Change Scripts category and select New Script.

  2. This opens the Tag Selector dialog, where you can select the tag you want to create the script for.

  3. This will create a new item under the Data Change Scripts node, and opens a new Script Editor where you can write the code to execute on data change.


Data Change Scripts (WebHMI)

Data Change Scripts (WebHMI) are scripts that are executed whenever a tag value changes while running in the WebHMI. These scripts are used to monitor and perform actions when tags associated with WebPages are modified or change state. Refer to WebPages HMI Scripting for more information.

  1. To add a new script, under Scripting in the Project Explorer, right click on the Data Change Scripts (WebHMI) category and select New Script.

  2. This opens the Tag Selector dialog, where you can select the tag you want to create the script for.

  3. This will create a new item under the Data Change Scripts (WebHMI) node, and opens a new Script Editor where you can write the code to execute on data change.

    Note:
    • If you create a data change script (WebHMI) on a complex object (for example, an Image or Dictionary), then you will not get the changed value as an input to the script. Instead, it will always be null.
    • The script is executed on each active web client. If no browser is connected the script will not run. If two browsers are connected the script will run twice.


DataSet Data Type

The DataSet Data Type provides an intuitive way to organize, access and visualize data. A DataSet variable stores tabular data consisting of named columns, each of which can be of a different Data Type, and several rows.

Used with WebPage Elements, such as the Controls DataTable, and Bar, Pie and Trend Charts, to graphically display tabular data while the project is in deployed mode.


Key Scripts

Cognex Designer Key Scripts are scripts that are executed when a specific key combination is pressed.

  1. To create a new script, under the Scripting node of the Project Explorer, right-click on the Key Scripts node and select New Script.

  2. Select the specific key combination that the script should execute on, and then press the Accept button.

  3. In the Script Editor, enter the code you want to execute and once the script successfully compiles, press the Save icon.


Script Example

For the complete list of Designer sample codes, please visit the Cognex Designer Support site.

The example below is taken from the AuditTrail sample sample application:

// must have user and password in local user database  - see user management help topic
// place in script for mousedown action of a command button

// will need to replace hardcoded variables in the if statement with text from a textbox and a passwordbox
// example reference:  $Pages.Page.TextBoxUserName.Text and $Pages.Page.passwordbox.Text
string username = "Engineer";
string password = "eng";

//-------------------
//The Login And Log function

// Get current user before login starts
string prevUser = $System.Users.CurrentUsername;

if ($System.Users.Login(username, password))
{
    string msg = prevUser + " logged in as " + username + ".";
    $System.AuditTrail.Log(prevUser + " logged in as " + username, "Users");
    $HMI.ShowInformation( username + " has been successfully logged in.", "Login Success");
    return true;
}
else
{
    string msg = prevUser + " failed to login as " +  username + ".";
    $System.AuditTrail.Log(msg, "Users");
    $HMI.ShowError(msg, "Login Failed");
    return false;
}


Accessing VisionPro Objects from Script

Users can access the VisionPro internal API classes through the $System.GetInternalObject() function, e.g. $System.GetInternalObject(string path). This allows interactions with objects such as the range and encoder modes for Cognex Displacement Sensor cameras.

The list of components currently implementing the interface:

Class | Access Path | Internal API Class | Referenced DLLs
VisionProCamera | $System.GetInternalObject("Devices.CameraName") | ICogAcqFifo | Cognex.VisionPro.Core
VisionProToolBlock | $System.GetInternalObject("Tasks.Task.Task.ToolBlock") | CogToolBlock | Cognex.VisionPro.ToolBlock
ImageDisplay | $System.GetInternalObject("Pages.Page.VisionProDisplay") | CogRecordDisplay | Cognex.VisionPro.Controls
ImageDisplay3D | $System.GetInternalObject("Pages.Page.VisionProDisplay3D") | ICog3DDisplayV2 | Cognex.VisionPro3D.Display.Controls
CC24Device | $System.GetInternalObject("Devices.CommCardName") | CogCommCard | Cognex.VisionPro.Comm
Note: When using $System.GetInternalObject(), ensure that the reference DLLs are added.
  1. Add Cognex.VisionPro and Cognex.VisionPro.Display to your Using statements.
  2. Add Cognex.VisionPro.Controls to your Project References.

  3. Use similar code:

    CogRecordDisplay internalObject = $System.GetInternalObject("Pages.Page.ImageDisplay") as CogRecordDisplay;


Scripting Tips in a Task

  • When scripting, you can add the reference for Cognex.Designer.Sequences.dll
  • To rename or view scripts of a Task (On Error and On Complete), right-click on the Task and select Scripts.
  • Note: If scripting will be utilized, it is advised to write the tag value in the script, versus writing to the output pin of a Block.

  • In Tag Browser, you can access the properties of each Task.


Keypad and Keyboard Script Functions

Cognex Designer provides two user-callable functions that can be used to open a Keypad or Keyboard:

$HMI.ShowKeypad(double initialValue, int decimalPlaces, double zoom)

Or

$HMI.ShowKeyboard(string currentText, bool hideCharacters, double zoom)


Components

Components are reusable objects that provide specific application functionality, and can be added using the Component Browser.

  1. To access the Component Browser, right-click the Components node in the Project Explorer and select Configure.

  2. To add a Component, select from the Process and/or Utilities nodes, select the desired Component and press the Add button. Once all the desired Components have been added, press the Accept button to close the Component Browser.

  3. Once the Component has been added, they will appear under the Components node in the Project Explorer.

Clock

Timers

Shift Register

Inactivity Monitor

Disk Monitor


Clock

The Clock Components is used to return the current time.

Control | Description
Name | The name of the clock.
Offset (h) | Specifies an optional time offset (in hours), which can be used to display a different time zone.

Tags & Functions

Tag | Description
Time | Returns the datetime value from the clock.


Timers

There are two Timer Components that can be used to execute custom code at a specified "tick" interval.

Note: The OnTick() script can be used to define the custom code for the timer. After adding a Timer device, right-click the Timer device in the Project Explorer, and select On Tick from the Scripts menu. If, for example, the application should execute the Task when the Timer "ticks" to its next interval, the $Tasks.Task.Run(); script would be added to the OnTick() script.

  • High Precision Timer

    The High Precision Timer is useful for executing code at very small intervals (for example high-speed functionality, reading I/O lines), with a higher degree of accuracy. It can be set to an interval of 1 millisecond.

    There are a limited number of High Precision Timers available per system; Cognex recommends that no more than 3 or 4 High Precision Timers be used, per project.

  • Standard Timer

    The Standard Timer is suitable for most user-interface updates, and other non-critical items (or example, updating the HMI status periodically). It can be set to an interval of 20-30 milliseconds.

    There is no limit on how many standard timers you can run per project.

    Note: The standard timer runs on the UI thread, so it can block the UI if a long running process is performed in the OnTick() script.
Control | Description
Name | The name of the timer.
Interval | The rate at which the timer should tick, in milliseconds.

Tags & Functions

Tag | Description
Start() | Function that starts the timer.
Stop() | Function that stops the timer.
IsRunning | A Boolean tag indicating whether or not the timer is running.
OverrunCount | Measures the time taken to run the OnTick() script; if the time to run the OnTick() script is longer than the specified Interval value, the OverrunCount value will be incremented by 1. Note: The OverrunCount tag only applies to the High Precision Timer.


Shift Register

The Shift Register Components provides an array of tags of a particular data type. When a new item is added to the shift register, previous items in the register are shifted in position.

Control | Description
Name | The name of the shift register.
Data Type | The data type of the shift register tags.
Buffer Size | The number of shift register tags to create.

Tags & Functions

Tag | Description
Add(item) | Function that adds a new item of the specified data type to the register.
Clear() | Function that removes all items from the register.
Item[0 -> N] - Item[BufferSize] | An array of tags containing the register items.
ItemCount | The maximum amount items that can be stored in the Shift Register.


Inactivity Monitor

The Inactivity Monitor monitors the time since the user last performed any kind of input to Windows (Mouse movement, key press, etc.) and calculates the length of the inactivity time. The monitor provides a configurable timeout script that can be executed when the inactivity time exceeds the specified amount.

Control | Description
Name | The name of the inactivity monitor.
Timeout | The inactivity timeout period; when exceeded the Component will execute the timeout script.

Tags & Functions

Tags | Description
IdleTime | Tag that stores the latest calculated inactivity time. This is updated every 3 seconds.


Disk Monitor

The Disk Monitor Components allow users to monitor disk space usage on a specified hard disk.

Control | Description
Name | The name of the disk monitor.
Drive | The disk drive to monitor.
Interval | Specifies how often (in minutes) to check the selected drive.

Tags & Functions

Tag | Description
Capacity | The disk space capacity for a drive (in gigabytes).
FreeSpace | The total free disk space (in gigabytes).
IsRunning | Whether or not the monitor is running.
PercentFree | The percentage of disk space free.
PercentUsed | The percentage of disk space used.
Refresh() | Scans the selected disk and updates all of the free/used space tags.
UsedSpace | The total amount of disk space used (in gigabytes).


Devices

A Device is an object that can connect to something, and has the notion of being connected and disconnected, such as a camera, I/O card and/or a server. Once a Device has been added, they can become Reference Blocks that are added to a Task.

Cameras

Communications

Simulating Devices


Cameras

Cognex Designer supports several types of cameras and frame grabbers, and up to four cameras may be connected. This can be any combination of Cognex Industrial Cameras (CIC), as well as the Cognex Displacement Sensor (DS) 3D sensors.

Note: For more information regarding which specific cameras and frame grabbers are supported in Cognex Designer, please consult the cameras.html file, which is included with the VisionPro software, in the Doc directory of the VisionPro installation.

Camera Device

Image File


Camera Device

The Camera device is used to establish a connection to a camera and/or frame grabber.

Note:
  • Prior to adding GigE cameras to Cognex Designer, the camera must be configured using the Cognex GigE Vision Configuration Tool. This utility can be accessed from the Utilities tab of the Designer Launcher. See the Cognex Designer Launch Page - Utilities topic for more information.
  • A camera cannot be connected to both an CogAcqFifoTool in a VisionPro Tool Block and as a Device in Designer.
Control | Description
Name | Specifies the name of the camera. Tip: Cognex recommends giving your camera a unique name, such as "Camera1" or "Camera2". This is helpful when creating Templates that are easily reusable for multiple camera projects.
Camera | Specifies the type of camera/frame grabber.
Video Format | Specifies the video format used to acquire images (this setting is dependent upon the type of camera/frame grabber used).
Related Topics

The following topics can be referenced in the VisionPro® Online Documentation:

  • Configuring an Image Source
  • Acquiring From a Connected Camera

Camera Properties


Camera Properties

The following properties are available in the Toolbox while in the Script Editor, and may be useful when programming a Camera device:

Property | Description
Acquire | Tells the Camera to take a new image.
BeginAcquire | Tells the Camera to begin acquiring a new image.
EndAcquire | Tells the Camera to end acquiring.
Exposure | Exposure time in milliseconds. The special value of zero indicates to use the smallest supported time.
Image | The latest image taken by the Camera.
IsConnected | The Camera is connected and working correctly. Note: This property is only updated prior to Designer being started.
IsSimulation | The Camera is in simulation mode.
NumberPending | Indicates the number of acquisition that are queued and waiting to be acquired.
NumberReady | Indicates the number of acquisitions that have been completed and are ready for inspection.
TriggerModel | Specifies the type of trigger used to start the Camera’s image acquisition.


Image File

Image File Device

The Image File device simulates a camera by using a single image, or a set of images in a folder.

  1. To add an Image File device, from the Project Explorer > Devices node, right-click Cameras, then select Add 'Image File' Device.
  2. Once the Image File device has been added, it can be used in a Task and configured. It will appear under the Devices node of the Task Toolbox.
Control | Description
Name | The name of the image file device.

Image Source Selection

Image File Properties


Image Source Selection

After the Image File device has been added, an icon for the newly created device will appear under the Devices > Cameras node of the Project Explorer. Double-click the device to specify an image or a directory of images through the Image Source Selection dialog.

Press the Choose File... button to navigate to a specific image file, or press the Choose Directory... button to navigate to a directory of images.


Image File Properties

The following properties are available in the Toolbox while in the Script Editor, and may be useful when programming the Image File device:

Property | Description
Acquire | Tells the Image File device to load a new image.
Filename | The full file name of the latest image loaded by the Image File device.
Image | The latest image loaded to the Image File device.
IsConnected | The Image File device is connected and working correctly.
IsSimulation | The Image File device is in simulation mode.


Communications

Cognex Designer supports several different types of communication Devices, such as I/O (physical and simulated), and serial and TCP/IP communications.

Cognex Communications Card

RS232

TCP/IP


Cognex Communications Card

Cognex Designer supports both the Cognex Vision Controller (Cognex Communication Card 24A) or a standalone PC I/O card (Cognex Communication Card 24C). Both of these Devices can also be simulated.

Note: The EtherNet settings of the Cognex Communication Card must be configured prior to adding the device to Cognex Designer. First run the "Cognex Comms Card Configurator" utility to configure the EtherNet settings on the card (located in the Windows Start Menu > Cognex > VisionPro > Utilities directory). For more information, see the Network Configuration topic.

All physically connected cards will be automatically displayed (e.g. CC24 followed by the card's serial number) under the Devices > Cognex Communications Card node of the Project Explorer. Simply right-click the card and select Connect to add the card as a Device.

After a card has been added, it can be configured for use in a Task and its API will be accessible via scripting in the Script Toolbox, and as tags in the Tag Browser.

CC24 Device

CC24 Simulator


CC24 Device

The CC24 Device is used to establish a connection to the I/O card on a Cognex Vision Controller or a standalone PC I/O card.

To add a CC24 Device, right-click Cognex Communication Cards, then select Add > 'CC24' Device.

Control | Description
Name | Specifies the name of the device.
Factory Protocol | Specifies the factory floor protocol (EtherNet/IP, PROFINET or SLMP) that should be used for communication.
Index | Specifies the indexed hardware slot of the board.

Precision IO Configuration Editor


CC24 Simulator

The CC24 device is used to establish a connection to a simulation I/O card of a Cognex Vision Controller or a standalone PC I/O card.

To add a CC24 simulator device, right-click Cognex Communication Cards, then select Add > 'CC24 Simulator' Device.

Tip: This Device option is helpful when the communication card cannot be connected to during development.
Control | Description
Name | Specifies the name of the device.
Simulator Type | Specifies the type of I/O card to simulate, a PC I/O card or a Vision Controller I/O card.


RS232

The Cognex Designer RS232 device allows you programmatic access to a serial port on the PC.

Control | Description
Name | Specifies the name of the serial device.
COM Port | Specifies the serial port connection. Note: When connecting to a Vision Controller, Designer displays COM1 and COM2 as possible COM Port settings; use COM1.
Baud Rate | Specifies the baud rate for the connection.
Parity | Specifies the parity-checking protocol for the connection.
Data Bits | Specifies the standard length of data bits, per byte, for the connection.
Stop Bits | Specifies the standard number of stop bits, per byte, for the connection.
DTR Enabled | Specifies whether or not to enable the Data Terminal Ready (DTR) signal during serial communication (disabled by default).
Buffer Size | Specifies the size (minimum 1 byte; default = 4096) of the received data buffer for the serial device. Note: This setting can be used in conjunction with the Receive Data block.
Number of Buffers | Specifies the number of buffers (minimum 1 buffer; default = 10) for the received data for the serial device. Note: This setting can be used in conjunction with the Receive Data block.

Serial Port Events

Writing to the Serial Port

Reconfiguring a Previously Configured RS 232 Device


Serial Port Events

The serial port has three events (script points), which are accessible by right-clicking the serial device in the Project Explorer.

Before invoking the On Data Received method, ensure that if you transmit ASCI text, all data sent and received must be ASCI text and both sender and receiver must be using the same encoding algorithm. Sending or receiving non-ASCI text may result in data loss and unexpected results.

Serial Port Events Description
On Data Received ()

Will be raised whenever new data is received by the serial port device. The event argument contains the received data as a string (using UTF-8 encoding).

Note: See the Microsoft Developer Network Help for more information.
On Error Received ()

Will be raised whenever new data is received by the serial port device. The event argument contains the received data as a string (using UTF-8 encoding).

Note: See the Microsoft Developer Network Help for more information.
On Pin Changed ()

Will be raised whenever a non-data signal event has occurred on the port represented by the serial device.

Note:
  • See the Microsoft Developer Network Help for more information.
  • This script point does not correspond to the Cognex Designer implementation of input or output pins on Task Blocks.


Writing to the Serial Port

The serial port can be written to programmatically in a script, using the following methods:

Function | Description
Flush() | Flushes all buffers of the device by script. This method can be used to consume the device's buffers if it is not consumed otherwise (e.g. an attached Receive Data block).
Write(string) | Writes a string to the serial port with ASCII encoding (e.g. RS232.Write("HelloFromVS").
WriteData(byte[]) | Writes an array of bytes to the port (e.g. RS232.WriteData(new Byte(){0,8,0,255,64,64}).
Reconfigure()

Reconfigures properties of the serial device while the project is in deployment mode (aka runtime). Takes a Dictionary data type, which stores the new parameters of the device.

Note: For more information about using this method, see the Reconfiguring an RS 232 Device Through Script topic.


Reconfiguring a Previously Configured RS 232 Device

There are two different methods for reconfiguring an RS 232 Device for a project: through the Cognex Designer User Interface and through script.

The method of reconfiguring the project using the Designer UI can be done while the project is in development mode; the script method allows changes to be made while the project is in deployment mode (aka runtime).

Reconfiguring an RS 232 Device Through the Designer UI

Reconfiguring an RS 232 Device Through Script


Reconfiguring an RS 232 Device Through the Designer UI

This method should be used before the project is put in runtime mode.

If you have already created and connected to an RS232 device, and then want to deploy the project to a new environment that has another RS232 device with different configuration options, the RS232 device will have a broken link icon beside it.

  1. To use the new device, from the Project Explorer, right-click on the RS232 device and select Reconnect.

  2. This will launch the Parameter Configuration dialog, which will allow you to reconfigure the settings accordingly (allowing you to retain any previously constructed scripts).


Reconfiguring an RS 232 Device Through Script

If you have already created and connected to an RS232 device, and then want to deploy the project to a new environment that has another RS232 device with different configuration options, the script options allow you to make changes while the project is in deployment mode (aka runtime).

Note:
  • More than one property can be reconfigured at a time.
  • Every time that the reconfiguration method is called, the RS 232 Device will be disconnected and the connection will then attempt to be reconnected.
  • You can verify that the reconnection was successful by monitoring the RS 232 Device's IsConnected property.

The properties of the RS 232 Device are:

Property Name | Data Type | Default Value
Port | String | "COM1"
BaudRate | Integer | 19200
DataBits | Integer | 8
Parity | Parity | System.IO.Ports.Parity.None
StopBits | StopBits | System.IO.Ports.StopBits.One
DtrEnable | Boolean | False
BufferSize | Integer | 4096
NumberOfBuffers | Integer | 10

Example:

//Get the port to use
string portToUse = "COM2";
int baudRateToUse = 9600;

//Create the collection of property names - value pairs.
var newProperties = new Dictionary<string, object>();

//Add the properties that you wish to change.
newProperties.Add("Port", portToUse);
newProperties.Add("BaudRate", baudRateToUse);

//Apply the new property values.
$Devices.[SerialDeviceName].Reconfigure(newProperties);


TCP/IP

The Cognex Designer TCP/IP devices support two modes: Client & Server. These can be used as programmatic channels to talk to other TCP/IP devices. All data sent and received is converted into an ASCII string.

TCP/IP Server

TCP/IP Client


TCP/IP Server

Connects to a remote TCP Server.

Note:

If you have already created and connected to a TCP/IP device (Client and/or Server), and then want to deploy the project to a new environment that has another TCP/IP device with different configuration options, the TCP/IP device will have a broken link icon beside it.

  1. To use the new device, from the Project Explorer, right-click on the TCP/IP device and select Reconnect.

  2. This will launch the Parameter Configuration dialog, which will allow you to reconfigure the settings accordingly (allowing you to retain any previously constructed scripts).

Control | Description
Name | The name of the server.
Port Number | Specifies the port number over which to communicate; this TCP port must be open across all firewalls in order to work.

TCP/IP Server Events

TCP/IP Server Methods


TCP/IP Server Events

The TCP Server has three events that scripts can be hooked into. Once the Server is loaded, you can access it using scripts. Right-click the newly created TCP/IP Server device, select Scripts and choose from On Data Received, On Client Connected or On Client Disconnected.

Before invoking the On Data Received method, ensure that if you transmit ASCI text, all data sent and received must be ASCI text and both sender and receiver must be using the same encoding algorithm. Sending or receiving non-ASCI text may result in data loss and unexpected results.

Event | Description
Data Received | This event occurs when data is received on the TCP Server.
Client Connected | This event occurs when a new client establishes a connection.
Client Disconnected | This event occurs when a client disconnects from the server.


TCP/IP Server Methods

The TCP/IP Server has two methods:

Method | Description
Broadcast(message) | Sends the message to all connected clients.
SendTo(client, message) | Allows a message to be sent to a specific client. The client object is of the type Devices.TCPIP.TcpServerConnectionInfo, and is passed through the Client Connected, Client Disconnected and Data Received script events.


TCP/IP Client

Allows numerous client connections.

Note:

If you have already created and connected to a TCP/IP device (Client and/or Server), and then want to deploy the project to a new environment that has another TCP/IP device with different configuration options, the TCP/IP device will have a broken link icon beside it.

  1. To use the new device, from the Project Explorer, right-click on the TCP/IP device and select Reconnect.

  2. This will launch the Parameter Configuration dialog, which will allow you to reconfigure the settings accordingly (allowing you to retain any previously constructed scripts).

Control | Description
Name | The name of the client device.
Remote Address | The IP Address of the TCP Server.
Port | Specifies the port number over which to communicate; this TCP port must be open across all firewalls in order to work.
Buffer Size | Specifies the size (minimum 1 byte, maximum 67108864 bytes; default = 8192) of the received data buffer for the TCP client device. The buffers are used to queue incoming messages. For example, if the Receive Data block is being used in a Task, and the block executes after the message was actually received, the message will be stored in the buffer, and processed the next time the block executes. Note: This setting can be used in conjunction with the Receive Data block.
Number of Buffers | Specifies the number of buffers (minimum 1 buffer, maximum 65536 buffers; default = 10) for the received data for the TCP client device. Note: This setting can be used in conjunction with the Receive Data block.

TCP/IP Client Events

TCP/IP Client Methods


TCP/IP Client Events

TCP Client hooks into the Data Received event.

Before invoking the On Data Received method, ensure that if you transmit ASCI text, all data sent and received must be ASCI text and both sender and receiver must be using the same encoding algorithm. Sending or receiving non-ASCI text may result in data loss and unexpected results.

Event | Description
Data Received | This event is triggered when new data has been received by the client.


TCP/IP Client Methods

The TCP/IP Client has two methods:

Method | Description
Send (message) | Sends a message to the client's server.
Flush () | Flushes all buffers of the device by script. This method can be used to consume the device's buffers if it is not consumed otherwise (e.g. an attached Receive Data block).


Simulating Devices

Both Cameras and Cognex Communications Card Devices can be simulated, enabling development to occur without the device being physically connected, by either right-clicking the device under the Devices node of the Project Explorer and selecting Simulate, or programmatically by using the SetSimulationDevice function.

Simulating a device is helpful during application development of your project. For example, if you had a camera and you wanted to simulate your application without having the camera continually acquiring images, you could have a Camera Device being simulated by an Image File Device. This allows you to mimic your application by having the Image File device point to a database of acquired images, and pass those images into your Task, instead of using the real Camera device. When configured in this way, you can leave the Camera block in the Task, and you do not have to replace it with an Image File block.

Note: For the Cognex Communications Card, if a CC24 Device is not installed in the PC, before creating a simulation of the CC24 Device, you must create a disconnected version of the device. Follow the steps for adding a CC24 Device, and ensure that the Index is set to 0, so once the project is moved to a PC with a CC24 Device installed, it will automatically replace the disconnected version with the CC24 Device present in the PC. Then, follow the steps outlined in the Enabling a Simulation Device to create a simulation of the disconnected CC24 Device.

You can also have multiple simulation devices, and change between the different simulators.

Enabling a Simulation Device

Changing a Simulation Device

Disabling a Simulation Device


Enabling a Simulation Device

Before beginning, add the simulation device.

  • For Cameras, right-click the Cameras node and select Add > 'Image File' Device.
  • For a Cognex Communications Card, right-click the Cognex Communications Cards node and select Add > 'CC24 Simulator' Device.

  1. Right-click the Camera or Cognex Communications Card Device that you want to simulate, and from the right-click menu, select Simulate.

  2. This will open the Select Simulation Device dialog.

  3. Select the simulation device from the list in the dialog, and press the Accept button.

  4. The name of the real device will now be appended with the simulation device name in the Project Explorer.

Programmatically Enabling a Simulation Device


Programmatically Enabling a Simulation Device

To enable the simulation of a Camera or Cognex Communications Card programmatically, use the SetSimulationDevice function. This example is based on a Camera device and an Image File device, where the Camera device is named Camera_01, and the Image File device is named Camera_Simulator.

SetSimulationDevice takes two arguments, the first being the name of the actual device, and the second being the simulation device: $System.Devices.SetSimulationDevice(deviceName, simulationDeviceName)

Use the following call to enable the simulation of the Camera device: $System.Devices.SetSimulationDevice("Devices.Camera_01", "Devices.Camera_Simulator")

Note: You can also programmatically change the simulation device by providing the new simulation device name (e.g $System.Devices.SetSimulationDevice("Devices.Camera_01", "Devices.Camera_Simulator2").


Changing a Simulation Device

If you have configured multiple simulation devices, you can change between the different simulation devices.

  1. Select the device being simulated in the Project Explorer.

  2. Right-click and select Change Simulation.

  3. This will open the Select Simulation Device dialog.

  4. Select the simulation device from the list in the dialog, and press the Accept button.

  5. The name of the real device will now be appended with the new simulation device name in the Project Explorer.


Disabling a Simulation Device

  1. Select the device being simulated in the Project Explorer.

  2. Right-click and select Disable Simulation.

Programmatically Disabling a Simulation Device


Programmatically Disabling a Simulation Device

To disable the simulation of a Camera or Cognex Communications Card programmatically, use the SetSimulationDevice function. This example is based on a Camera device and an Image File device, where the Camera device is named Camera_01, and the Image File device is named Camera_Simulator.

While SetSimulationDevice takes two arguments, the first being the name of the actual device, and the second being the simulation device, to disable the simulation, the second argument is passed an empty string.

Use the following call to disable the simulation of the Camera device: $System.Devices.SetSimulationDevice("Devices.Camera_01", "")


Databases

Cognex Designer allows access to different database types, including Microsoft® SQL Server® and SQLite databases, along with the creation of Designer databases.

Note:
  • Designer only supports a limited number of data types, and may incorrectly interpret certain data types. For more information, see the Creating/Modifying a SQLite Database Without Designer topic.
  • Designer does not close the connection to a previous database when the path to a SQLite database is updated. You must restart Designer to close the connection.
  • A SQL query of a database cannot be performed via script.
  • Do not use the ANALYZE command on a database being used by Designer.

Databases - Best Practices

Creating a SQLite Database

Connect to an SQL Server Database

Writing to a Database

Querying a Database

Showing Query Results


Databases - Best Practices

The following are guidelines to consider when building Databases for your project:

  • For tables, create an index to speed up queries.

    When creating an index, use only a single index per table, and the index should contain each column that will be used in a WHERE or ORDER BY statement. The order of columns in the index matters; columns used in WHERE statements should occur before columns that only appear in ORDER BY statements.

    The larger the database, the greater the impact on insert performance. This issue is more likely to be noticed when using the default mode (leaving the Enable Unsafe Write (Fast Mode) checkbox unchecked).

    Note: For more information, see the Creating a SQLite Database topic.

  • Limit the number of rows returned by a query.

    Before creating a table, consider how many rows will actually need to be displayed to the user; less rows equals faster query times. In general, the user does not need to know the entire row history, every time. Instead, for example, consider limiting it to the last seven days, or provide a better filter mechanism.

  • The first column of a table should be the row's unique ID.

    The first column of a table should be used to uniquely identify each row. This is standard practice for databases, and allows the {TableName}.Update method to be used correctly.

    The {TableName}.Update method is a helper function that is used to update values on a specific row, e.g. $Databases.FastDatabase.Results.Update(value1, value2, value3), which translates to a SQL Update statement of: UPDATE Results Set Col2=value2, Col3=value3 WHERE Col1=value1.

  • Backing up and restoring a database.

    Currently, Designer does not support backing up and restoring a database, this must be implemented by the user.

    Note: To restore a database, Designer must be closed before replacing the .db3 file.

  • Do not save image data in a database.

    Instead of saving image data in a database, save a relative link to the image file. Store the root image folder path as a tag, so that when the project is deployed or the Designer application is moved, you can easily continue to work with the database.

    In addition, you can use %Environment_Variables% in the string input for the RootDirectory pin on an Image Recorder block. If using this option, use %PROJECT_PATH% in the string to so it is relative to the project folder (e.g. $ImageSavePath = "%PROJECT_PATH%\\Images";). This ensures that when the project is being developed, it will be saved into the project folder, and when the project is deployed, it will use the automatically use the Deployed Folder path.

  • Default "Safe" Mode or Enable Unsafe Write (Fast Mode)

    Cognex recommends using the default "safe" mode, unless attempting to address a specific performance issue. There is no difference in the execution time for queries that read from a database (e.g. SELECT); it only affects statements that write to a database (e.g. INSERT, UPDATE, DELETE, etc.).

    When Enable Unsafe Write (Fast Mode) is enabled, Designer will offload the writing to the database to an asynchronous buffer, which means that there should not be a direct Disk I/O performance hit when altering a database. However, this option does present some risks:

    • If a hard reset/power cycle happens to the PC at an inopportune time, the database can become corrupted. For example, if the PC is not properly shutdown before an operator power cycles the entire line, or if the main power is cut at the end of a shift.
    • Stopping Designer via a Windows Task Manager End Process command can possibly corrupt the project.
    • The only option to recover from such a scenario is to manually revert to a backup copy of the database.
    • If the database is missing at startup, a new one will be automatically created, without an error prompt or warning.
    Note: If using Enable Unsafe Write (Fast Mode), the following SQLite settings will be set automatically: Journal Mode = In Memory and Synchronous Mode = Off.

    The following graphic of a Task with two different Database Writer blocks, one using the default, "safe" mode, and the other with Enable Unsafe Write (Fast Mode) enabled, illustrates the difference between the two modes:

  • Enable the Publish Query Results as Tags checkbox.

    This allows properties of Page elements to be easily bound to a small set of results from a database.

    It is also highly recommended that rows NOT be processed via a script. Instead, see the Iterate Through Rows of a Query topic for an alternative approach.

    Note: For more information, refer to the Advanced Query Options topic.

  • The Reverse Row Index Parameter

    While this option exists in the Advanced Query Options dialog, Cognex recommends that this checkbox not be enabled. This option performs an in-memory reverse of the query results, and should only be used if a large performance hit is being encountered by using the ORDER BY statement. However, before implementing this option, first consider reexamining how the index is being used.


Creating a SQLite Database

  1. To create a new (or connect to an existing) SQLite database, in the Project Explorer, right-click on the Databases node and select New Database. This will launch the New Database dialog.

  2. Select the directory and enter a name for the database in the Directory and File name fields.

    Note: If connecting to an existing SQLite database, use the browse button beside the File name field to locate a directory other than the default directory for the database. The default directory is located at: C:\Users\<user_name>\Documents\Cognex Designer\Projects\<Project_Name>\Data

  3. Check the Enable Unsafe Write (Fast Mode) checkbox to allow the Windows operating system to handle sending data to the database. This mode is similar to an "asynchronous mode" and provides for faster insert and update times. However, this option has the risk of the database being corrupted if the PC running Designer is not shutdown properly.

    Note: For storing critical data, a SQL Server should be used. For more information, see the Connect to a SQL Server Database topic.

  4. Once the database has been created, it will be displayed beneath the Databases node in the Project Explorer.

Note: When using a SQLite database, for the best use-case, use Designer to build the SQLite database, and use the other database program to simply view or add indexes to the tables already created in Designer. Another tool, such as a SQLite database browser, can be used to create indexes within the tables. If using another program, ensure that the database file is only open in one program, e.g. the database is not being viewed by a SQLite browser while being edited in Designer. The database may become locked in such a scenario.

Creating SQLite Tables


Creating SQLite Tables

  1. To create a new table, right-click on a database and select New Table, which will open the Table Definition Editor.

  2. Enter a name for the table, and enter a row for each column in the table.

  3. Once you have specified the Name and Data Type (using the Data Type Selector) for each column, click Accept to create the table. The table will be displayed beneath the Databases node in the Project Explorer.

Note: The SQLite database has a maximum size of 1TB.


Connect to an SQL Server Database

Connect to a SQL Server Database

Cognex Designer supports the option of connecting to a Microsoft® SQL Server® database (SQL Server 2008 R2 and later), which can be running locally or on another PC on the network. However, Designer does not support modifying (e.g. add/remove/edit tables) the database structure within the Designer development environment. Therefore, Cognex recommends that the database table be created and edited in Microsoft® SQL Server® 2012 Management Studio or later.

To create a connection to a SQL Server database, right-click on the Databases node in the Project Explorer and select New Database Connection.

Note:

  • Designer only supports a sub-set of data types: bigint, binarybit, char, date, datetime, datetime2*, datetimeoffset, float, int, nchar, ntext, nvarchar, real, smalldatetime, smallint, text, tinyint, uniqueidentifier, varbinary, varchar.

    These data types are contained in a whitelist of supported fields (if a data type is not in the whitelist, it is not supported). When utilizing a SQL Server database, Cognex recommends that the account(s) connecting to the database be granted explicit permissions to just the tables needed for the application, and those tables only contain the data types contained in the whitelist.

    *datetime2 values may lose precision when being read and written to by Designer.

  • Designer does not support the decimal, geography, hirachyid, image, money, numeric, smallmoney , sql_variant, time, timestamp and xml any other data type that is not contained in the whitelist. When creating a database, ensure that these types are not used for columns, otherwise Designer will be unable to connect to the database.

Standard SQL Database Connection

SQL Database Connection String


Standard SQL Database Connection

The Standard mode connection requires that the fields be configured by the user.

Control | Description
Server Name | The name of the server and the instance name (ServerName\Instance).
Database Name | The name of the database to connect to.
SQL Login | If checked, use the specified User name/password as used to access the SQL Server database; otherwise, use the Microsoft Windows integrated log in.
Command Timeout | Sets the default timeout period for application queries.


SQL Database Connection String

Use the Connection String mode to specify more advanced configuration options for the database. Once connected, Cognex Designer will automatically discover the database tables available on the database.

Note: More information on Connection Strings can be found by visiting the Microsoft Developer Network Website (requires Internet connectivity).


Writing to a Database

This section describes how to insert new data rows into a database table. Data can be written from either a script or a Task.

Note: The examples in this section assume a database with four columns, with data types of date-time, double, string and Boolean, respectively, has been created.

Writing to a Database from a Script

Writing to a Database from a Task


Writing to a Database from a Script

Once a database table has been defined, Cognex Designer will automatically add a new function that can be called from a script called AddRow. This function will show up in the function list under: [DatabaseName].[TableName].AddRow

Calling this function with a value for each column will insert a new row of data into the table. For example:

$Databases.MyData.MyTable.AddRow(DateTime.Now(),12345.67, False,"Message");


Querying a Database

These topics describe how to create a query on a table, based on parameters, as well as additional advanced query options.

  1. To add a query to a table, from the Project Explorer, right-click the table and select New Query from the menu.

  2. This will launch the Query Builder dialog.

Note: Query Text syntax is dependent on the database type. i.e. selecting the first 100 rows in MS SQL is SELECT TOP(100) * FROM MyTable while in SQLite it is SELECT * FROM MyTable LIMIT 100

Queries with Parameters

Advanced Query Options


Queries with Parameters

Queries can have parameters that allow users to specify ranges and conditions for the query results.

  1. To create a parameter, press the Add button.

  2. When configuring the parameter, use the "@" symbol as a prefix for the parameter's name.

  3. Once the query is created, Cognex Designer will add tags for the query parameters and a function that can be used to update the query:

    $MyData.MyTable.MyQuery.Parameters.Result;
    $MyData.MyTable.MyQuery.Run();


Advanced Query Options

Additional query options can be configured by clicking the Advanced button in the Query Builder.

Control | Description
Publish Query Results as Tags | Specifies that a tag will be created for every Column:Row.
Number of Rows to Publish | Specifies the number of rows to be published. Note: The maximum number of rows is 50; if a value greater than 50 is specified, the Accept button will be disabled.
Reverse Row Index | Specifies that the last item will become the first item.
Update Query on Parameter Changed | Specifies that each time a parameter is changed, to wait for the specified delay period and then re-run the query.
Delay before triggering | Specifies the time between parameter value changes before re-running the query. This is useful to help minimize UI related coding.
Tip: When using the Update Query on Parameter Changed delay setting, set it to 50ms. This will allow setting the values through code, without causing the query to re-run.


Showing Query Results

Query results can be displayed either on a Page using a Table User Controls, or by accessing the individual results of a query using tags.

The following example illustrates how publish the results of a query, using a script:

// The Database is a SQLite database, named "new_database".
// The Table is named "MyTable" with the following fields, in this order: Value(Double), Active(Boolean)
// The Query is named "MyQ"; select * from MyTable.
// There are two examples below; one which uses indexes, and another which uses column names.
// No additional references are needed for other dlls.
// Two integer data type tags need to be created: $TotalUsingIndex &  $TotalUsingName

$Databases.new_database.MyTable.MyQ.Run();

DataRow[] rows = $Databases.new_database.MyTable.MyQ.QueryResults;

double total = 0;

// using index
foreach (var row in rows) {
  double value = Convert.ToDouble(row[0]);
  bool isActive = Convert.ToBoolean(row[1]);

  if (isActive)
      total+=value;
}
// add label to HMI bound to tag below
$TotalUsingIndex = total;

total=0;

// using column name (slower than index)

 foreach (var row in rows) {
 double value = Convert.ToDouble(row["Value"]);
 bool isActive = Convert.ToBoolean(row["Active"]);

   if (isActive)
      total+=value;
 }

// add label to HMI bound to tag below
$TotalUsingName = total;
return $Databases.new_database.MyTable.MyQ.RowCount;//

Displaying Query Results in a Table

Displaying Individual Query Results


Displaying Query Results in a Table

Query results can be directly connected on a Page to a Table User Controls, for display purposes.

  1. Set the Source property of the Table to the query that you would like to display.

  2. The Table will automatically generate the appropriate table columns, and, once connected, the Table control will automatically update the display of the rows whenever the query or source table are updated.
Note:

In addition, a Button control can be added and configured using the GetSelectedRow function to retrieve items from the table.

For example, if a Button (in conjunction with the Table) was added to the Page above, the following script in the On Mouse Click script point could be used to retrieve data from the table (the example assumes that the Data Type in the first column is a String, and the second column contains an Integer Data Type; otherwise, the cast operation will throw an exception):

Cognex.Designer.Database.DataRow myRow = $Pages.Page.MyTable.GetSelectedRow();
$Name = (string)myRow.ItemArray[0];
$Count = (int)myRow.ItemArray[1];


Displaying Individual Query Results

  1. In the Query Builder, press the Advanced button to launch the Advanced Properties dialog.

  2. Check the Publish Query Results as Tags checkbox.

  3. Cognex Designer will create a set of tags for each column:

    $Databases.MyData.MyTable.Row0.Time[1] -> $Databases.MyData.MyTable.Row10.Time[10]
    $Databases.MyData.MyTable.Row0.Result[1] -> $Databases.MyData.MyTable.Row10.Result[10]
  4. These tags will be updated whenever the query is updated, and can be bound to Properties of Page elements, the same as a standard tag.


Templates

Templates are used to import and export user-created components to better allow team collaboration between users. Templates allow users to store existing elements, or groups of elements, in the dedicated user library for later use in other projects.

  • Items within the application can be exported to a project independent template.
  • Items within the template library can be imported into a new project.

There is a dedicated template directory within the user directory where users can export and store their own templates. Templates in this directory are automatically loaded at start up. By default, this directory is located at: <MyDocuments>\Cognex Designer\Templates\<templatename>.cdtx

Note:
  • Multiple user directories can be created, in addition to the default (Tools\Options\Templates). For more information, see the Template Browser topic.
  • The template file extension, .cdtx, was updated in Cognex Designer 2.1 (formerly .cdt). Only files with the .cdtx extension will be visible in the Template Browser. For more information, please refer to the Migrating to this Release topic.

Supported Template Elements

Unsupported Template Elements

Exporting Items

Importing an item


Supported Template Elements

High-level Elements

  • Task
  • Page
  • User Script
  • Components
  • Tags

Low-level Elements

Note: These elements require user placement.
  • UI Element(s)
  • Block(s) and their links
  • Task(s)
  • Application Scripts*
  • Data Change Scripts*

  • Key Press Scripts*

    Note: These scripts can be dropped into a User Script.


Unsupported Template Elements

The following elements are not supported as template elements:

  • Alarms (Single/Multiple)
  • Recipes
  • Resources (Single/Multiple)
  • Database
    • Queries and their settings (E. g. Published results)

  • Users (the authentication mode, properties, etc)

  • Devices

    Note: Alarms and Tags can also be exported into Comma Separated Value (CSV) format in the Tag\Alarm Managers pages but this process is not the same as exporting to a template.


Exporting Items

You can export an item from your project by doing the following:

  1. Select the element on your Page or in your Task.

    Note: If it is a Page, Task, Script or Task, select it in the Project Explorer.
  2. Right-click the element and select Export.

  3. Fill in the details about the exported element. If you want to fine-tune where to export your element exactly, right-click on either the root folder or one of the sub-folders and create a New Folder. Right-click on the newly created folder and select Rename to create a custom name.

  4. Click Export. Your new exported element appears in the Template Browser.

    Note: You can select and export multiple items as a set, if you select only blocks in a single Task, controls on a single page, or tags in the Tag Browser. You cannot combine these three element types to make a set.

Note:

Templates only hold references of dependent objects. You must either additionally export those dependent objects to be added at import time, or recreate them at import time. For example, exporting Script X that calls Script Y will not export Script Yinto the template. An HMI control that is bound to a tag (e.g. $Bee), will not export the $Bee tag itself, only a reference to it.

Consider the following scenario:

  1. Create two string tags: $tg_Hello and $tg_World with respective values "hello" and "world".

  2. Create a Script block that returns a string with one line: return $tg_Hello + " " + $tg_World;

  3. Export the block.

  4. Select the two tags in Tag Manager and export as pair.

  5. Close/ save the project and open a new project.

  6. Drop in the script control template and open it in the Script Editor.

  7. Try to compile the script; it results in an error.

  8. Import the pair of tags.

  9. Try to compile again and now it results in success.

  10. Run the task and observe that the output to the pin is "Hello world".

Exporting Individual Elements

Export a Script, Task or WebPage


Exporting Individual Elements

To export an individual element:

Note: When exporting an element, if the element references another element, such as another script or tag, ensure that those are exported, as well.

  1. Select the individual element:

    • individual Tags in the Tag Manager
    • individual WebPage Elements on your WebPage
    • individual Task Blocks in your Task
    Note:
    • You can select and export multiple items as a set. Select only blocks in a single Task, elements on a single WebPage, or tags in the Tag Browser. However, you cannot combine these three element types to make a set.

  2. Right-click the element and select Export.

  3. Fill in the details about the exported element.

    If you want to fine-tune where to export your element exactly, right-click on either the root folder or one of the sub-folders and create a New Folder.

    Right-click on the newly created folder and select Rename to create a custom name.

  4. Press the Export button, and your new exported element will appear in the Template Browser.


Export a Script, Task or WebPage

To export Scripts, a Task or a WebPage:

  1. Select the script, Task or WebPage in the Project Explorer.

  2. Right-click the script, Task or WebPage, and from the menu, select Export.

  3. Fill in the details about the exported component in the Export dialog.

  4. Press the Export button, and your new exported component will appear in the Template Browser.


Importing an item

Importing Items

There are two ways to import an item from the template directory:

  • Double-click or Right-click – For top-level templates, see supported elements in the Templates section, since they have only one target where they can go.

  • Drag and Drop – From the Template Browser, can be used with all elements.

Different items can be imported differently:

  • Low-level elements require a user to select where they should be imported to - drag-and-drop them in their respective place. This is why there is no Import option in the right-click menu for them.

    Note: When importing objects with bindings / references to tags, the tags are not automatically created. Some tag names may already exist in the other project but they are being used for other purposes.

    To handle these issues, follow one or more of the following strategies:

    • Import the referenced tags (assuming those tags are already exported).
    • Create the necessary tag(s).
    • Use the Edit | Replace Tag () tool to globally replace any missing tags used by the object(s) that have been imported with existing tag(s) that the project already uses.
    • Manually rename tags for certain new or existing objects to resolve conflicting uses.

  • High-level elements have one possible import location, therefore this can be done automatically - you can import them by double-clicking or by right-clicking and selecting Import. For high-level items, see the Templates topic.

    Note: While importing templates, it is possible that existing components in the application conflict with the items being added. To handle this, you can simply rename the imported elements. Remember to run the Project | Verify tool after importing to ensure all required referenced scripts and tags exist.


Project Maintenance

The topics in this section provide useful information on maintaining your Cognex Designer project.

Designer Folder Structure

Saving, Loading and Switching Projects

Backing up and Recovery

Designer Assemblies and Antivirus Software

Cognex Designer Version Compatibility

Cognex Designer and VisionPro

Cognex Designer Security


Designer Folder Structure

This topic describes in detail the folders that are of importance from the point of view of working with Designer:

 | Folder/Location (default) | Description
1. | C:\Program Files\Cognex\Designer\<version> | Contains the application executable and related files. Only user-configurable file is NLog.config
1.1 | C:\Program Files\Cognex\Designer\<version>\Docs | Contains documentation and licenses.
1.2 | C:\Program Files\Cognex\Designer\<version>\Sources | Contains open sources.
2 | C:\Users\<user_name>\Documents\Cognex Designer | This folder contains user-created content.
2.1 | C:\Users\<user_name>\Documents\Cognex Designer\Projects | Contains the projects, created by the user.
2.1.1 | C:\Users\<user_name>\Documents\Cognex Designer\Projects\<Project_Name> | Contains the specific files belonging to a specific project.
2.1.1.1 | C:\Users\<user_name>\Documents\Cognex Designer\Projects\<Project_Name>\Data | Contains the database files like runtime.db3 and other SQLite databases, user data, audit and/or user management.
2.1.2 | C:\Users\<user_name>\Documents\Cognex Designer\Projects\<Project_Name>\Images | Contains the image files for a specific project.
2.1.3 | C:\Users\<user_name>\Documents\Cognex Designer\Projects\<Project_Name>\Recipes | Contains the recipes for a specific project.
2.1.4 | C:\Users\<user_name>\Documents\Cognex Designer\Projects\<Project_Name>\Recipes\<recipe_name> | Contains the recipe files for a specific recipe.
2.2 | C:\Program Files\Cognex\Designer\<version>\Samples | This folder contains sample applications for Designer.
3. | C:\ProgramData\Cognex\Designer\Plugins | Contains the plugins added/created by the user. For more information on internal folder structure and best practices, see Working with Plugins.
4. | C:\Runtime\ | Default folder for runtime applications.
5. | C:\Logs | Default folder for Designer logs.
6. | C:\Users\<user_name>\AppData\Local\Cognex\ProjectData | Contains the configuration files for all projects separately.
7. | C:\Users\<user_name>\AppData\Roaming\Cognex Corporation\Cognex Designer\<version>\Preferences | Preferences for layouts of tabs, etc.
8. | <MyDocuments>\Cognex Designer\Templates | Default folder for the exported templates.


Saving, Loading and Switching Projects

Save the project by clicking File > Save. Simply enter a name for the project and click Accept. The default location for projects is: Documents\Cognex Designer\Projects\{Project Name}.

Note: "Save as" is used to save the project to a new location. Changes made to the project since the last save will only be made to the new location. After the project is saved, Cognex Designer will restart and open the new project. If the speciﬁed project folder already exists, your project will remove existing files and subdirectories from it.


Backing up and Recovery

Cognex Designer will automatically backup the previous version of your project every time you save it, with the file name of: <ProjectName>_yyyyMMdd_hhmm_0.cdp. The timestamp in the backup file indicates when the original project .cdp file was saved.

Note:
  • The timestamp uses the following format: yyyyMMdd_hhmm_0; the _0 denotes seconds/milliseconds, and will be incremented if the file is saved more than once, in under a minute. For example, if the original project file is saved at 1:25 PM, on May 13, 2015, the backup file would be named <ProjectName>_20150513_1325_0.
  • See the Restoring a Project From a Backup topic for more information about creating a new project file from a backup.
  • The Date modified column in Windows Explorer will indicate the last time that the project file itself was saved.

To make backing up easier, try to keep all database files, sample images, etc. in the Project Folder. This will allow you to move the project from computer to computer more easily.

  • ﻿Project Files: Located in the Projects folder, with a .vsp file extension (Libraries > Documents > Cognex Designer > Projects).
  • Sample Files: Located in the Samples folder (Libraries > Documents > Cognex Designer > Samples).
  • Persistent Tags: Located in the Data folder, and given the name runtime.db3 (RunTime > "ProjectName" > Data).
  • Database: Dependent upon where the Database is saved (best practice is to keep it located in Project Folder\Data).

If the .cdp file gets corrupted or deleted, Designer will attempt to find the latest backup in the Project Folder, and the following message will be displayed:

If you click Yes, and then save the resulting opened project, a new file is created: <project_name>.cdp. It is based on the backup, and will contain any modifications that were made since the backup was opened (the backup file itself will remain unchanged).

Note:

To be able to open the latest backup, you must have backup files saved in your project folder. To create a backup, in Designer, click File | Save. If you have no backup of your project, and your original project file is corrupted, missing or does not match the project folder name, Designer will not display the project in Launcher. The image below illustrates a project file and its backups:

Since there is no backup version of supporting files, any change related to items like databases, recipes, user tables, exported tag files, templates and/or images, they will need to be recreated.

Restoring a Project From a Backup


Restoring a Project From a Backup

To restore a project based on a backup, instead of the current .cdp project file, do the following:

  1. Identify the backup file that you want to use from the list of backup files in the Project folder, via its timestamp.

  2. Move the original .cdp file and all of the other backup files, except the one that you want to use, from the Project folder.

    Note: To prevent inadvertently losing necessary changes permanently, Cognex recommends copying and storing the .cdp project file and its backups in another directory before removing them from the Project folder.

  3. When you next start Designer, the program will prompt you that the .cdp project file cannot be found, and if you want to use the backup file, instead:

  4. Press Yes to continue, and the backup file will now become the .cdp project file.
Note: Any changes that you made to a database or recipe after the backup was created will not be restored, and will need to be recreated in the new project.


Designer Assemblies and Antivirus Software

Due to assembly obfuscation, Cognex Designer executables and assemblies might be recognized by some antivirus software as a possible threat. If this happens, please add the marked files to the exception list of your antivirus application.


Cognex Designer Version Compatibility

Cognex Designer supports backward compatibility, which means that projects created with earlier versions of Designer should be able to be opened, edited, and saved in the latest Designer release. However, once projects are saved in the latest Designer release, Cognex does not guarantee that these project files may be reopened in an earlier version of the software. This is due to the introduction of new features and capabilities that are not present in the older releases.

Note:

In addition, the following also applies to Designer version compatibility:

  • A Designer project originally created in Cognex Designer 1.0 or 2.0 should be able to be opened, edited, and saved in Cognex Designer 2.1 and later. When loading the older Designer project into Designer 2.1 and later for the first time, Designer 2.1 and later may detect conversion issues, and will inform you of the conversion issues. In order for the project to work with the latest version of Designer, you will need to correct these issues.
  • Project files originally created in Designer 2.0 that were later opened and saved in Designer 2.1 cannot be opened again in Designer 2.0. To open and use a project from an earlier revision, you will have to go to the project folder and find a backup project file (via the project file's timestamp) before it was opened and saved in Designer 2.1. For more information about loading a project from a backup project file, please see the Restoring a Project From a Backup topic.


Cognex Designer and VisionPro

Cognex Designer provides a graphical user-interface for interacting with VisionPro functionality and objects, to build advanced machine vision application solutions. Prior to installing Cognex Designer, VisionPro must first be installed.

Note: For a complete list of compatible versions of Cognex Designer and VisionPro, please visit the Cognex Designer Support Website.

While building projects in Designer, it may be necessary to consult the VisionPro® Online Documentation for additional information. Topics in the Designer Help File that reference information in the VisionPro® Online Documentation will contain an extra section, entitled "Related Topics", which will provide the titles of relevant topics in the VisionPro Online Documentation Help file.

Simply copy the name of the topic and paste it into the Search field of the VisionPro Online Documentation Help file to quickly locate the relevant information.

Tip: The Designer Help menu contains links to the Vision Controller Installation Manual, Cognex Communications Card Installation Manual and the VisionPro® Online Documentation.


Cognex Designer Security

To successfully launch the Cognex Designer application in either development and/or deployment modes, the correct version of VisionPro software, device and security licenses must be installed.

  • At startup, Cognex Designer will check to see that the correct version of VisionPro and Designer security licenses are installed.

    If the appropriate version of VisionPro is not installed, a warning dialog will be displayed, indicating that the necessary version of VisionPro (and the appropriate drivers) needs to be installed. Designer will then close.

  • The security mechanism also requires having one of the following devices present on the PC with Designer and VisionPro installed:

    • A Cognex frame grabber installed on the PC
    • A Cognex Communication Card installed in the PC

    • A Cognex USB security key attached to the PC

      Note: The Cognex Vision Controller includes a built-in security device; no USB security key is needed.

  • If the appropriate Designer security license is missing, a warning dialog will be displayed indicating the missing license, and then Designer will close.

    The required security licenses are "Cognex Designer Development License" and "Cognex Designer Deployment License":

    • Cognex Designer Development License: This security license covers the use of Designer in development mode. Without this license present, you cannot launch the Designer application.

    • Cognex Designer Deployment License: This security license covers the use of Designer in deployment mode. Without this license present, you cannot deploy and run a Designer project.

      Development License Present | Deployment License Present | Designer Behavior
      When neither of the licenses are present, Designer will not run in either development or deployment modes.
      X | When only the Development license is present, Designer will run in both development and deployment modes, but Test Mode and Deployment Mode will timeout after running for 8 hours. You will be able to click the Test Mode button again to get another 8 hours of operation (Designer will stop in another 8 hours). In addition, you can create and launch a deployed project, but it will automatically display a message dialog and close after 8 hours.
      X | When only the Deployment license is present, a Designer project can be deployed, without timing out, but the Designer application will not run.
      X | X | When both licenses are present, Designer will run in both development and deployment modes without timing out.
Related Topics The following topic can be referenced in the VisionPro® Online Documentation: Understanding VisionPro Security


Test Mode

Cognex Designer allows you to very quickly test your project without having to compile or exit Designer.

Note: Before entering Test Mode, you need to have a basic Page constructed for your project.
  1. In order to test an application, you need to enter Test Mode, either by selecting the Start Test Mode from the Project menu, pressing the Start Test Mode [image] button in the main project toolbar, or pressing the F5 key on your keyboard.

  2. By default, the test application will be shown in a tab called Test Mode, using the default Page for your project.

  3. To exit Test Mode, either select Stop Test Mode from the Project menu, press the Stop Test Mode [image] button in the main project toolbar, or pressing the F5 key on your keyboard.
Note: Full screen testing can be toggled by pressing the F11 key.


Deploying a Cognex Designer Project

The final step of project development is to deploy the application. In other words, roll out the application to your users so it can be run without the Cognex Designer Integrated Development Environment.

Deploying a Project Using WebHMI

  • Running a web browser on the PC where the deployed applications is executed may result in varying Task execution time. If this is of significant concern, we recommend that the WPF HMI is used for web deployment, rather than WebHMI

  • In release 4.0.0, tasks will take a longer time to execute in Test Mode than in release 2.x. This is due to increased Garbage Collection time in the development environment. As a result, always benchmark using a deployed application.

Deployment Options

Project Files and Deployment

Controlling the Startup State of a Deployed Project


Deployment Options

Once the application development has been completed, the project can be deployed and structured so that the application can not be modified.

  1. Navigate to Project > Deploy to launch the Deployment dialog.
  2. Configure the deployment options as desired, and then click Accept to deploy the application.
  3. You can then launch the deployed application by going to the deployment folder and running the Launcher exe file, or by using the shortcut on the desktop.
Note: See Deploying a Cognex Designer Projectfor information regarding deployment behavior specific to WebHMI.
Tip: Prior to deployment, the user will need a way to exit the application. In one of the Pages, add a Button with the Click Command property set to System.Shutdown, which will tie the Button to the Shutdown() function. Alt-F4 will also cause the application to shutdown.
Control | Description
Project Name | The name of the run time application.
Project Version | Specifies version number of the Run {ProjectName}.exe file.
Deployment Folder | Specifies where the run time application will be stored.
Scale Option

Specifies three display options:

  • None: Uses the Pages resolution.
  • Stretch: Fills the entire screen.
  • Fit: Fills the screen, while preserving aspect ratio.
Note: When the Scale Option is set to Stretch or Fit, the Windows taskbar will be hidden. To be able to access the taskbar, enable the Windowed Mode option.
Windowed Mode

Specifies whether or not the deployed application can be minimized. When enabled (the option is disabled, by default), at startup, the deployed application window will have a border, with minimize and close buttons.

The application will always be on top of other windows, and the maximize/restore button is disabled, regardless of the Scale Option setting. In addition, the application window cannot be resized; it can only be minimized or closed.

Note:
  • When enabled, and the Scale Option is set to Fit or Stretch, the deployed application UI will be set to full screen, and the Windows taskbar will be hidden while the deployed application is selected.
  • For applications designed to have multiple Pages, each Page will show up in the same window.
  • Regardless of whether or not Windowed Mode is enabled, you can use the Microsoft Windows keyboard shortcuts (ALT + TAB) to switch between programs while the application is deployed. However, by enabling Windowed Mode, you can minimize the deployed application.
Overwrite Folders

If checked, any sub-folders in the project directory will be copied into the deployment path. Overwrites the existing RunTime database with the one currently used in the Cognex Designer Integrated Development Environment, as well.

If not checked, it will copy over any folders that currently do not exist in the deployment folder.

Note: Prior to release 4.0, in the deployment folder, the overwrite option would replace files but not delete files in the folder that weren't replaced. As of release 4.0, the deployment folder is cleared of all files that weren't replaced.


Project Files and Deployment

Cognex Designer is divided into two modes of operation: Development Mode and Deployment Mode. As a result, Cognex Designer divides application configuration data into two areas: static data and active data.

  • Static data is used in Development Mode. This is the configuration information, and includes the Page, Tasks, Device configurations, and anything else needed to recreate the application. This information is all stored in the project file (.cdp).
  • Active data is used in Deployment Mode. This information will change when the application is running, and includes the database records, recorded image files and product recipe data.

Project Files

Deployed Folder

Running Your Project on Multiple Machines with Different Configurations


Project Files

A Cognex Designer project file contains the configuration of a specific Cognex Designer application, and is required in order to make modifications to the application in Development Mode.

By default, project files are stored in the following directory: My Documents\Cognex Designer\Projects\{Project_Name}

Note:
  • Sub-folders within the project folder will be deployed with the project.
  • Cognex Designer automatically keeps a backup of project files so that previous versions can be restored, if necessary.
  • The project file does not contain any modifiable data while the system is running, i.e. Databases, Image Files, Recipes, etc. This data is included in the Deployed Folder.


Deployed Folder

When an application is deployed, a new folder is created at the path specified in the Deployment tab of the Project Settings dialog, and the runtime files are created.

The default deployment path is: C:\Runtime\{Project_Name}\.

Note:
  • The deployment folder contains the deployed application configuration that is created from the project file.
  • The deployed application can not be opened in the development environment; the project file is required to make modifications.
  • The deployed application opens in run-mode, with no development tools accessible.
  • No file or folder name beginning with a dot (.) will be copied to the deployed folder.
  • The deployment folder will usually contain multiple sub-folders for Databases, Image Files and Recipes, depending on the application.
  • If deploying the application on a separate PC, the entire deployment folder should be copied to the new PC. In addition, the VisionPro and Designer must be installed on the PC.


Running Your Project on Multiple Machines with Different Configurations

Running Your Application on Multiple Machines with Different Configurations

You can run the same project on multiple machines with different configurations.

By using a project configuration override file, you override an application’s existing configurations on start-up, enabling your application to run on multiple machines with different settings.

Override the following project components by adding entries to the project configuration override file:

  • TCP/IP Client (Remote Address, Port, BufferSize)

  • Serial Ports (COM Port, BaudRate, Parity, DataBits, StopBits, DTR Enabled)

  • I/O Card FFP Protocols (EtherNet/IP, PROFINET, SLMP, None)

  • SQL Databases (Connection String)
  • WebHMI Server Settings (Port, Enable, User Directory)

Deploying with the Project Configuration Override File

To deploy your project on more than one system, with different configurations, do the following:

  1. Create an XML or text file and rename it Project.config, eliminating the .xml or .txt suffix. Move Project.config to the root directory of the project that you want to deploy, as shown in the illustration below:

  2. Edit Project.config with configuration settings you want to overwrite or change. Add a comment by starting a line with a pound symbol (#). Review the sample file below and use it as a model when creating your Project.config file. Comments describing the various configuration overrides are inline.
    3.                        # Note that for the following override examples: MyTcpClient, myCom, and comCard are the names of the Devices in a project,
            # and therefore should be changed to the correct name of the applicable Device for another Designer project.

            #================ TCP/IP Client ================
            # Overrides the IP Address of the TCP Client “MyTcpClient” to 192.168.1.32
            Devices/MyTcpClient/RemoteAddress=192.168.1.32
            # Overrides the Port number of the TCP Client “MyTcpClient” to 8080
            Devices/MyTcpClient/Port=8080

            #================ Serial (Rs232) ================
            # Overrides the Baudrate of the Serial Device "myCom" to 115200
            Devices/myCom/BaudRate=115200

            #================ Cognex Communication I/O Card ================
            # Overrides the Factory Floor Protocol (FFP) of the I/O card "comCard" to EtherNet/IP
            Devices/comCard/FFP=EthernetIP

            #================ Web HMI Server ================
            # Overrides the Port property of the WebHmi Server Settings to 85
            System.WebServer/ServerSettings/Port=85
            # Overrides the UserRootDirectory property of the WebHmi Server Settings to “C:\SomeOtherDirectory”
                    System.WebServer/ServerSettings/UserRootDirectory=C:\SomeOtherDirectory

Overriding the FFP Parameter when Configuring a Communication I/O Card

When overriding the FFP (Factory Floor Protocol) parameter for a Cognex Communication I/O Card, the override parameter names differ from those names displayed in the Cognex Designer user interface (IDE).

In the Cognex Designer user interface, the I/O Card Parameter Configurations are displayed, as in the figure below.

The configurable FFP options in the drop-down list box are: None, EtherNet/IP, PROFINET, and SLMP.

To override the FFP parameter, use one of the following lines as appropriate.

        Devices/comCard/FFP=EthernetIP
        Devices/comCard/FFP=Profinet
        Devices/comCard/FFP=Slmp
        Devices/comCard/FFP=None

Overriding the WebHMI Server Port

When overriding the Web HMI Server Port, register the new Port number enabling the Web HMI functionality to operate.

Register the Web HMI Server Port number with one of the two methods:

  • Follow the instructions in the section WebHMI: A Functional Overview
  • Run the following shell command while logged in with Administrator privileges: netsh http add urlacl url=http://+:{port}/ user=EVERYONE.


Controlling the Startup State of a Deployed Application

Controlling the Startup State of a Deployed Project

As you develop your Designer application, you will typically switch between development mode, where you use the Cognex Designer Integrated Development Environment to write script code, configure Tasks, and design HMI pages, and Test Mode, where you interactively test your application.

It is important to remember that whatever changes you make to your application state while you are in Test Mode remain in effect when you return to development mode. Because of this, it can be easy to inadvertently save temporary changes to your project.

For example, suppose your application includes a Page CheckBox control. If you enter Test Mode and check the CheckBox, then return to development mode and save your application, the state of that checkbox will be saved as well. If you then deploy the application, it will always start with that checkbox checked.

  1. You can explicitly establish the startup state of your application's tags and Page elements by adding code to your application's OnStartup script to initialize those items, as shown below (you can also use Recipes for the same purpose):

    // Initialize tag values
$myRect = null;

// Initalize HMI control states
$Pages.Page.Checkbox.State = false;
$Pages.Page.ResidualError.Text="0.0";
$Pages.Page.xText.Text = $Pages.Page.yText.Text = "0";

  2. To set the startup state of VisionPro Tool Blocks in Tasks, you can use code in the OnStartup script to load the state of a tool block from a persisted .VPP file. To do this, start by using the Export ToolBlock button in the tool block editor to save the state of the tool block to a .VPP file.

  3. Next, to allow script code to set the state of the tool block through a tag, open the VisionPro Tag Manger and check the Expose ToolBlock checkbox.

  4. Once you have performed these steps, adding the following code to your application's OnStartup script will initialize the tool block based on the saved state:

    // Load toolblock state from saved .VPP file
$Tasks.CopyRegion.Task.myToolBlock.ToolBlock = CogSerializer.LoadObjectFromFile($System.Info.ProjectPath + "\\Data\\tbstate.vpp") as CogToolBlock;
Tip:
  • As shown in the preceding example, if you save the .VPP file into the Data folder in your project folder, you can use the $System.Info.ProjectPath function to specify the location of the file for loading. This path will be automatically resolved so that it is also valid when you deploy your application.
  • If you want all tags to revert to default, delete {DeployedFolder}\Data\runtime.db3


Industrial Communications

Cognex Designer provides full support for the industrial communications protocols supported by VisionPro: EtherNet/IP, PROFINET and SLMP.

Industrial Communications Overview


Industrial Communications Overview

The industrial communications protocols (also known as factory floor protocols) supported by VisionPro and Cognex Designer allow you to create an application that can communicate with a compatible Programmable Logic Controller (PLC) across an industrial network.

VisionPro and Designer support the following protocols:

  • PROFINET (Siemens PLCs): PROFINET PLC Configuration
  • EtherNet/IP (Rockwell PLCs): EtherNet/IP PLC Configuration
  • SLMP (Mitsubishi PLCs): SLMP PLC Setup

The Cognex implementation of the factory floor protocols is based on the Cognex Network Data Model (NDM), a protocol-independent abstraction that allows your application to work with any supported protocol without any modifications.

Setting up a PLC For Industrial Communications

Network Data Model


Setting up a PLC For Industrial Communications

You should keep the following important concepts in mind when configuring your vision system for PLC communications:

  • The industrial communications protocol software runs on two types of Cognex hardware:

    • The Vision Controller system, which includes an embedded Cognex Communication Card.
    • The Cognex Communications Card, installed in a PC that you supply.

  • The Cognex Communication Card includes a dedicated processor that:

    • Manages the factory floor communications system.
    • Implements the NDM.
    • Manages the low-latency precision discrete I/O subsystem.
Note:
  • For more information on the card, refer to the Cognex Communication Card Installation Manual. For more information on the Vision Controller, refer to the Vision Controller Installation Manual. Both of these manuals are available from the Cognex Designer Help menu.
  • Only one protocol, EtherNet/IP, PROFINET or SLMP may be active.

There are four steps to configuring communications between your Designer application and a compatible networked PLC:

  1. Install and connect the required Cognex hardware, either a Cognex Communication Card or a Vision Controller
  2. Configure the hardware network settings to be compatible with your network.
  3. Install Cognex-supplied configuration files on your PLC.
  4. Start the NDM on your Cognex hardware and verify that the Cognex NDM is visible from your PLC.

Hardware Configuration

Network Configuration

PLC Configuration

Troubleshooting


Hardware Configuration

Two types of Cognex hardware support the NDM:

  • The Cognex Communication Card-24, an expansion card that you can install in any compatible PC.
  • The Cognex Vision Controller, a standalone vision system.
Note: The Cognex Vision Controller has an embedded Cognex Communications Card. The implementation of Factory Floor Protocols is identical for the two devices (the version of the card installed in the Vision Controller includes additional discrete I/O lines to support the Vision Controller's dedicated power and I/O connector for DS1000 series cameras.

Whichever type of hardware that you are using, you must install it, connect it to power, and connect it to your factory network.


Network Configuration

You use the Cognex Comm Card Configurator to set the following network parameters:

  • TCP/IP addressing mode (DHCP or Static)
  • Network address and subnet (Static mode only)
  • Host name and (optionally) station name for PROFINET
  • Settings, Remote Station and Device Addressing for SLMP
Note: Only a single application program can communicate with the Communication Card at a time. Make sure that Designer is not running before you launch the Configurator.

There are two methods to launch the Cognex Comm Card Configurator:

  • From the Installer, select the Utilities tab and double-click on the Cognex Comm Card Configurator icon.
  • Select Cognex -> VisionPro -> Utilities -> Cognex Comm Card Configurator.

The Configurator displays the following window:

You can use the controls at the top of the window to specify the host name, select between DHCP and static addressing, and in the case of static addressing, specify the IP address and subnet mask. You should select the network settings that are appropriate for the network to which the card is connected.

Note: The Comm Card Configurator does not change your PC's network settings, only the settings used by the Cognex Communication Card.

The Active Card Settings portion of the window displays the current settings of the card. These settings may be different from the card's stored settings in some cases (such as when a PROFINET device alters the active card settings). Whenever you change a setting and press Apply, both the active and stored settings are updated.

The Network Status portion of the window displays the current link status (whether the device is physically connected to a network) and interface status (whether the activated IP settings permit the card to communicate on an IP network).


PLC Configuration

The configuration steps for your PLC are specific to the type of PLC that you are using. Refer to the following topics which describe how to configure each type of supported PLC:

  • PROFINET PLC Configuration
  • EtherNet/IP PLC Configuration
  • SLMP PLC Setup

EtherNet/IP PLC Setup

PROFINET PLC Setup

SLMP PLC Setup


EtherNet/IP PLC Setup

EtherNet/IP PLC Configuration

Cognex Designer supports EtherNet/IP, an application level protocol based on the Common Industrial Protocol (CIP).

EtherNet/IP provides an extensive range of messaging options and services for the transfer of data and I/O over Ethernet. All devices on an EtherNet/IP network present their data to the network as a series of data values called attributes. Attributes can be grouped with other related data values into sets, these are called Assemblies.

Enabling EtherNet/IP involves the following main steps:

  1. Make sure you have the Rockwell Software tool on your machine.
  2. Set up the Rockwell Software tool so that it recognizes your vision system.

  3. Install the Electronic Data Sheets (EDS) for the Cognex Communication Card and the Cognex Vision Controller.

    Go to: Programs->Rockwell Software-> RSLinx->Tools->EDS Hardware Install Tool.

    The EDS files are located at: C:\Program Files\Cognex\VisionPro\ffp\eds.

Note: The C:\Program Files\Cognex\VisionPro\ffp\eds directory also includes a rung file that describes the layout of the input and output assemblies.

EtherNet/IP System Information

EtherNet/IP Support


EtherNet/IP System Information

Identity information (refer to the EDS files in C:\Program Files\Cognex\VisionPro\ffp\eds):

 | EtherNet/IP -- Cognex Communication Card | EtherNet/IP -- Vision Controller
Vendor ID | 0x2A6 | 0x2A6
Product ID | 0x308 | 0x308
Product Code | 0x801 | 0x802
Family Name | "Cognex Communication Card" | "Cognex Vision Controller"
Product Name | "Communication Card CC24" | "Vision Controller VC5"
Product Description | "Communication Card CC24" | "Vision Controller VC5"


EtherNet/IP Support

  • Support for cyclic connections with 1 – 1000ms cycle times.

  • Support for cyclic connections with up to 500 bytes of data in both directions.


PROFINET PLC Setup

PROFINET PLC Configuration

To set up a PROFINET I/O connection between your Vision Controller or Communication Card and a Siemens controller, the vision system must first be added to the controller's hardware configuration, using the Siemen's HW Config tool:

  1. Open the SIMATIC manager and load the PLC's project.
  2. Select the SIMATIC 300 or SIMATIC 400 node, then double-click on the Hardware node in the object list.
  3. The HW Config tool will now appear. In order to add PROFINET IO nodes to the controller, a PROFINET IO system must be present in the hardware configuration diagram; if there isn't a PROFINET IO system in the diagram, complete the following steps:
    • Ensure that the PROFINET IO interface on the CPU has been assigned a subnet address; to verify this, double-click on the PROFINET IO module on the CPU. If the PROFINET IO module's Networked status indicates "No," then click the Properties button and add a new subnet.
    • Once the PROFINET IO interface on the CPU has been assigned a subnet, add a PROFINET IO system to the hardware configuration diagram by right-clicking the PROFINET IO module in the PLC configuration and selecting Insert PROFINET IO System.

  4. If this is the first Vision Controller or Communication card to be added to the PROFINET network, the Cognex-supplied GSD file will need to be installed. To install the GSD file, follow these steps:

    Note: VisionPro and Cognex Designer include two GSD files, one for the Cognex Vision Controller and one for the Cognex Communication Card.
    1. From the HW Config tool, select Options > Install GSD Files from the menu.
    2. Press the Browse button and select the folder C:\Program Files\Cognex\VisionPro\ffp\gsd.
    3. Press the Select All button, then click the Install button to install the hardware description both system types.
  5. To add a your system to a PROFINET network, browse to the appropriate node of the Hardware Catalog (PROFINET IO > Additional Field Devices > Controllers> Cognex Vision Controllers or PROFINET IO > Additional Field Devices > Network Components> Cognex Communications Devices ), and then drag an instance of the desired vision system into the PROFINET IO System in the hardware configuration.
  6. Set the device name and IP address to the exact name and IP address of the device that you configured.
  7. The Vision Controller or Communication Card should now be displayed as a device on the PROFINET IO system.
Note: Note: If an underscore was used in the device name, the underscore will have to be replaced by a hyphen when the vision system's name is input in PROFINET. For example, if the system was named "System_Top" using the Comm Card Configurator, it will need to be renamed to "System-Top" in PROFINET.

PROFINET System Information

PROFINET Support


PROFINET System Information

 | PROFINET -- Cognex Communication Card | PROFINET -- Vision Controller
Vendor ID | 0x0137 | 0x0137
Device ID | 0x0008 | 0x0008
Product Code | 0x10D | 0x802
Family Name | "Cognex Communications Devices" | "Cognex Vision Controllers"
Product Name | "Communication Card CC24" | "Vision Controller VC5"
Product Description | "Communication Card" | "Vision Controller"


PROFINET Support

  • Support for cyclic connections with 1 – 1024ms cycle times.
  • Support for cyclic connections with 1440 bytes of user data and inspection result.


SLMP PLC Setup

The SLMP Scanner connection supports the exchange of data between an Automation Controller and the vision system. This connection provides dedicated control and status channels that allow the Automation Controller to issue vision system commands through direct addressing of the control and status registers. In addition, the SLMP Scanner connection provides dedicated command channels for sending and receiving more advanced string commands that are not included in the control and status channels.

SLMP Scanner is a command/response-based protocol, which originates from the vision system, and the vision system must send read requests to the Mitsubishi Automation Controller at periodic intervals to determine if there are changes in the control bits. This process is called "polling," and defines the polling cycle.

In the Mitsubishi communication protocol, information from the vision system is combined into data blocks, which are then transferred between the vision system and the Automation Controller. Within this methodology, bit-type data is stored in bit registers in the Automation Controller and word-type data is stored in word registers in the Automation Controller. Due to this implementation, bit data is never combined with word data in a data block, which allows these data items to be addressed separately in the Automation Controller.

SLMP PLC Configuration

SLMP Settings via the Cognex Comm Card Configurator


SLMP PLC Configuration

To setup a connection between a Cognex Communication Card or Vision Controller to a Mitsubishi PLC, the PLC must be configured using Melsoft Series GX Works2.

Create a New GX Works2 Project

Discover the PLC on the Network

Configure the PLC IP Address

Prepare the PLC for the MC Protocol Connection


Create a New GX Works2 Project

  1. Open the Melsoft GX Works2 software program, version 1.507d, and create a new project.
  2. In the New Project dialog, setup the PLC by establishing the series, type, project type and language.
Note: When connecting to the PLC, have the PLC's IP address available, or connect the PLC and the configuration PC on the same network switch, or connect the PLC directly to the PC's network port. If using a laptop PC, the PLC will not be seen over a wireless connection. The PLC can be connected via USB or Serial, as well.


Discover the PLC on the Network

  1. In the Navigation pane, select Connection Destination.
  2. Double-click Connection1 to open the Transfer Setup Connection dialog.
  3. In the PC side I/F row, select the Ethernet Board as the connection method.
  4. Note: Select Serial USB if that is the preferred connection method.
  5. In the PLC side I/F row, select PLC Module.
  6. Note: Select Ethernet Module if that is the preferred connection method.
  7. In the Other Station Setting row, select No Specification.
  8. In the Target System row, select the first PLC icon in the Multiple CPU Setting group box.
  9. In the PLC side I/F row, double-click the PLC Module to open the PLC side I/F Setting of PLC Module dialog, then press Find CPU (Built-in Ethernet port) on Network.

  10. If the PLC is listed, double-click it; however, if the PLC is not listed, double check the connection mode settings, as well as the PLC's wiring and power supply.

    Note: This dialog is capable of displaying PLCs on a network outside of the PC's IP range.
  11. Once the IP address of the PLC is displayed in the IP address field, press OK to close the dialog.

  12. In the Transfer Setup Connection dialog, press the Connection Test button to ensure the connection was properly established. If the test passes, close the dialog.

    Note: The test will fail if the PLC's IP address is outside of the PC's IP range.


Configure the PLC IP Address

  1. With the connection established, from the Navigation pane, select Project and expand the Parameter node to display the PLC Parameter setting.
  2. Double-click PLC Parameter to open the Parameter Setting dialog, and click on the Built-in Ethernet Port Setting tab to set the PLC's IP address and Subnet Mask.
  3. Check the Enable online change (FTP, MC Protocol) checkbox.
  4. Press the End button.
  5. From the Online menu, select Write to PLC....
  6. In the dialog, check the Parameter checkboxes and press the Execute button.
  7. Once the download has completed, physically power-cycle the PLC.
  8. After the PLC has restarted, move the PC's IP address back to the PLC's IP address and test the connection.


Prepare the PLC for the MC Protocol Connection

  1. From the Navigation pane, select Project and expand the Parameter node to display the PLC Parameter setting.
  2. Double-click PLC Parameter to open the Parameter Setting dialog, and click on the Built-in Ethernet Port Setting tab.
  3. Press the Open Settings button to launch the Built-in Ethernet Port Open Setting dialog.
  4. Within line 3, set the Open System setting to MC Protocol, and the Host Station to 12288 (3000 in HEX).
  5. Press the End button in the Built-in Ethernet Port Open Setting dialog, and then press the End button in the Parameter Setting dialog.
  6. Once the download has completed, physically power-cycle the PLC.


SLMP Settings via the Cognex Comm Card Configurator

Before SLMP communications can be established, the vision system must be configured to enable SLMP, using the SLMP tab of the Cognex Comm Card Configurator. This is used to configure the connection to the MELSEC Automation Controller (either FX series PLCs over Ethernet, or Q and L series PLCs over Ethernet, and CC-Link IE field gateways), and define the device addresses and sizes for the various data blocks.

The Cognex Comm Card Configurator can be accessed from Cognex Designer Launch Page > Utilities tab.

SLMP PLC Settings Configuration

SLMP PLC Remote Station Configuration

SLMP PLC Device Addressing Configuration


SLMP PLC Settings Configuration

The Settings are used to configure the connection information required to establish a connection between the vision system and the Mitsubishi PLC.

Setting | Description
Controller Type | Specifies the type of Mitsubishi PLC to communicate with: Q/L Series (3E Frame) or FX Series (1E Frame). Default = QL Series_3E.
Target Address | Specifies the IP address of the PLC that will be connected to by the vision system.
Host Port

Specifies the TCP port number, in decimal (Dec: 1 - 65535; default = 12288) format, of the SLMP channel that will be used by the PLC.

Note:
  • This value should match the Host Port setting established on the SLMP Port of the Mitsubishi PLC.

  • The format of the Host Port number will be reset to decimal (Dec) when Cognex Designer is closed.
Timeout (ms) | Specifies the timeout (5 to 1000; default = 1000), in milliseconds, for a response from the PLC to an SLMP message.
Poll Interval (ms) | Specifies the amount of time (5 to 1000; default = 1000), in milliseconds, between successive polls of the Vision Control block on the PLC.


SLMP PLC Remote Station Configuration

The Remote Station is used to configure the connection information required to establish a connection between the vision system and the Mitsubishi PLC/MC.

Settings | Description
Station ID | Specifies the station ID (ID of C24 on a multi-drop serial connection); also used as the PCID field for 1E/3E frames.
Network ID | Specifies the SLMP network number (0 to 239; default = 0) that will be used to communicate (0 = the local network).
Destination Station | Specifies the Remote Station Destination Station ID, which is the ID of the second hop station (also the PCID for 1C frames).
Destination Module

Specifies the identifier of the device module that the vision system will be connected to.

LocalStation_0x3FF | 0x3FF
ControlSystemCPU_0x3D0 | 0x3D0
StandbySystemCPU_0x3D1 | 0x3D1
SystemACPU_0x3D2 | 0x3D2
SystemBCPU_0x3D3 | 0x3D3
CPU 1_0x3E0 | 0x3E0
CPU 2_0x3E1 | 0x3E1
CPU 3_0x3E2 | 0x3E2
CPU 4_0x3E3 | 0x3E3


SLMP PLC Device Addressing Configuration

The Device Addressing is used to configure the PLC/MC device addresses and sizes of the various data blocks that will be communicated from the vision system to the Mitsubishi PLC/MC. The Device Type and size of the data blocks vary, depending on the Controller Type (Q/L Series or FX Series) defined in the Settings.

Setting | Description
Ndm Signal Block | Specifies the name (read-only) of the data block that will be communicated to or from the PLC/MC.
Selected Device

Specifies the PLC/MC device that will be used to read or write the data block. The available PLC/MC devices are as follows:

Device Name | Prefix | Bit/Word Based | Address Representation | Q/L Series | FX Series
Input Relay | X | Bit | Hex (Q/L Series)/Octal (FX Series) | X | X
Output Relay | Y | Bit | Hex (Q/L Series)/Octal (FX Series) | X | X
Internal Relay | M | Bit | Decimal | X | X
Latch Relay | L | Bit | Decimal | X |
Annunciator | F | Bit | Decimal | X |
Link Relay | B | Bit | Hex | X |
State Relay | S | Bit | Decimal |  | X
Data Register | D | Word | Decimal | X | X
Link Register | W | Word | Hex | X |
File Register | R | Word | Decimal | X | X
File Register Multiple Blocks | ZR | Word | Hex | X |
Timer | TN | Word | Decimal | X | X
Counter | CN | Word | Decimal | X | X
Offset

Specifies an offset within the device table used to read or write the data block. The offset value should be entered in decimal, hexadecimal or octal, depending on the Selected Device.
Size in Bits | Specifies the size of the data block that will be communicated with the PLC/MC. The size is expressed in units of PLC/MC "devices", and is configurable only for those data blocks that do not have a fixed size, or where the size is automatically set by the referenced Format PLC Input Buffer or Format PLC Output Buffer.


Troubleshooting

Follow these steps to debug problems:

  1. Verify the interface and link status.
    1. Launch the Comm Card Configurator and verify that both the Interface Status and Link Status indicators say Up.
    2. From a PC that is on the same network as your vision system, open a command window and issue a ping command with the network address specified in the IP Address field.

    If the ping command does not receive a reply, verify the physical network connection and verify that the network settings are correct for your network.

  2. Verify the NDM is configured for the correct protocol. When you connect to the Comm Card in Designer, verify that you have selected the correct protocol.
Note: Signals from the PLC resulting in an error, such as a job load error or an acquisition error will still result in changing the discrete output value (if the signal is mapped to a discrete output).


Network Data Model

The Cognex Network Data Model (NDM) allows both the vision application (written by you in Cognex Designer) and the corresponding PLC application (running on the PLC) to interact with a familiar, platform-appropriate interface.

On the PLC, the NDM is represented as a signal table. The signal table defines a collection of status and control signals that the PLC and the vision application use to communicate. Signals are represented as named sections consisting of one or more bits of memory on the PLC. The overall signal table is represented as a pair of sub-tables that define the overall layout of the signal bits:

  • A status table, that contains the signals and memory that are set by the vision application and read by the PLC application.
  • A control table, that contains the signals and memory that are set by the PLC application and read by the vision application.
Note: The SLMP connection uses a modified version of the NDM signal table layout. For Mitsubishi customers, bit-typed data is stored in bit registers in the PLC, and word-type data is stored in word registers in the PLC. Due to this implementation, bit data is never grouped with word data in a data block, which allows these data items to be addressed separately in the PLC.

The PLC implementation also includes blocks of memory that can be used for sending configuration information to the vision application (such as the name of a job to load ) and for sending results data to the PLC (such as a decoded string or a collection of part measurements).

Within the vision application, the NDM is represented as a collection of notification functions and events. Your application invokes the notification functions to raise or lower the state of a signal in the signal table. Your application is notified of signal state changes by writing handlers for the NDM events.

Note: The NDM imposes a collection of constraints on the virtual signals. The state of a signal may be changeable or not changeable, from both the PC application and the PLC application, depending on the value of other signals and on the internal state of the NDM. The SLMP specific NDM signal table groups the NDM signals into four blocks, with each block containing only single bit signals, or signals that take up an entire word.

The following figure provides an overview of how the NDM works, and how it supports communication between your vision application and your PLC.

The sequence of events shown in the preceding figure is simplified; in practice, communication tasks are implemented with a series of signal changes.

NDM Capabilities

NDM Signal Tables

NDM Startup and Verification

Using the NDM to Interact with the Protocols


NDM Capabilities

The NDM lets you:

  • Invoke image acquisition and inspection under the control of the PLC application. This is typically done for slow-speed applications where the PLC is managing the line motion.

    The basic signal flow is:

    • Vision Application invokes NotifyAcquisitionReady on the selected camera.
    • PLC sets TriggerCamera for the selected engine.
    • Vision Application TriggerAcquisition() event handler is invoked.
    • Vision Application invokes NotifyInspectionComplete(), optionally supplying inspection result data.

  • Update a PLC with results and status information from a vision application running on your PC.

    The basic signal flow is:

    • Vision Application is triggered by an external trigger.
    • Vision Application invokes NotifyInspectionComplete(), optionally supplying inspection result data.
    • PLC processes results.
    Note: The PLC can set the Results Buffer Enable signal true to enable buffering of up to 16 results within the NDM.

  • Change the configuration of a running vision application on your PC from a PLC.

    The NDM provides two methods for modifying the configuration:

    • Job load signal which lets you specify an ID value to load a job or configuration file.
    • A soft event signal, which allows you to invoke one of 31 predefined functions within your vision application.


NDM Signal Tables

For the EtherNet/IP and PROFINET protocols, the virtual signal table implemented by the NDM is divided into a status table, which contains signals that are modified by the vision application, and a control table, which contains signals that are modified by the PLC. The vision application modifies signals in the status signal table by invoking NDM notification functions, and it is notified of changes to signals in the control signal table when NDM events are invoked. The PLC simply reads and writes the memory locations that correspond to the signal values in the two tables.

The status and control tables are further partitioned into a system region, an engine section, and a data section.

  • The system region contains signals that are related to the overall state of the NDM, such as online and offline state.
  • The engine region contains four identical blocks of memory that correspond to the four cameras and inspection jobs that can be run concurrently on the vision system.
  • The data section contains data written from the vision system to the PLC (inspection results) and from the PLC to the vision system (user data).

The following signal table maps describe the overall organization of both the status and control signal tables.

Note:

The specific memory layout on your PLC depends on the protocol and PLC type:

  • For EtherNet/IP PLCs, the signal table layout corresponds exactly to the memory layout on the PLC.
  • For PROFINET PLCs, the memory layout is described in the supplied GSD file.
  • For Mitsubishi PLCs, the signal table groups the NDM signals into four blocks. Each block contains only single bit signals, or signals that take up an entire word.

NDM Status Signal Table

NDM Control Signal Table

SLMP Defined Data Blocks


NDM Status Signal Table

The following table shows the layout of the NDM status signal table for EtherNet/IP and PROFINET (status signals are sent FROM the vision system to the PLC):

Note: For EtherNet/IP communications, this table refers to Assembly Object, Instance 11. The size may vary, depending on the Inspection Results.
 | Byte | Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0
System Status | 0 | Online | Offline Reason |  |  | Rsvd | Rsvd | System Busy | System Ready
 | 1 | General Fault | Rsvd | Job Load Complete | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd
 | 2 | Reserved
 | 3 | Reserved
 | 4-5 | Current Job ID
 | 6-7 | Error ID
 | 8-11 | Soft Event Ack 0-31
 | 12-15 | Reserved
Engine 0 | 16 | Results Buffer Overrun 0 | Inspection Passed 0 | Results Valid 0 | Inspection Completed 0 | Exposure Complete 0 | Acq Error 0 | Trigger Ack Camera 0 | Trigger Ready Camera 0
 | 17 | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Set UserData Ack 0
 | 18-19 | Acquisition ID 0
 | 20-21 | Inspected Image ID 0
 | 22-23 | Inspection Result Code 0
Engine 1 | 24 | Results Buffer Overrun 1 | Inspection Passed 1 | Results Valid 1 | Inspection Completed 1 | Exposure Complete 1 | Acq Error 1 | Trigger Ack Camera 1 | Trigger Ready Camera 1
 | 25 | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Set UserData Ack 1
 | 26-27 | Acquisition ID 1
 | 28-29 | Inspected Image ID 1
 | 30-31 | Inspection Result Code 1
Engine 2 | 32 | Results Buffer Overrun 2 | Inspection Passed 2 | Results Valid 2 | Inspection Completed 2 | Exposure Complete 2 | Acq Error 2 | Trigger Ack Camera 2 | Trigger Ready Camera 2
 | 33 | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Set UserData Ack 2
 | 34-35 | Acquisition ID 2
 | 36-37 | Inspected Image ID 2
 | 38-39 | Inspection Result Code 2
Engine 3 | 40 | Results Buffer Overrun 3 | Inspection Passed 3 | Results Valid 3 | Inspection Completed 3 | Exposure Complete 3 | Acq Error 3 | Trigger Ack Camera 3 | Trigger Ready Camera 3
 | 41 | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Rsvd | Set UserData Ack 3
 | 42-43 | Acquisition ID 3
 | 44-45 | Inspected Image ID 3
 | 46-47 | Inspection Result Code 3
Results | 48-xxx | Inspection Results

NDM Status Signals Descriptions


NDM Status Signals Descriptions

System Status

Byte 0

Bit | Name | Description
7 Online

This bit is set when the vision system is running, or "Online", and cleared when the vision system is stopped, or "Offline". When the vision system is Offline, examine the Offline Reason field to determine the reason.

The state of this bit is set in the NDM by the NotifyStopped and NotifyRunning functions (see the NDM Notification Functions topic for more information), and can also be controlled by the Notify PLC block, when the Notification Method Type is set to either NotifyStopped or NotifyRunning.

Note: This bit must be set manually or programmatically; it will not be set automatically.
6-4 Offline Reason

This field is a user-defined 3-bit field used to identify the cause of why a vision system has stopped running, or is "Offline". It is used in conjunction with the NotifyStopped function. The NDM supports 3 bits of stopped code information, which are reflected in the PLC's "Offline Reason" signal.

Note: For more information, see the VisionPro Online Documentation NotifyStopped Method topic.
3-2 | Reserved | Unused.
1 System Busy

Set when the vision system is responding to user input. The state of this bit is set by the NotifySystemStatus function (see the NDM Notification Functions topic for more information), or by a Notify PLC block, when the Notification Method Type is set to NotifySystemStatus.

Note: This bit must be set manually or programmatically; it will not be set automatically.
0 System Ready

Indicates that the vision system has completed its startup and is ready to start its activities. The state of this bit is set in the NDM by the NotifySystemStatus function (see the NDM Notification Functions topic for more information), or by a Notify PLC block, when the Notification Method Type is set to NotifySystemStatus.

Note: This bit must be set manually or programmatically; it will not be set automatically.

Byte 1

Bit | Name | Description
7 General Fault

This bit is set whenever an error has been reported within the Error ID field. This bit is cleared by setting the Clear Error bit from the PLC. If another error is queued, the Error ID and General Fault bits will be set once the Clear Error bit is set to low.

Errors can be caused by PLC logic errors (for example, setting the Trigger bit when Trigger Ready is already low), or by the user, through the Notify PLC block.

Note: Error codes are buffered, and if there is more than one error code buffered, the Clear Error bit must be toggled several times to clear the buffer and the General Fault bit.
6 | Reserved | Unused.
5 Job Load Complete

This bit is toggled upon the completion of a job load operation.
4-0 | Reserved | Unused.

Byte 2-3

Byte | Name | Description
2-3 | Reserved | Unused

Byte 4-5

Byte Name Description
4-5 Current Job ID

The list of currently loaded job IDs, sorted by job slot. An empty job slot has a job ID of -1. The current software only supports a single job slot. The current NDM layout requires valid Job IDs fit in the range of unsigned 16-bit integers (0, 65535).

The NDM NotifyJobState function (see the NDM Notification Functions topic for more information), or by a Notify PLC block, when the Notification Method Type is set to NotifyJobState, must be called to inform the PLC of the necessary information.

Byte 6-7

Byte | Name | Description
6-7 | Error ID | A 16-bit numeric representation of the error that has occurred. Note: The NDM supports 16-bits of error code information. However, currently, the NDM does not define its own error codes. You must supply your own meaningful error codes as arguments to NotifyError(Int32). Cognex recommends using the lower 12-bits (0x0001 to 0x0FFF) for your error codes.

Byte 8-11

Byte | Name | Description
8-11 | Soft Event Acknowledgment 0-31 | These bits are used to indicate that the Soft Event command was received.

Byte 12-15

Byte | Name | Description
12-15 | Reserved | Unused

Engine 0 - 3

Byte 16, 24, 32 and 40

Bit | Name | Description
7 | Results Buffer Overrun 0-3 | This field is set when the Buffer Results Enable bit is set and the vision system has discarded a set of inspection results because the PLC has not acknowledged the results, and in turn set the Inspection Results Acknowledgment bit. Up to sixteen inspections are held in the vision system's buffer; therefore, this bit is set when the seventeenth inspection is added to the buffer. The seventeenth inspection, and all subsequent inspections, will be dropped until there is room in the buffer (when the results have been acknowledged out). The bit is not cleared until a valid inspection occurs and a previous inspection is not overwritten.
6 Inspection Passed 0-3

This bit is set if the most recent inspection passed; this bit is cleared if the inspection did not pass. The Inspection Passed bit is part of the "inspection results" package of signals: Inspection Results Code, Inspection Passed, Inspected Image ID and Inspection Results. Once the "inspection results" package is written to the outgoing FFP interface of the Cognex Communications Card or Vision Controller, the Results Valid bit will be set to High. This ensures that when the Results Valid bit has been set to High, all of the data tied to that signal is valid and accessible to the PLC.

Note:

The behavior of the Inspection Passed bit will depend on whether or not results buffering is disabled or enabled.

Buffering is Disabled Buffering is Enabled

When a new inspection result is available, the last inspection result will be overwritten by the latest one.

When buffering is enabled, the Inspection Results Acknowledgment bit is used to acknowledge that the results have been read. In the case where the buffer contains one result set, and the Inspection Results Acknowledgment bit is set to High and then Low, the Results Valid bit will be set to Low. This indicates that there are no more result sets in the buffer, and a new result set will automatically overwrite the existing set.

In the case where there are several result sets in the buffer, and the Inspection Results Acknowledgment bit is set to High, the Results Valid bit is set to High, then Low and then High again so a new set of results will be displayed by the PLC interface. Setting the Results Valid bit High and then Low should be done until the buffer is emptied.

Note: In the case with multiple results in the buffer, all of the data in the result set is available before setting the Results Valid bit High once again, which ensures that no inconsistent data can be from the PLC interface.
5 Results Valid 0-3

Set when the Inspection Count, Inspection Result Code, Inspection Results and/or Inspection Passed bits are set. The bit is cleared when the Inspection Results Acknowledgment bit is set.

Note: If overlapped job processing is enabled to occur, either the Buffer Results Enable bit should be enabled/set, and the Inspection Results Acknowledgment bit should be set to latch the inspection results.
4 | Inspection Completed 0-3 | This bit is toggled upon the completion of an inspection. It is guaranteed to be toggled after the Inspection Count, Inspection Result Code, Inspection Results and/or Inspection Passed bits are sent to the PLC.
3 Exposure Complete 0-3

It is set upon the completion of the vision system's exposure period, and is reset by the Clear Exposure Complete bit. This bit will be held in a reset state if the Clear Exposure Complete signal is set to High.

This bit is set in the NDM by the NotifyAcqComplete or NotifyAcqMovePart functions (see the NDM Notification Functions topic for more information), or by a Notify PLC block, when the Notification Method Type is set to either NotifyAcqComplete or NotifyAcqMovePart.
2 Acquisition Error 0-3

This bit is set when a vision system fails to acquire an image; it is cleared when a successful acquisition is triggered.

This bit is set in the NDM by the NotifyAcqError function (see the NDM Notification Functions topic for more information), or by a Notify PLC block, when the Notification Method Type is set to NotifyAcqError.
1 Trigger Acknowledgment Camera 0-3

Indicates when a vision system has been triggered by the Trigger bit being set; this bit will stay set until the Trigger bit is cleared. In addition, the Acquisition ID can be latched to the rising edge of this bit.

This bit is set in the NDM by the NotifyAcqStarted function (see the NDM Notification Functions topic for more information), or by a Notify PLC block, when the Notification Method Type is set to NotifyAcqStarted.
0 Trigger Ready Camera 0-3

Indicates when a vision system can accept a new trigger via the Trigger bit. This field is true when the Trigger Enable bit is set by the PLC, the NDM NotifyAcqReady function or a Notify PLC block (with the Notification Method Type set to NotifyAcqReady) is called, and the vision system is not acquiring an image.

This field is set to false when the Trigger Enable bit is set to false by the PLC, or the NDM NotifyAcqDisabled function or a Notify PLC block (with the Notification Method Type set to NotifyAcqDisabled) is called, and the vision system is acquiring an image.

Byte 17, 25, 33, 41

Bit | Name | Description
7-1 | Reserved | Unused.
0 | Set UserData Acknowledgment 0-3 | This bit is set to acknowledge completion of the Set User Data command.

Byte 18-19, 26-27, 34-35, 42-43

Byte | Name | Description
18-19, 26-27, 34-35, 42-43 | Acquisition ID 0-3 | This ID is user-defined, and can be used to synchronize an acquisition with its Inspection Results. It can be implemented to increment at the beginning of an acquisition and when the Trigger Ack bit is set.

Byte 20-21, 28-29, 36-37, 44-45

Byte | Name | Description
20-21, 28-29, 36-37, 44-45 | Inspected Image ID 0-3 | The acquisition ID of the image associated with a set of results.

Byte 22-23, 30-31, 38-39, 46-47

Byte | Name | Description
22-23, 30-31, 38-39, 46-47 | Inspection Result Code 0-3 | The inspection result code (typically pass, fail or warning) associated with a set of results.

Results

Byte | Name | Description
48-xxx | Inspection Results | Inspection result data collection. This is user-defined; the results size is defined for each inspection. For example, you can define the Inspection 0 results section to be larger than that defined for Inspection 1.


NDM Control Signal Table

The following table shows the layout of the control signal table for EtherNet/IP and PROFINET (control signals are sent FROM the PLC to the vision system):

Note: For EtherNet/IP communications, this table refers to Assembly Object, Instance 21. The size may vary, depending on the User Data.
 | Byte | Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0
System Control | 0 | Set Offline | Clear Error | Reserved | Initiate Job Load | Reserved | Reserved | Buffer Results Enable | Trigger Enable
 | 1 | Reserved
 | 2-3 | Job Load ID
 | 4-7 | Soft Event 0-31
 | 8-9 | Reserved
 | 10-11 | Reserved
 | 12-13 | Reserved
 | 14-15 | Reserved
Engine 0 | 16 | Reserved | Reserved | Reserved | Reserved | Set User Data 0 | Clear Exposure Complete 0 | Inspection Results Acknowledge 0 | Trigger Camera 0
Engine 1 | 17 | Reserved | Reserved | Reserved | Reserved | Set User Data 1 | Clear Exposure Complete 1 | Inspection Results Acknowledge 1 | Trigger Camera 1
Engine 2 | 18 | Reserved | Reserved | Reserved | Reserved | Set User Data 2 | Clear Exposure Complete 2 | Inspection Results Acknowledge 2 | Trigger Camera 2
Engine 3 | 19 | Reserved | Reserved | Reserved | Reserved | Set User Data 3 | Clear Exposure Complete 3 | Inspection Results Acknowledge 3 | Trigger Camera 3
User Data | 20-xxx | User Data

NDM Control Signals Descriptions


NDM Control Signals Descriptions

System Control

Byte 0

Bit | Name | Description
7 | Set Offline | This bit is set by the PLC to temporarily place the vision system into a disabled state.
6 | Clear Error | This bit is used to acknowledge an Error Code, and can also be used to acknowledge any Acquisition Errors being signaled by the vision system.
5 | Reserved | Unused.
4 | Initiate Job Load | This bit is used to initiate a job load.
3-2 | Reserved | Unused.
1 | Buffer Results Enable | When this bit is set, the Inspection ID, Inspection Result and Inspection Results fields are held constant until the Inspection Results Ack field has acknowledged them and been set. Up to eight inspections are held in the vision system's buffer. The vision system will respond to the acknowledgment by clearing the Results Valid bit. Once the Inspection Results Ack field is cleared and there is a new set of rules sent to the PLC, the Results Valid bit will no longer be cleared. If the Inspection Results Ack bit is cleared and there are no more results in the vision system's buffer that are to be sent to the PLC, the Results Valid bit remains cleared.
0 | Trigger Enable | This field is set to enable triggering via the Trigger bit. Clear this bit to disable the network triggering mechanism. If the Trigger Enable and a Trigger bit are set simultaneously, then the trigger will fail and an Acquisition Error will be signaled. There will be one Trigger Enable signal to gate all cameras connected to the vision system.

Byte 1

Bit | Name | Description
7-0 | Reserved | Unused

Byte 2-3

Byte | Name | Description
2-3 | Job Load ID | This byte indicates the current job ID to be loaded, when the Initiate Job Load bit is set.

Byte 4-7

Byte | Name | Description
4-7 | Soft Event 0-31 | These bits are used to trigger a programmable action in the vision system.

Byte 8-15

Byte | Name | Description
8-15 | Reserved | Unused

Engine 0-3

Byte 16-19

Bit | Name | Description
7-4 | Reserved | Unused
3 Set User Data 0-3

This command is used by the PLC to indicate to the vision system that it should transfer the User Data field into a holding buffer for consumption by the vision system. These bits will fire the FFP NewUserData script point in Designer, and the event argument indicates which bit was set. See the NDM Event Handlers topic for more information about the NewUserData event.

Note: The Set User Data bits need to be configured to read the User Data field in Designer. If Set User Data is not set by the PLC, the User Data in Designer will either be unavailable, or, if a successful transmission had already occurred, the old values will be present.
2 | Clear Exposure Complete 0-3 | While this signal is High, the Exposure Complete status will remain reset. Once this signal is set to Low, the Exposure Complete status will be set to High on the next exposure completion.
1 | Inspection Results Acknowledgment 0-3 | When the Buffer Results Enable bit is set, the Inspection Results Ack bit acknowledges that the PLC has received the Inspection ID, Inspection Result and Inspection Results data. The next set of inspection results is then sent to the PLC. Clearing the Inspection Results Ack bit causes the vision system to set the Results Valid bit if the buffer is not empty. If results buffering is disabled, the Inspection Results Ack bit must be set to clear the Results Valid bit.
0 | Trigger Camera 0-3 | Setting this bit triggers an acquisition on a specific camera when the Trigger Enable bit is set. These four bits fire the FFP TriggerAcquisition script point and the FFP TriggerAcquisition 0-3 Task triggers. See the NDM Event Handlers topic for more information about the TriggerAcquisition event, and the Task Mode topic for more information configuring the Task trigger.

User Data

Byte | Name | Description
20-xxx | User Data | This data is sent to the application by the PLC, using the Read PLC block. This data is user-defined; the size of the user data section for each camera is set by the user. For example, the user can define that camera 0 has a user data size that is larger than the size of camera 1. Note: The User Data needs to be set prior to setting the Set User Data bits.


SLMP Defined Data Blocks

The defined data blocks allow you to control where the vision system is reading and writing data to and from the Automation Controller. For easier application setup, the various control and status bits required for command functionality are grouped into contiguous blocks, which can be processed together. When setting up the interaction between the vision system and the Automation Controller, you will need to choose the starting address and device type for each block of data.

SLMP Control Bit Signal Table

SLMP Status Bit Signal Table

SLMP Status Word Signal Table

SLMP Control Word Signal Table


SLMP Control Bit Signal Table

The SLMP Control Bit signal table/block organizes the single bit NDM signals sent FROM the PLC to the vision system. The Control Bit block is 80 bits long.

Byte | Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0
0 | Set Offline | Clear Error | Reserved | Initiate Job Load | Reserved | Reserved | Buffer Results Enable | Trigger Enable
1 | Reserved
2-5 | Soft Event 0-31
6 | Reserved | Reserved | Reserved | Reserved | Set User Data 0 | Clear Exposure Complete 0 | Inspection Results Acknowledge 0 | Trigger Camera 0
7 | Reserved | Reserved | Reserved | Reserved | Set User Data 1 | Clear Exposure Complete 1 | Inspection Results Acknowledge 1 | Trigger Camera 1
8 | Reserved | Reserved | Reserved | Reserved | Set User Data 2 | Clear Exposure Complete 2 | Inspection Results Acknowledge 2 | Trigger Camera 2
9 | Reserved | Reserved | Reserved | Reserved | Set User Data 3 | Clear Exposure Complete 3 | Inspection Results Acknowledge 3 | Trigger Camera 3


SLMP Status Bit Signal Table

The SLMP Status Bit signal table/block organizes the single bit NDM signals sent FROM the vision system to the PLC. The Status Bit block is 112 bits long.

Byte | Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0
0 | Online | Offline Reason |  |  | Reserved | Reserved | System Busy | System Ready
1 | General Fault | Reserved | Job Load Completed | Reserved | Reserved | Reserved | Reserved | Reserved
2-5 | Soft Event Acknowledge 0-31
6 | Results Buffer Overrun 0 | Inspection Passed 0 | Results Valid 0 | Inspection Completed 0 | Exposure Complete 0 | Acq Error 0 | Trigger Acknowledge Camera 0 | Trigger Ready Camera 0
7 | Reserved | Reserved | Reserved | Reserved | Reserved | Reserved | Reserved | Set User Data Ack 0
8 | Results Buffer Overrun 1 | Inspection Passed 1 | Results Valid 1 | Inspection Completed 1 | Exposure Complete 1 | Acq Error 1 | Trigger Acknowledge Camera 1 | Trigger Ready Camera 1
9 | Reserved | Reserved | Reserved | Reserved | Reserved | Reserved | Reserved | Set User Data Acknowledge 1
10 | Results Buffer Overrun 2 | Inspection Passed 2 | Results Valid 2 | Inspection Completed 2 | Exposure Complete 2 | Acq Error 2 | Trigger Acknowledge Camera 2 | Trigger Ready Camera 2
11 | Reserved | Reserved | Reserved | Reserved | Reserved | Reserved | Reserved | Set User Data Acknowledge 2
12 | Results Buffer Overrun 3 | Inspection Passed 3 | Results Valid 3 | Inspection Completed 3 | Exposure Complete 3 | Acq Error 3 | Trigger Acknowledge Camera 3 | Trigger Ready Camera 3
13 | Reserved | Reserved | Reserved | Reserved | Reserved | Reserved | Reserved | Set User Data Acknowledge 3


SLMP Status Word Signal Table

The SLMP Status Word signal table/block organizes the word length signals sent FROM the vision system to the PLC. The size of the Status Word block can vary, depending on the size of the inspection results section.

Byte | 16 Bit Word
0 | Current Job ID
1 | Error ID
2 | Acquisition ID 0
3 | Inspected Image ID 0
4 | Inspection Result Code 0
5 | Acquisition ID 1
6 | Inspected Image ID 1
7 | Inspection Result Code 1
8 | Acquisition ID 2
9 | Inspected Image ID 2
10 | Inspection Result Code 2
11 | Acquisition ID 3
12 | Inspected Image ID 3
13 | Inspection Result Code 3
14-1920 | Inspection Results


SLMP Control Word Signal Table

The SLMP Control Word signal table/block organizes the word length signals sent FROM the PLC to the vision system. The size of the Control Word block can vary, depending on the size of the User Data section.

Byte | 16 Bit Word
0 | Job Load ID
1-1920 | User Data


NDM Startup and Verification

To start the NDM, follow these steps:

  1. Launch Cognex Designer.
  2. Create a new project.
  3. In the Devices section of the project explorer, verify that the Cognex Communication Cards device is present in the Communications drop-down.
  4. Right click on the Cognex Communication Card device and select Connect (or double-click the device). Specify the protocol type (EtherNet/IP, PROFINET or SLMP) that you are using, and set the Index to 0 (the default setting). If the Index is set to anything other than 0, a disconnected card will be created.

At this point the NDM should be running and visible to your PLC:

Note: If neither Cognex Designer nor the Comm Card Configurator is running, then the card will be unreachable. If the Comm Card Configurator (it will not start the NDM and will not allow the PLC to connect to the card) is running, then the card will be reachable, but it will not be a valid station. Only when Cognex Designer is running and the current project is connected to the card will the card appear as a valid station.


Using the NDM to Interact with the Protocols

There are three aspects to using factory floor protocols through the NDM:

  • Calling NDM Notification functions
  • Implementing NDM event handling functions.
  • Reading and writing signal values on the PLC.

Each of these topics is discussed in this section.

NDM Notification Functions

NDM Event Handlers


NDM Notification Functions

You call the NDM notification functions to raise or lower a signal state in the NDM (and by extension, on the PLC). In some cases, you also supply some additional data which is stored in the NDM (and by extension, available to your PLC application).

Note: Within a Task, the Notify PLC can also be used to generate notifications.

The following table summarizes the available NDM notification functions. For information on function arguments and return values, refer to the VisionPro programming reference documentation, starting with the Cognex.VisionPro.Comm.CogNdm class. Many of the functions listed below take a cameraIndex argument. This argument indicates which of the four acquisition and inspection engines, each of which corresponds to a physical camera, the notification refers to. Some functions also take an acquisitionID argument. This argument serves as a unique identifier so that multiple overlapping image acquisitions from multiple cameras can be managed.

NotifyAcquisitionComplete

Notify the PLC that an acquisition has completed.

This function is used to inform the PLC that an acquisition has been completed. Calling this function will automatically re-enable the trigger ready bit on the PLC. You call this function to inform the PLC that an acquisition that it requested is complete and to inform it that a locally triggered acquisition is complete.

Before calling NotifyInspectionComplete(), it is required to call this function as well.

Note: Calling NotifyAcquisitionComplete sets the Exposure Complete bit on the PLC (if the bit has not already been set by calling the optional NotifyAcquisitionMovePart function).
NotifyAcquisitionDisabled | Optionally notify the PLC that the Vision System is unable to receive acquisition triggers.
NotifyAcquisitionError | Notify the remote device that an acquisition error has occurred.
NotifyAcquisitionMovePart

Optionally notify the remote device that the exposure is complete or the strobe has fired and it is now safe to move the part from the field of view.

You can use this notification function to tell the PLC that the acquisition (but not the inspection) is complete.
NotifyAcquisitionReady

Notify the PLC that the Vision System is ready to receive acquisition triggers. You must call this function to enable the PLC to send a trigger using the TriggerAcquisition event.

Note:

  • The NotifyAcquisitionReady method should be used in the following manner:

    1. In a typical configuration, the application has just been started, and it is ready to accept the first acquisition trigger signal.
    2. The PLC then sets the Trigger Enabled bit, which enables triggering by the PLC.
    3. Next, Designer will use the NotifyAcquisitionMethod (indexes are specified when there are more than one camera to trigger) to enable triggering by the PLC.
    4. Once both the PLC and Designer are set, triggering is enabled.
    5. Setting the Trigger Enabled to false, or calling the NotifyAcquisitionDisabled method, will result in trigger signals being ignored.
  • Calling NotifyAcquisitionComplete() automatically re-enables triggers for a particular camera, so calling NotifyAcquisitionReady() is only required to enable the very first acquisition. After the first acquisition you must call NotifyAcquisitionComplete() for the trigger ready signal to be sent back to the remote device or PLC.
NotifyAcquisitionStarted | Optionally notify the remote device that an acquisition has started.
NotifyAsyncSoftEventComplete | Notify the remote device that an asynchronous soft event has completed.
NotifyError | Notify the remote device (PLC) that the Vision System has encountered an error.
NotifyInspectionComplete(CogNdmInspectionResult result)

Notify the PLC that an inspection has finished.

This overload is not available through the Notify PLC; it can only be called from script. The CogNdmInspection result argument to this function provides information, including which engine and which images were used to generate the result.

Note: The InspectionIndex member of the CogNdmInspection object corresponds to the cameraIndex argument used in other functions. It is the engine number.
NotifyInspectionComplete(Int32 inspectionIndex, CogNdmUsedAcquisitionIDCollection usedAcquisitionIDs, Boolean inspectionPassed, Int32 resultCode, Byte[] resultData, Int32 resultDataOffset)

Notify the PLC that an inspection has finished.

This overload is available through the Notify PLC or it can be called from script. All of the supplied arguments are written to the signal table for use by your PLC application.

Note: The inspectionIndex argument corresponds to the cameraIndex argument used in other functions. It is the engine number and must be in the range 0-3.
NotifyJobState | Notify the remote device which job is loaded.
NotifyRunning | Notify the PLC that the Vision System is running or "online".
NotifyStopped | Notify the PLC that the Vision System stopped running or gone "offline".
NotifySystemStatus | Notifies the PLC of the Vision System status.

You can invoke NDM notification functions directly from script code using the standard VisionPro programming interface.

Here is an example of a notification function called from script:

//Acquire an image
$Devices.myCam.Acquire();
//Perform the inspection
$Tasks.Task.Run();
//Increment the inspection number
++$ResultCount;
//Construct results objects
CogNdmUsedAcquisitionIDCollection acqIDcoll = new CogNdmUsedAcquisitionIDCollection();
CogNdmUsedAcquisitionID usedID = new CogNdmUsedAcquisitionID($AcqID, 0);
acqIDcoll.Add(usedID);
//Call notification function on Engine 0 (set the result data to 0x2021)
$Devices.myCC24.NotifyInspectionComplete(0, acqIDcoll, true, 32,new byte[] {0x20, 0x21 }, 0);


NDM Event Handlers

When your PLC application changes the value of an NDM signal, the NDM will issue one of the events listed in the following table.

Note: Within a Task, the Read PLC block can be used to read the NewUserData from the Cognex Communication Card.
CardStatus | The NDM raises this event when the Comm Card reports very specific status or error events to the vision system. These events are typically used to inform the vision system of important "out of band" information that cannot be reported synchronously. Sign up for the CardStatus event, and use the StatusCode property of the event arguments to identify which status event code is being reported by the Comm Card.
ClearError

The NDM raises the ClearError event to inform the vision system that the remote device has been notified of an error reported by the vision system and the error has been be cleared.

Handle this event to know when the remote device has acknowledged an error and normal operation can continue.
JobChangeRequested

The NDM raises the JobChangeRequested event to inform the vision system that the remote device has requested a job change.

Handle this event and use the JobID property of the event arguments to determine which job to load.
NewUserData

The NDM raises the NewUserData event to tell the vision system that new user data has arrived from the remote device.

Handle this event and call ReadUserData(Int32, Int32) to read the new user data. Note that changes to the user data present on the remote device cannot be read until the remote device signals the vision system that new user data is available by sending a "Set User Data" signal.

The remote device can send separate "Set User Data" signals for each user data channel. Use the ChannelIndex property of the event arguments to determine which "Set User Data" signal was received. Upon returning from the event handler, the remote device is automatically notified by sending the “Set User Data Acknowledge” signal.
OfflineRequested

The NDM raises the OfflineRequested event to tell the vision system that it should go offline.

Handle this event and use the ReturnToPreviousState property of the event arguments to determine whether to transition the vision system offline or return it to its previous state.
ProtocolStatusChanged

The NDM raises the ProtocolStatusChanged event to inform the vision system that the status of the underlying protocol has changed.

Handle this event and use the RemoteAddress and ProtocolStatus properties of the event arguments to determine how the protocol status has changed.
TriggerAcquisition

The NDM raises the TriggerAcquisition event to inform the vision system that the remote device has requested an image Acquisition.

Handle this event and use the CameraIndex property of the event arguments to determine which camera should perform the image acquisition. Set the ResponseCode property of the event arguments to notify the remote device if an acquisition error has occurred.
TriggerAcquisitionDisabledError | The NDM raises the TriggerAcquisitionDisabledError event to tell the vision system that an acquisition trigger was set but the acquisition trigger was not enabled.
TriggerAcquisitionNotReadyError

The NDM raises the TriggerAcquisitionNotReadyError event when the remote device asserts a "Trigger Camera" signal high without waiting for the vision system to signal that it's ready to receive triggers by setting the "Trigger Ready" signal high.

Handle this event and use the CameraIndex to identify which camera channel was triggered before it was ready. Your user code should call NotifyAcquisitionComplete(Int32, Int32) to signal that the vision system that it has completed the current acquisition and is ready to receive another "Trigger Camera" signal from the remote device.
TriggerAcquisitionStop

The NDM raises the TriggerAcquisitionStop event to tell the vision system that the Acquisition trigger has been reset.

Handle this event and use the CameraIndex property of the event arguments to determine which camera trigger was reset.
TriggerSoftEvent

The NDM raises the TriggerSoftEvent event to inform the vision system that the remote device has requested that a soft event execute.

Handle this event and use the SoftEventID property of the event arguments to determine which soft event should execute. Set the ResponseCode property of the event arguments to notify the remote device of the status of the soft event when the event handler returns.
TriggerSoftEventOff

The NDM raises the TriggerSoftEventOff event to tell the vision system that the soft event trigger bit has been reset.

Handle this event and use the SoftEventID property of the event arguments to determine which soft event has been reset.

If you want your application to respond to one of these events, you must create a script point for the event by following these steps:

  1. Connect to the Cognex Communication Card device.

  2. Right click on the connected device and select the event to handle.

  3. Implement the event handling script.

There are some important restrictions to keep in mind while writing event notification functions:

  • You should avoid writing an event handler that takes a long time to execute.
  • Your event handler must not throw any unhandled exceptions.
  • Your event handler should not attempt to manipulate any HMI elements.

In most cases, your event handler will set the value of a tag, and your application will implement a data change script that runs when the tag value changes.

For example, the following script fragments show the event handler for the Trigger Acquisition event along with the associated data change script.

The event handler script simply sets the $doTrigger tag to true:

e.ResponseCode = CogNdmTriggerAcquisitionResponseCodeConstants.Success;
// Set tag to indicate trigger has occurred
$doTrigger=true;

The associated data change script implements the acquisition and inspection:

//Acquire an image
$Devices.myCam.Acquire();
//Perform the inspection
$Tasks.Task.Run();
//Increment the inspection number
++$ResultCount;
...
Related Topics See the VisionPro documentation for Cognex.VisionPro.Comm.CogNdm for more information.


Vision Controller

The Cognex Vision Controller can be configured and managed using Cognex Designer. These topics will cover the configuration, setup and management of the vision controller from within Designer. These topics assume that the vision controller has been setup and wired into its application environment, following the steps provided in the Vision Controller Installation Manual.

After starting, the vision controller will automatically open Designer in the Cognex Designer Integrated Development Environment. By default, the desktop of the vision controller contains shortcuts to the Cognex GigE Vision Configuration Tool, the Cognex Comm Card Configuration Tool and Designer. Close Designer and run both the Cognex GigE Vision Configuration Tool and Cognex Comm Card Configuration Tools to establish connections to the attached cameras and communication devices. Re-open Designer once the connections are established.

Most typical use-case scenarios with the vision controller will be placing the vision controller on the network, establishing a Remote Desktop Connection to the vision controller from a networked PC, developing the application in Designer, and then deploying the application to the vision controller.

While supporting network connectivity, in addition, the vision controller has three USB 2.0 ports (allowing HID devices such as a keyboard and mouse to connect) and a VGA monitor port. Also supported is the ability to use USB mass storage devices for file transfers. This allows the vision controller to be deployed in an environment that does not have access to a network, and updates and projects can be uploaded to the vision controller via a USB thumb drive.

Note:
  • For more information about the installation of the Vision Controller and cameras associated with the Vision Controller, please consult the Vision Controller Installation Manual (available from the Designer Help menu). The manual will need to be viewed on a PC with a PDF viewer installed.
  • For more information about establishing a Remote Desktop Connection, please see the Microsoft Windows Support topic Connect to another computer using Remote Desktop Connection.

Managing a Vision Controller

Switching Between Opto- and Differential Trigger Signals

Configuring DS1000 Series Sensors on a Vision Controller

Deploying On a Vision Controller


Managing a Vision Controller

This topic covers how to manage the vision controller from within Designer, and also provides additional information about users and naming conventions. The name of the vision controller will be CGNXVC-XXYYZZ, where XXYYZZ is the last six characters of the MAC address of the Vision Controller's I-ENET port.

Note:

  • If an attempt is made to log on to the vision controller with the wrong password more than six times, the log on access will be temporarily disabled. In this event, press the ESC key, choose the desired account from the possible selections (if no additional users have been added, the two default users, "user" and "admin" will be available), and then enter the correct password for the selected account.

  • If the vision controller fails to power up, please contact your Cognex sales representative immediately.

Operating System and Additional Programs

User Management


Operating System and Additional Programs

The vision controller operates on a modified version of the Microsoft Windows® 8 Operating System. Under this modified version, there is no direct access to the Windows Start screen. Instead, use the Windows Logo key on a keyboard to navigate to the Start screen.

The Control Panel is also hidden. To open the Control Panel, press the Windows Logo key to enter the Start screen, and type "Control Panel" and press Enter. The program should appear on the Start screen; double-click it to open the program.

In addition, Internet Explorer is also hidden. To open Internet Explorer, press the Windows Logo key to enter the Start screen, and type "iexplorer" and press Enter. The program should appear on the Start screen; double-click it to open the program.

By default, Windows Firewall is enabled. If needed, the Windows Firewall can be disabled. Navigate to the Control Panel > Windows Firewall dialog to disable.

By default, Remote Desktop connections to the vision controller are disabled. To enable remote desktop connections to the vision controller, navigate to Control Panel > System > Remote settings. Check the checkbox in the Remote Assistance section, and select Allow remote connections to this computer in the Remote Desktop section of the dialog. Press OK to commit the changes.


User Management

By default, the vision controller is preconfigured with a default "user" account (user name = user and password = user). This user does not have the ability to lock the vision controller.

In addition, an Admin user account is also available (user name = admin and password = Cognex).

The default passwords can be updated and modified (recommended) by navigating to Control Panel > User Accounts > Manage Accounts.

Tip: Additional users can be added and managed using the User Access functionality of Designer. For more comprehensive user management and security features, use Active Directory to manage users.


Switching Between Opto- and Differential Trigger Signals

To switch between opto and differential trigger signals for DS1000 connected to the DSUB connector on the Vision Controller, use the dropdown list in the Strobe & Trigger tab of the Image Source control in VisionPro 8.4.


Configuring DS1000 Series Sensors on a Vision Controller

Configuring DS1000 Series Sensor on a Vision Controller

If you are using a DS1000 series sensor with a Vision Controller, you have the option of using a Cognex-supplied cable (CKR-200-CBL-00x, 185-1010R). In order to support triggering of the DS1000 sensor using one of the Vision Controller discrete inputs, you must perform some special configuration as part of your Designer application's OnStartup script.

To do this, open the OnStartup script , and paste the following code into the script (you may wish to modify the trigger line number).

// This Script allows a DS1000 series sensor to be
// triggered by a Vision Controller connected through
// the Vision Controller's dedicated SENSOR port.
//
// The script does two things: It creates a precision I/O
// event that sends a trigger pulse to the DS1000 when
// an input pulse is seen on one of the Vision Controller
// input lines, and it alters the trigger line characteristics of
// the DS1000 camera to be compatible with the signals
// generated by the Vision Controller.
//
// This script code assumes that your application includes
// a connected DS1000 series sensor device named 'DS1100'
// and a connected Cognex Communication Card device named
// 'CommCard'.
//

if(! $Devices.DS1100.IsConnected)
    {
    $System.Log.Write("Connected DS1100 Device not found.");
    return null;
    }

if(! $Devices.CommCard.IsConnected)
    {
    $System.Log.Write("Connected CommCard Device not found.");
    return null;
    }

// get the VisionPro comm card in the system

CogCommCard card = $System.GetInternalObject("Devices.CommCard") as CogCommCard;

// access the discrete io object

CogDiscreteIOAccess dioAccess = card.DiscreteIOAccess;
CogPrio prio = dioAccess.GetActivePrecisionIO();

// verify that this device supports the DS1000 output lines

if(! prio.IsBankSupported(CogPrioBankConstants.DS1000OutputBank0))
    {
    $System.Log.Write("CommCard Device does not support DS1000.");
    return null;
    }

// Add a new event to the VisionPro Comm Card's collection.
// The event is caused by an input pulse on Bank0Line0.
// The event responds by immediately pulsing the
// VC5's dedicated DS1000 output trigger line for 10ms.

prio.Events.Clear();
prio.Events.Add
    (
    new CogPrioEvent()
        {
        Name = "TriggerDS1000",
        CausesLine = new CogPrioEventCauseLineCollection()
            {
            new CogPrioEventCauseLine()
                {
                LineBank = CogPrioBankConstants.InputBank0,
                LineNumber = 0,		// Select input line for triggering here
                LineTransition = CogPrioLineTransitionConstants.LowToHigh
                }
                //
                // Replace the above lines with the following lines
                // to use NDM triggering instead of local hardware
                // trigger
                //
                // new CogPrioEventCauseNdm()
                // 	{
                // 	Signal = CogPrioNdmSignalConstants.TriggerAcquisition,
                // 	SignalIndex = 0
                //	}
            },
        ResponsesLine = new CogPrioEventResponseLineCollection()
            {
            new CogPrioEventResponseLine()
                {
                OutputLineBank = CogPrioBankConstants.DS1000OutputBank0,
                OutputLineNumber = 2, // Select 2 for SENSOR1 output, 3 for SENSOR2 output
                OutputLineValue = CogPrioOutputLineValueConstants.SetHigh,
                PulseDuration = 10.0,
                DelayType = CogPrioDelayTypeConstants.None,
                DelayValue = 0.0
                }
            }
        }
    );

// Verify that the PRIO state is valid
//
if(! prio.Valid )
    {
    $System.Log.Write("Invalid precision I/O configuration.");
    return null;
    }

// get the internal VisionPro ICogAcqFifo interface
//
ICogAcqFifo acqFifo = $System.GetInternalObject("Devices.DS1100") as ICogAcqFifo;

// Here we set the DS1000 input line for high-speed mode. If the DS1000 is acquiring, or
// waiting for a  trigger signal, we can't program the device. We can disable triggers in order
// to program  the device, then re-enable them.

acqFifo.OwnedTriggerParams.TriggerEnabled  = false;
acqFifo.FrameGrabber.OwnedGigEAccess.SetFeature("TriggerSource","CPLine0HighSpeed");
acqFifo.OwnedTriggerParams.TriggerEnabled = true;
Note: Your application needs to ensure that the DS1000 configuration command and the precision I/O configuration commands refer to the correct camera and SENSOR port.


Deploying on a Vision Controller

Once the application has been developed and the project is completed and ready for deployment, to launch the application automatically at start up of the vision controller, the project should be placed in the vision controller's Startup folder. The Startup folder is located with the AppData folder, which is hidden by default, and the location of the folder varies by user.

Note: Due to the differing locations of the AppData folder, if it is desired that the project launch on log on for both the "user" and "admin" accounts, the project must be placed in the Startup folder for each account.

To navigate to the folder on a vision controller, open Windows Explorer, and type in %AppData%, or use the Command Prompt to navigate to %AppData% (which points to C:\Users\user\AppData\Roaming for the "user" account). For example, the default "user" account would be in: C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Simply remove the Designer launcher and replace it with the project for deployment.


How To...

This section covers various configuration scenarios and provides information on general and specific issues the user may encounter.

How to Add a Splash Screen

How To... Audit Trail

How To... Databases

How To... Developer's Guide

How to Use the FORMAT Option in the Expression Builder

How To... Industrial Communications

How To... Images

How To... Permissions

How To... Plugins

How To... Scripting

How To... VisionPro


How to Add a Splash Screen

Cognex Designer supports custom images within the Splash Screen, when launched in Runtime mode. After deploying the project, when launched in Runtime mode, your custom image will be shown within the Cognex Designer splash screen.

To add a splash screen, place an image named "SplashScreen.png" in the Data subfolder of your project. The image should be approximately 480 pixels by 270 pixels, or larger, to maintain a 16:9 aspect ratio (the image will be scaled to fit if it is larger than this size).


How To... Audit Trail

An audit trail (also called audit log) is a security-relevant chronological record, set of records, and/or destination and source of records, that provide documentary evidence of the sequence of activities that have affected at any time a specific operation, procedure, or event.

The following topics cover the basic information related to audit trails and how to deal with them in Designer.

How To Create an Audit Trail Database

Audit Trail Maintenance

Audit Trail Table Fields

How to View Data From an Audit Trail Database


How To Create an Audit Trail Database

To use Audit Trail, first you have to create a database for it:

  1. From the Project Explorer, right-click the Databases node and select New Database.

  2. In the New Database dialog, provide a name for your database and press the Accept button. Your database is created.

  3. From the Project Explorer, right-click the Settings node and select Edit. This will launch the Project Settings dialog; from this dialog, select the Audit Trail tab.

  4. Check Enable Audit Trail checkbox.

  5. From the Select Database drop-down, select your database.

  6. From the Selected Table drop-down field, press the New button.

  7. Press the OK button.


Audit Trail Maintenance

It is advisable to develop a maintenance program/plan for the audit table. The most basic version would be to periodically delete items older than a certain date. The following example deletes items older than 3 month from today:

delete from AuditTrail where Timestamp < datetime ('now' , '-3 month')
Note: For more information on date and time functions in SQLite, SQLite Date and Time Functions.


Audit Trail Table Fields

Field name | Type | Description
Timestamp | datetime | Time and date of event down to second .
Username | string | Its source is defined by the field “user tag” in Audit settings. The default is System.Users.CurrentUsername, which is the name of the current user logged. It is blank if no one is logged in.
Action | string | From $System.AuditTrail.log( )
Message | string | From $System.AuditTrail.log( )
Note: The String data types may show up as text date types in 3rd party applications.


How to View Data From an Audit Trail Database

In Designer, to view data from your Audit Trail database, create a query on the AuditTrail table:

  1. Right-click on AuditTrail table and select New Query.
  2. Provide a meaningful name for the query.

  3. In the Query Text field, enter your query, for example: SELECT * FROM [AuditTrail] order by Timestamp desc LIMIT 0, 20

    This query returns the newest 20 log items.

  4. Click Accept. Your new query will appear in the Application Explorer, under the AuditTrail table in the Databases node.

To view data in a third-party application, create the following query:

SELECT
    Timestamp, Username,  Action ,  Message
FROM
    AuditTrail


How To... Databases

These topics provide helpful guides on how to interact with Databases in Designer.

Tip: To see examples of the implementation, load the DatabaseSample project from the Cognex Designer Launch Page - Sample Projects tab.

Creating an Index for a SQLite Database

Build a SELECT Query

Get the Most Recent 'N' Rows

Filter a Table by Date/Time

Clear Data From a Table

Enable Buffer

Iterate Through Rows of a Query

Export Query Data to a CSV File

Creating/Modifying a SQLite Database Without Designer


Creating an Index for a SQLite Database

Create an Index for a SQLite Database

SQL language cannot be written directly in a script, therefore, to create an index, a Query needs to be created and then called in the OnStartup script. For example, if there is a Table that stores results: inspection time, pass/fail and the expected name of the product type. Generally, the most recent results are the primary concern, along with the ability to filter by the product type name and whether or not it passed or failed.

  1. Add a new Query for the Table, called "CreateIndex".

    Note: For more information about adding a query, see the Querying a Database topic.

  2. Add the following to the Query Text field:

    CREATE INDEX IF NOT EXISTS IDX_ReplayResults ON ReplayResults(InspectionTime DESC, ProductType, ResultCode)

    This SQL statement indicates:

    • If the index called "IDX_ReplayResults" (ReplayResults is the name of the table) does not exist, then create an index called "IDX_ReplayResults".

    • The index should include:

      • The InspectionTime column (a DateTime data type), in descending order, so that when queried for the most recent, it will be displayed first.
      • The ProductType and ResultCode will also be included.


Build a SELECT Query

Designer allows you to build a query for both SQLite (the default database) and SQL Server databases. However, the syntax for these databases is different.

The table below shows the format for constructing SELECT queries (only SELECT and FROM are operators that are required).

SQLite | SQL Server
SELECT expressions | SELECT[TOP top_value] expressions Note: SQL Server uses the optional operator, TOP, immediately after the SELECT operator, not at the end, like SQLite.
FROM tables | FROM tables
WHERE conditions | WHERE conditions
ORDER BY expression [ASC | DESC ] | ORDER BY expression [ASC | DESC ]
LIMIT number_rows OFFSET offset_value |


Get the Most Recent 'N' Rows

A common usage for tables is to display the most recent 'n' rows/results from a table.

  1. Ensure that an index for the table has been correctly configured.

    Note: See the Create an Index for a SQLite Database topic for more information.

  2. Create a query with the following in the Query Text field:

    SELECT * FROM #TABLE

    ORDER BY InspectionTime DESC

    LIMIT @Limit

    • In Designer, #TABLE will automatically be replaced with the table name that the query belongs to.
    • The InspectionTime column is a DateTime data type, used to record the date and time when the product was inspected.
    • The LIMIT refers to a Query Parameters, as an Integer data type, that selects the first 1000 rows returned from the query.


Filter a Table by Date/Time

A table can be filtered based on a product type and a date range, to display the most recent result first.

  1. Configure the database.

    1. Ensure that an index for the table has been correctly configured.

      Note: See the Create an Index for a SQLite Database topic for more information.

    2. Create a query with the following in the Query Text field:

      SELECT * FROM #TABLE

      WHERE Timestamp < @ToDate AND Timestamp >= @FromDate AND ProductType=@ProductType

      ORDER BY Timestamp DESC

    3. From the Query Builder dialog, press the Advanced button and enable the Update Query on Parameter Changed parameter.

      Note: See the Advanced Query Options topic for more information.
    4. Set the Delay before triggering parameter to a value (e.g. 50), otherwise the script code that will be instituted later will cause the query to execute twice.

  2. On a Page, from the User Controls, add two DateTime Entryelements.

    1. Set both of the DateTime Entry elements Date Format property to display the ShortDate format:

    2. One of the DateTime Entry elements will be configured for the database's FromDate parameter, and the other DateTime Entry element will be for the ToDate parameter.

      1. Configure the Value property of the first DateTime Entry to the database's FromDate parameter tag:

      2. Configure the Value property of the second DateTime Entry to the database's ToDate parameter tag:

  3. When using dates as parameters, it is important to note that they have a time field, as well. The time field must be correctly configured via script.

    1. In a User Scripts (or in the OnStartup script), enter similar code:

      // Query defaults
$Databases.FastDatabase.Results.DateSearch.Parameters.FromDate = DateTime.Now.Date.AddDays(-7);
$Databases.FastDatabase.Results.DateSearch.Parameters.ToDate = DateTime.Now.Date.AddDays(1).AddTicks(-1);


Clear Data From a Table

It can be helpful to clear stale data from a table.

  • Establish the length of time that data can reside in the table before being deleted. For example, you could establish that data more than 7 days old can be removed.

    This would involve a query with the following syntax:

    DELETE FROM #TABLE

    WHERE Timestamp < DateTime('now', '-7 days')

  • This can also be accomplished by using a tag (e.g. @MinDateToKeep), which defines the number of days to store data. This enables you to set the minimum inspection date to keep via a tag (e.g. $Databases.FastDatabase.Results.DeleteOld.Parameters.MinDateToKeep).

    When using a tag, a parameter needs to be added to the Query Parameters, MinDateToKeep, with a DateTime data type. This would change the query syntax to the following:

    DELETE FROM #TABLE

    WHERE Timestamp < @MinDateToKeep


Enable Buffer

Set the Enable Buffer parameter of a table to add a "buffer" query, which will return the last n number of records added to the table, ordered by the most recently added, first.

From the Project Explorer, right-click the table and select Enable Buffer from the menu.

When Enable Buffer is enabled for a table, a new query is created that keeps each newly added row in memory for easy access. This option is intended to be used as a simple query that displays the latest row(s) added to the table during the current session of Designer.

With this option enabled:

  • The query result is ordered so that the row added last is displayed first.
  • The query's row count is limited to the size of the buffer.
  • At startup, the query will return no rows. Only once rows have been added in the current session of Designer will there be rows to display.


Iterate Through Rows of a Query

The latest set of rows will be populated in the $Databases<DatabaseName>.<TableName>.<QueryName>.QueryResults tag each time that a Query is executed via one of the following:

  • An automatic update from an element on a Page;
  • Manually executing the $Databases.<DatabaseName>.<TableName>.<QueryName>.Run() command;

  • The Update Query on Parameter Changed parameter is enabled.

    Note: See the Advanced Query Options topic for more information.

This will enable you to iterate through the rows, and perform whatever type of processing you need to utilize. However, keep in mind the following:

  • You need to cast the row's value using the correct data type.

  • Using an integer lookup instead of a string may improve performance. For example:

    double sum = 0;
foreach (DataRow row in $Databases.FastDatabase.Results.GetRecent.QueryResults)
    sum += Convert.ToDouble(row["Confidence"]);


Export Query Data to a CSV File

Data from a query can be exported to a CSV file, which can be used by other programs.

Note:

This option has the following known limitations:

  • Precision on DateTime objects may be lost.
  • Any string with a new line or a comma will break the CSV columns.
  • Cognex recommends performing tests to ensure accuracy before deploying.

The following code illustrates how to implement this functionality, using the OnClick script point of a Button element on a Page:

string csvFilePath = "C:\\MyBackup.csv";
using (StreamWriter sw = File.CreateText(csvFilePath))
{
    foreach (DataRow row in $Databases.FastDatabase.Results.GetRecent.QueryResults)
    {
        string line = string.Join(",", row.ItemArray.Select(o => o==null ? string.Empty : o.ToString()));
        sw.WriteLine(line);
    }
}


Creating/Modifying a SQLite Database Without Designer

It is possible to create and/or modify a SQLite database with another program besides Designer. However, if this is going to be done, the following guidelines should be followed:

  • When naming your database, tables, queries and stored procedures, ensure that following are observed:
  • Names should always start with a letter.
  • Characters to be used are: A-Z, a-z, 0-9 and the underscore character (_).

  • When creating data types, ensure that data type mapping is observed (using the wrong data type names may result in the database not working):

    Designer | SQLite
    Boolean | bit
    Integer | int
    Double | float
    String | text
    DateTime | datetime
    Note:

    In addition, the following should be followed:

    • Do not use Scale or Precision.
    • Do not set a length for String or text.
    • Byte can be used instead of bit.
    • Float or double can be used interchangeably.
  • A field can be "not null"; however, be prepared to deal with an error if a value is not provided.
  • Default values can be assigned to a field.
  • An index can be added.


Developer's Guide

How To... Developer's Guide

The topics in this section provide more in-depth information for advanced developers, who may be working on complex systems, need maximum performance and are comfortable programming.

Logging with Designer

PC Performance

Debugging Designer with Microsoft Visual Studio


Logging with Designer

Designer uses the NLog logging engine (the configuration file, nlog.config, is stored in the Designer install path), which provides multiple levels of logs for the application. The logs are saved in C:\Logs, with the default file names being CD_Log_Current.csv, CD_Log0.csv, CD_Log1.csv, CD_Log2.csv, ..., CD_Log9.csv (the logs are saved from newest to oldest). Renaming or deleting a log will cause a new log to be generated.

Designer uses a rolling archive, so there will never be more than 11 log files (the maximum disk space used for logging is approximately 800MB).

The logging levels, from highest to lowest in verbosity, are: Trace, Debug, Info (the default), Warn, Error and Fatal.

  • Trace: Every little piece of information that may be useful, e.g. Log entering and exiting a method, with a lock inside of it.
  • Debug: Information that can be used to debug an application, e.g. when a button is clicked.
  • Info: Useful information about how the system is operating, e.g. if a Device is connected/disconnected.
  • Warn: When an exception or something else occurs that prevents normal use of the application; even though the application anticipated it, and handled it gracefully.
  • Error: When an exception or something else occurs that prevents normal use of the application; the application stops the routine when it occurs.
  • Fatal: Either on a "caught" crash, or something that causes the application to unexpectedly shutdown.

The logging level can be changed by modifying the NLog.config file (located at C:\Program Files\Cognex\Designer\{DesignerVersion#}\NLog.config), or by adding <space>/LogLevelFile={LogLevel} to the Designer Launcher shortcut (e.g. "C:\Program Files\Cognex\Designer\2.5\Cognex.Designer.Launcher.exe" /LogLevelFile=Trace).

You can also use the $System.Log.Write("message") and $System.Log.WriteException("message", exception) methods to post Info level log messages to the Output window of Designer, or the log file of your runtime environment in a deployed application.


PC Performance

These topics relate to considerations when designing and implementing a project on a PC, during both development and deployment.

Each PC only has a finite set of resources (e.g. processor time, memory, disk space, etc.). Having additional programs running in the background will impact the PC's performance. Therefore, Cognex recommends the following: Assess the impact that the additional programs may have on memory usage, processor performance, and in particular, disk I/O (as a general rule, disk I/O is indeterminate); where applicable, disable the additional programs, where possible.

In addition, the following external issues may be causing the Cognex Designer application to experience performance problems:

  • Anti-Virus software (real-time monitoring, daily scans, etc.)
  • Automatic Windows OS updates
  • Other monitoring services (e.g. Wireshark uses a large amount of memory, which can lead to a noticeable slowdown in performance)
Tip: Since VisionPro and Designer are both .NET applications, Cognex recommends that deployed projects have startup code in place that performs a Wake-up execution of Tasks prior to being used in runtime, to help prevent a slow first run of the system.

Multi-Threading

Hyper-Threading

Disk I/O


Multi-Threading

There is a general, "golden rule" to follow for multithreading: Only one thread per physical processor core can be running at any point in time. Therefore, a thread can only run on a single core, and cannot be spread across multiple cores.

The Windows OS does a good job of organizing threads onto separate cores, but is not guaranteed, due to the workload and load balancing required by the system.

Using multithreading does not always translate into faster performance. There are overheads associated with creating the multiple threads, and joining them back to the original thread.

Use the $System.InvokeAsync method sparingly. The purpose of this method is to allow you to run asynchronous methods from the UI, to prevent blocking and/or freezing the UI. Too many $System.InvokeAsync methods can slow down the Processing Parallel Regions.

Note: For more information, see the Microsoft Developer Network topic on Task Parallel Library (TPL).


Hyper-Threading

Hyper-Threading is a processor feature that simulates multiple cores to the OS, and is advantageous when switching between numerous threads. However, when dealing with intensive image processing, this can be problematic, especially when using a Processing Parallel Regions.

The Windows OS will typically assign each thread to a separate physical processor without Hyper-Threading. But, when Hyper-Threading is enabled, threads are assigned to separate "logical" processors, which may actually be on the same physical processor, leading to longer processing times.

Tip: Cognex recommends disabling Hyper-Threading for more consistent Task times.


Disk I/O

Reading and writing to disk can lead to varied performance times for a Task. Due to not necessarily knowing what else is using a PC's hard drive, disk I/O can delay a process if Designer needs to wait to access a file (for example, if Windows is indexing the files on the same physical disk where Designer stores its project files).

Cognex recommends the following disk I/O strategies:

  • Perform disk I/O asynchronously.
  • Use a SQL Server with a Database, especially when performance is a major factor in your application.
  • Perform disk read/writes on a separate physical drive than the drive being used by the OS; simply splitting a drive to have C and D partitions is of no benefit, and can actually decrease performance.
  • Use a solid-state drive (SSD) if disk I/O is having a negative impact on performance.

In addition, the following actions while the project is deployed may cause problems with disk I/O performance:

  • Loading an image from a disk on the same main processing Task.
  • Saving images synchronously in a Task.
  • Writing to the default database (SQLite) in safe/slow mode on the same main processing Task.

Finally, there are also some issues that may arise, outside the scope of your application, which may also cause disk I/O performance problems:

  • The OS is constantly reading/writing system files in the background; trying to read and write at the same time will result in a performance hit.
  • Anti-Virus programs tend to scan items being written to disk.

  • The Windows Disk Defragmenter program operating in the background.

    Note: On Windows 7, the Disk Defragmenter program performs disk defragmentation in the background, which can have a negative effect on performance. In a production environment, it might be worthwhile to either disable it or configure a schedule that does not impact the deployed application.


Debugging Designer with Microsoft Visual Studio

You can use Microsoft Vision Studio 2010 or higher to debug your Designer project.

  1. Add break points in a script, using the $System.Debug.Break() function.

  2. Attach Microsoft Visual Studio 2010 or higher to Designer, while Designer is running.

  3. When a break point is encountered, Visual Studio will return code that is a converted form of Designer code that you typed in the Designer Script Editor. This is because $ tags and functions are converted into GetTag<T>(tagName).Value and CSharpInvoker.InvokeFunction<T>(functionName, params[]), respectively.

    Note: Visual Studio will generate script; however, any changes made from within Visual Studio will not be reflected in the Designer Script Editor.

  4. Visual Studio also has a Watch window, which can be used to view and edit Designer tag values.

  5. Once the return value has been reached, press the F5 key to return to the Designer application.


How to Use the FORMAT Option in the Expression Builder

The Expression Builder allows you to create expressions to format values for different display options.

Note: The format strings are based on the standard Microsoft .Net format strings (Numeric Formats, Custom Numeric Formats, and Date & Time Formats).

Below are examples using the following tag values:

  • $FloatVar = 1543.456321
  • $IntVar = 255
  • $TimeVar = "25/03/2002 15:54:30 pm"

To display a floating value to only three decimal places:

  • $FloatVar FORMAT "F3" = 1543.456

To display a value in Hexadecimal format:

  • $IntVar FORMAT "X" = FF

To display a value in exponential notation:

  • $FloatVar FORMAT "E" = 1.543456E+003

To display a date value as a short date, only:

  • $TimVar FORMAT "d" = "25/03/2002"


How To... Industrial Communications

These topics provide examples for configuring a Task, using the Factory Protocol Blocks, to interact with a Rockwell, Siemens and/or Mitsubishi PLC, over their respective industrial communication protocols (EtherNet/IP, PROFINET and SLMP).

These examples assume that the connection between Designer and the PLC has already been configured. For more information about setting up the connection between Designer and a PLC, see the Setting up a PLC For Industrial Communications topic.

Note:

For specific information about configuring a Rockwell, Siemens and Mitsubishi PLC, see these respective topics:

  • EtherNet/IP PLC Configuration
  • PROFINET PLC Configuration
  • SLMP PLC Setup

Sending and Receiving Formatted Data with a PLC

Sending Acquisition Status to a PLC

EtherNet/IP Rockwell PLC Logic Example


Sending and Receiving Formatted Data with a PLC

This topic will show how to send and receive formatted data between a Designer project and a connected PLC. The information in this example can be used with any of the supported protocols (EtherNet/IP, PROFINET or SLMP) and a Cognex Communications Card or a Vision Controller.

The project is built around two Tasks ("Input" and "Output") and their Tasks; one Task ("OutputFormat") is used to send the data to the PLC, and the other Task ("InputFormat") is used to receive the data from the PLC. The Page constructs an HMI that allows the user to edit the data used by the OutputFormat Task, and view the data returned by the InputFormat Task. Tags are used to pass data between the HMI and the Tasks.

The following hardware is required:

  • A Cognex Communications Card or a Vision Controller
  • A PLC running a Factory Floor Protocol:
    • Rockwell PLC using the EtherNet/IP protocol
    • Siemens PLC using the PROFINET protocol
    • Mitsubishi Automation Controller using the SLMP protocol

Configure the Cognex Communication Card

Create Input and Output Tags

Add the Input and Output Tasks

Build the Input Task - InputFormat Sequence

Build the Output Task - OutputFormat Sequence

Construct the Page for the HMI


Configure the Cognex Communication Card

  1. Use the Cognex Comm Card Configurator utility to configure the network settings of the Cognex Communication Card or Vision Controller.

    Note: See the Network Configuration topic for more information.

  2. Connect to the card.

    Note: See the Cognex Communications Card topic for more information.
  3. Select the desired Factory Protocol: EtherNet/IP, PROFINET or SLMP.


Create Input and Output Tags

In order to pass data between the Tasks and the HMI, Tags must be defined. A set of input tags ("In***") are used to bind data for the InputFormat Task, and a set of output tags ("Out***") are used to bind data for the OutputFormat Task.

  1. Open the Tag Manager (located in the Project Explorer, under the System node).

  2. Add the following tags, with the corresponding Data Type:


Add the Input and Output Tasks

By default, each new project contains one Task and its accompanying Task.

  1. Rename the default Task as "Input" by right-clicking the Task node in the Project Explorer and selecting Rename.

  2. Select and right-click the Tasks node in the Application Explorer, and select New Task.

  3. Rename the new Task as "Output".


Build the Input Task - InputFormat Task

The InputFormat Task is constructed from a Read PLC block, a Format PLC Input Buffer block, a Decompose Collection block and a Script block. The Task is triggered by the Cognex Communication Card FFP New User Data script point, so the Task will run whenever the PLC sends new User Data to Designer.

Note: For more information, see the NDM Event Handlers and NDM Control Signals Descriptions topics.

  1. The User Data is read from the PLC, and then formatted by the Format PLC Input Data and Decompose Collection blocks.

  2. The Read PLC block has the Selected Device property set to the Cognex Communication Card. If a Vision Controller is being used, it can be used as the Selected Device, as well.

  3. The Format PLC Input Data block is configured as shown in the figure below:

    Note: This configuration works for all of the supported protocols, EtherNet/IP, PROFINET and SLMP. Simply select the appropriate protocol from the Protocol setting. See the Format PLC Input Buffer Data Format Dialog topic for more information.

  4. The Decompose Collection block is configured as shown in the figure below:

  5. The Script block performs logging actions, using the following script:

    $Counter++;
$Log = "Data received. (" + $Counter + ")" + Environment.NewLine + $Log;


Build the Output Task - OutputFormat Task

The OutputFormat Task is constructed from a Compose Collection block, a Format PLC Output Buffer block and a Notify PLC block. In the Task, a byte array is being assembled by the Compose Collection and Format PLC Output Data blocks, and then sent to the PLC via the Notify PLC block, using the NDM InspectionComplete notification function.

Note: For more information, see the NDM Notification Functions and NDM Status Signals Descriptions topics.

  1. The Compose Collection block is configured as shown below:

  2. The Format PLC Output Data block is configured as shown below:

    Note: This configuration works for all of the supported protocols, EtherNet/IP, PROFINET and SLMP. Simply select the appropriate protocol from the Protocol setting. See the Format PLC Input Buffer Data Format Dialog topic for more information.

  3. The Notify PLC block has the Selected Device property set to the Cognex Communication Card. If a Vision Controller is being used, it can be used as the Selected Device, as well. The Notify PLC block Notification Settings dialog is configured as shown below:


Construct the Page for the HMI

The Page for the HMI consists of Output and Input panels, where the user can interact and view the data being exchanged with the PLC.

  • The Output panel contains the User Controls where the operator will be able to edit the data sent by the OutputFormat Task.

    The State, Value and Text properties of the respective CheckBox, Numeric Entry and TextBox are bound to the output tags.

  • The Input panel contains the User Controls that will receive the data from the InputTask, displaying the data sent from the PLC.

    The State, Value and Text properties of the respective CheckBox, Numeric Entry and TextBox are bound to the input tags.

  • The Run button has the Click Command property set to the Tasks.Output.Run command, which executes the OutputFormat Task.


Sending Acquisition Status to a PLC

This topic will show how to send a camera's acquisition status to a PLC. The information in this example can be used with any of the supported protocols (EtherNet/IP, PROFINET or SLMP) and a Cognex Communications Card or a Vision Controller.

This example illustrates a typical application that is utilizing a Cognex Communications Card or a Vision Controller connected to a PLC, and a single camera. In this scenario, we will be simulating the Camera Device with an Image File Device, and focusing on the communication between the Cognex Communications Card/Vision Controller and the PLC.

The project is built around three Tasks and their Tasks; one Task (OnStartup) is executed when the project starts, the second Task (OnShutdown) is executed when the project closes, and the last Task (OnTrigger) is used when the PLC sends an acquisition trigger to the Cognex Communications Card/Vision Controller (named "card").

Note: For more information on simulating a device, see the Simulating Devices topic.

The following hardware is required:

  • A Cognex Communications Card or a Vision Controller
  • A PLC running a Factory Floor Protocol:
    • Rockwell PLC using the EtherNet/IP protocol
    • Siemens PLC using the PROFINET protocol
    • Mitsubishi Automation Controller using the SLMP protocol

Configure the Cognex Communication Card

Create the Tags

Add the OnShutdown, OnStartup and OnTrigger Tasks

Build the OnShutdown Task

Build the OnStartup Task

Build the OnTrigger Task


Create the Tags

This application requires two custom Tags, which are used to store the Acquisition Count ("AcqCount") and Camera Index ("CameraIndex") variables.

  1. Open the Tag Manager (located in the Project Explorer, under the System node).

  2. Add the following tags, with the an Integer Data Type:


Add the OnShutdown, OnStartup and OnTrigger Tasks

Add the OnShutdown, OnStartup and OnTrigger Tasks and Task Mode

By default, each new project contains one Task and its accompanying Task.

  1. Rename the default Task as "OnShutdown" by right-clicking the Task node in the Project Explorer and selecting Rename.

  2. Select and right-click the Tasks node in the Application Explorer, and select New Task.

  3. Rename the new Task as "OnStartup".

  4. Repeat steps 2 and 3, and rename the last Task as "OnTrigger".

  5. After the Tasks have been added, set the Task Mode for each Task.

    Note: For more information about the Task Mode, see the Task Mode topic.
  6. Right-click the OnStartup Task, and from the right-click menu, select Properties.

  7. Set the Task Mode to Manual.

  8. Also set the OnShutdown Task to Manual.

  9. For the OnTrigger Task, set the Task Mode to Event, and select Devices.{CardName}.FfpTriggerAcquisition0 from the drop-down menu.


Build the OnShutdown Task

The OnShutdown Task will be executed using the OnShutdown script, and a Notify PLC block will send the NDM NotifyAcquisitionDisabled signal to the PLC to disable the triggering of images by the camera.

Note: For more information, see the NDM Notification Functions and NDM Status Signals Descriptions topics.

  1. Write the OnStartup script.

  2. Double-click the OnShutdown script under the Scripting > Application node in the Project Explorer.

  3. Enter the following script: $Tasks.OnShutdown.Run();
  4. Add a Notify PLC block to the Task.
  5. Configure the Selected Device property to the Cognex Communications Card or Vision Controller.

  6. Set the Notification Method Type property to AcquisitionDisabled, as shown in the Notification Settings dialog below:

  7. Set the Notify PLC block's input pin to the CameraIndex tag by right-clicking the pin and selecting Assign to Tag, which will launch the Tag Selector dialog, where you can select the CameraIndex tag.


Build the OnStartup Task

The OnStartup Task will be executed using the OnStartup script, and a Notify PLC block will send the NDM NotifyAcquisitionReady signal to the PLC, after the PLC has set the Trigger Enabled bit.

Note: For more information, see the NDM Notification Functions and NDM Status Signals Descriptions topics.

  1. Write the OnStartup script.

    Note: For more information about the OnStartup script, see the Controlling the Startup State of a Deployed Project topic.

  2. Double-click the OnStartup script under the Scripting > Application node in the Project Explorer.

  3. Enter the following script: $Tasks.OnStartup.Run();
  4. Add a Notify PLC block to the Task.
  5. Configure the Selected Device property to the Cognex Communications Card or Vision Controller.

  6. Set the Notification Method Type property to AcquisitionReady, as shown in the Notification Settings dialog below:

  7. Set the Notify PLC block's input pin to the CameraIndex tag by right-clicking the pin and selecting Assign to Tag, which will launch the Tag Selector dialog, where you can select the CameraIndex tag.


Build the OnTrigger Task

The OnTrigger task is constructed to execute automatically whenever the PLC sends an Acquisition trigger to the camera. It uses a Script block to increment the value of the AcqCount tag, and then a Notify PLC block sends an AcquisitionStarted signal to the PLC. The Camera block acquires an image, and then another Notify PLC block sends an AcquisitionComplete signal to the PLC. Finally, after the image has been acquired, a Tool Block is used to process the image and perform an inspection.

Note: For more information, see the NDM Notification Functions and NDM Status Signals Descriptions topics.

  1. Add a Script block, and enter the following script:

    $AcqCount += 1;
return $AcqCount;
  2. Add a Notify PLC block to the Task.
  3. Configure the Selected Device property to the Cognex Communications Card or Vision Controller.

  4. Set the Notification Method Type property to AcquisitionStarted, as shown in the Notification Settings dialog below:

  5. Set the Notify PLC block's input pins to the CameraIndex and AcqCount tags by right-clicking the pin and selecting Assign to Tag, which will launch the Tag Selector dialog, where you can select the tags.
  6. Add a Camera block to the Task.
  7. Add another Notify PLC block to the Task.
  8. Configure the Selected Device property to the Cognex Communications Card or Vision Controller.

  9. Set the Notification Method Type property to AcquisitionComplete, as shown in the Notification Settings dialog below:

  10. Set the Notify PLC block's input pins to the CameraIndex and AcqCount tags by right-clicking the pin and selecting Assign to Tag, which will launch the Tag Selector dialog, where you can select the tags.
  11. Add a Tool Block to the Task.
  12. Link the Camera block to the Tool Block.


EtherNet/IP Rockwell PLC Logic Example

This topic provides a brief overview and examples of the logic necessary to implement communication between Cognex Designer and a Rockwell PLC, using RSLogix 5000.

EtherNet/IP Module Configuration

Import Rung

User Data Logic

Trigger Logic

Inspection Complete Logic


EtherNet/IP Module Configuration

The screen capture below illustrates the basic settings necessary to communicate the Input/Output data structure via a Cognex Communications Card or Vision Controller.


Import Rung

Currently, Designer does not have an Add-On Profile (AOP), so an import rung has been created to copy the raw data from the Cognex Communication Card or Vision Controller into the User Defined Data Type (UDT), with tags, to improve access. The import rung is located at: C:\Program Files\Cognex\VisionPro\ffp\eds\VisionController_Copy_Run.L5X

The imported rung should be placed at the beginning of the main routine.

Note: In this example, a Generic Ethernet Module is being used, so the import rung is necessary.

The UDTs that are imported will have a tag name associated with all the data points that come in and out of the Cognex Communication Card/Vision Controller.


User Data Logic

To make it easier to move the data, a User Defined Data Type (UDT) was created to send the data. Four floats are moved into the Camera1SendData. tag, then copy the string length and string into the tag, and then latch the SetUserData0 bit.

After the data has been read, the SetUserDataAck0 bit will be returned by the Cognex Communication Card. Then SetUserData0 is unlatched, and will indicate that it is OK to trigger by using the TriggerBit0 latch.


Trigger Logic

Once TriggerBit0 is turned ON, and there is no error present and the trigger is ready, TriggerCamera0 will turn ON.

When TriggerAck0 is turned ON, TriggerBit0 is unlatched. TriggerAck0 is turned ON when a Notify PLC block, configured to use the NotifyAcquisitionComplete Notification Method Type, is called in a Task.

Note: For more information about the NotifyAcquisitionComplete function, see the NDM Notification Functions topic.


Inspection Complete Logic

The InspectionComplete function is a toggled bit, and waits for ResultsValid0 to be set by the Cognex Communication Card. This is controlled by a Notify PLC block that is configured with the Notification Method Type set to InspectionComplete. The data from the InspectionResults is copied to the UDT Camera1ResultsData (all of the floats and strings having been previously setup). Then InspectionResultsAck0 is latched.

InspectionResultsAck0 is unlatched when ResultsValid is OFF.


How To... Images

This section provides useful information on different topics related to displaying and saving images, and image acquisition.

Note: For more information on the best practices related to image acquisition, see the Acquiring Images - Manual Vs. Continuous topics.

Free Run and Auto Trigger Modes

DS 1000 Series Sensor Acquisition Wizard

Acquiring Images

Change Cameras

Creating a Filmstrip

Display an Acquired Image

Saving Images

Design Applications Without Actual Camera Hardware


Free Run and Auto Trigger Modes

The Free Run and Hardware Auto trigger modes do not require the Acquisition Edit Control to run in order to begin acquisition. Acquisition begins immediately if TriggerEnable=true, and will continue until 32 images are taken. After the buffer is full, an error message is generated, which is ignored by Designer. This results in 32 images waiting in the queue for the user. When the user presses the Run button, you will retrieve the oldest image from the application queue. Then another image is acquired, another error message is ignored, and then the acquisition stops again.
The behavior is the same with the Hardware Auto trigger mode, when the hardware signals are arriving on the camera's input pin.

Note: Consider Flushing the FIFO or setting TriggerEnable = false to help manage these behaviors (see Figure 1).

Figure 1: Disabling triggers in the Acquisition Edit Control.

Related Topics The following topics can be referenced in the VisionPro® Online Documentation: Acquiring From a Connected Camera and Acquisition Edit Control.


DS1000 Series Sensor Acquisition Wizard

When the user starts the Displacement Sensor Acquisition Wizard, a second FIFO is created in addition to the FIFO created by the Acquisition Edit Control (see Figure 1). If the Acquisition Edit Control is using Free Run or the Hardware Auto trigger modes while the Displacement Sensor Acquisition Wizard is running, the Displacement Sensor Acquisition Wizard must wait for the Acquisition Edit Control FIFO to finish before it can program the DS1000 series sensor to take the image it wants. This can result in unexpectedly long waits for the Displacement Sensor Acquisition Wizard until being able to acquire either range or intensity images. It can even lead to indefinite waits, depending on the circumstances.

It may be best to disable triggers in the Acquisition Edit Control in situations involving Free Run or Hardware Auto trigger model if the user is working with the DS Acquisition Wizard (see Figure 2).

Related Topics For more information, see the Acquiring Images from a DS1000 Series Sensor topic in the VisionPro Online Documentation.

Figure 1: Starting the Displacement Sensor Acquisition Wizard

Figure 2: Disabling triggers in Acquisition Edit Control


Acquiring Images

Acquiring Images - Manual Vs. Continuous

Image acquisition is one of the most complex areas of both VisionPro QuickBuild and Designer. Since QuickBuild's Job approach is slightly different than Designer's Task and Task approach, this section tries to summarize the ideal scenarios that should be used in Designer.

Note: For more tips and tricks related to image acquisition, see the following section: How To... Images.

There are two basic scenarios for acquisition:

  1. An image is acquired manually (by pressing a button, for example).
  2. Images are acquired continuously.

Acquiring Images Manually

Acquiring Images Continuously


Acquiring Images Manually

In the case of manual acquisition, the project typically has:

  • A Task that has its trigger mode set to "Manual" (Figure 1), with a Task that has a Camera Device in it (with the acquired image bound to a tag).
  • A Page with a Button User Controls, which is bound to Tasks.Task.Run and runs the Task when pressed, and, optionally, a VisionPro Display Vision control bound to the tag of the acquired image.

When the user presses the Button, the camera device acquires an image (and displays it in the VisionPro Display control, if exists).

Figure 1: A Task configured to be triggered manually.


Acquiring Images Continuously

In the case of continuous acquisition, the application typically has:

  • A Task that has its trigger mode set to "Event" (Figure 1), with a Task that has a Camera Device in it (with the acquired image bound to a tag).
  • A Page with a Button User Controls, which is bound to Tasks.Task.Run and runs the Task when pressed, and, optionally, a VisionPro Display Vision control bound to the tag of the acquired image.
  • In the Acquisition Edit Control, the Camera has to be set to Free Run (see Figure 2).

In this case, the Camera Device starts to acquire images continuously and the VisionPro Display control displays the images like a "live feed".

Figure 1: A Task configured to be triggered by the ImageAcquired event of the Camera Device.

Figure 2: The Acquisition Edit Control on the Strobe & Trigger tab within Designer, which is opened by double-clicking the Camera block in the Task.


Change Cameras

This topic covers how to quickly change out cameras in a Task, for scenarios where a previously connected Camera Device is being swapped out for another type of camera/frame grabber.

In this scenario, the Project Explorer had been configured with Camera1 connected to a particular type of camera, and that camera connection is no longer available.

  1. Go to the Task where Camera1 was being used as a Camera Blocks.

  2. Double-click the Camera1 Block, which will open the CogAcqFifoTool.

    Related Topics

    The following topics can be referenced in the VisionPro® Online Documentation:

    • Configuring an Image Source
    • Acquiring From a Connected Camera

  3. From the Image Acquisition Device/Frame Grabber drop-down, select the desired new camera.

    Note: This drop-down menu will display all of the discovered devices on the network. Selecting a device that is already linked to an existing, configured device in Designer will result in an error.
  4. From the Video Formats drop-down, select the desired video format.

  5. Press the Initialize Acquisition button.

  6. Now the new camera can be configured.


Creating a Filmstrip

When constructing the HMI for your application, adding a filmstrip to display acquired images and the overall results of the inspection can be done by combining a Shift Register, VisionPro Display and Script Block.

  1. Add a Shift Register, and configure it to act as the filmstrip.

    1. Name the Shift Register "Filmstrip", set the Data Type to VisionPro Record and the Buffer Size to the number of images that you want to display (for this example, the Buffer Size was set to 4).

  2. Add a second Shift Register, and configure it to record the pass/fail results of the images being displayed.

    1. Name the Shift Register "PassFailResults", set the Data Type to Boolean and the Buffer Size to the number of results to be displayed (again, the Buffer Size for this example was set to 4).

  3. Add a Script Block to the Task, which will be used to compile the images and results.
    1. In the Script Definition Editor, name the script "CreateFilmstrip" and add two arguments: the first, named "Image" with a Data Type of VisionPro Record, and the second, named "Result" with the Data Type set to Boolean.

    2. In the Script Editor, add the following script:

      $Components.Filmstrip.Add(Image);
$Components.PassFailResults.Add(Result);

    3. This will create two input pins on the Script Block.

      The first input pin should be assigned to the output of the tool outputting the image, by either configuring a Tool Block to provide an output pin, or assigning the pin to a tag. The second input pin should be assigned to a block that qualifies the result as either pass or fail. In this example, a Script Block is used to qualify the results of the inspection, using the following script:

      if (CenterX > 273)
return true;
else
return false;
if (CenterY > 277)
return true;
else
return false;
if (Radius > 78)
return true;
else
return false;
  4. On the Page, add and configure the VisionPro Display elements that will be used to display the images for the filmstrip, and the Rectangle Graphics elements that will be used to indicate the pass/fail status.
    1. For the first VisionPro Display, set the Subject property to Item0 of the Filmstrip Shift Register: $Components.Filmstrip.Item0.

    2. Add the other VisionPro Display elements, and set their Subject property to the rest of the Items of the Filmstrip Shift Register (e.g. $Components.Filmstrip.Item1, $Components.Filmstrip.Item2 and $Components.Filmstrip.Item3).

      Tip: To save time and effort, right-click the first VisionPro Display element, select Copy, and then Paste the other elements. Go to each pasted VisionPro Display and set the Subject property accordingly.

    3. To display the Pass/Fail results related to the image and its inspection, add a Rectangle element and configure it to surround the VisionPro Display.

    4. Set the Color property of the Rectangle to Item0 of the PassFailResults Shift Register: $Components.PassFailResults.Item0.

      When the Tag Selector dialog appears, enable the Show All Types checkbox to navigate to the PassFailResults Shift Register tags.

      Note: The Type Mismatch dialog will appear after making the selection; ignore the mismatch and Press Yes to continue.

    5. Before closing the Expression Builder, create an association between the colors, with Green being Pass, and Red being Fail.

      Note: For more information about creating the association, see the Binding Associations topic.

    6. Add the other Rectangle elements to the VisionPro Display elements.

      Tip: To save time and effort, right-click the first Rectangle element, select Copy, and then Paste the other elements. Go to each pasted Rectangle and set the Color property accordingly. You will not need to adjust the Association.

  5. Enter Test Mode and acquire images to verify whether or not the expected images and results appear.

    Note: See the Display an Acquired Image for more information about configuring the Page to display and acquire images.


Display an Acquired Image

This topic covers how to display an image output by a Camera Reference Block, and assumes that an image Device has been added to a Task.

Note: See the Integrating Cameras topic for more information on adding and configuring a Camera Device.

  1. On the Page, from the Toolbox, open the Vision node and drag and drop a VisionPro Display onto the Page.

  2. In the Properties, press the grey dot beside the Subject parameter to launch the Expression Builder.

  3. Press the Add Tag button, and in the Tag Selector dialog, navigate to the desired image Device, select the Image and press the Accept button.

  4. The Expression Builder will now display the newly created reference. Press the Accept button.

  5. Now, in the Properties, the dot beside the Subject parameter will now be green.

  6. Next, to facilitate cycling through images, add a Button to the Page from the User Controls node.
  7. Set the Click Command parameter to Device.{CameraName}.Acquire, and in the Text parameter, enter "Acquire Image."
  8. Place the Page into Test Mode, and press the Acquire Image button to force the connected camera device to acquire an image.


Saving Images

The VisionPro Display has the ability to save the images that it is displaying, by taking a screen capture of what is being displayed and saving it to a file.

To save an image associated with a VisionPro Display, do the following:

  1. Within a Task, add and configure a Device to acquire or load images, and a VisionPro Tool Block to perform vision tasks on the images.
  2. Create a folder to store the saved images.
    1. In the Designer Project directory (C:\Users\<user_name>\Documents\Cognex Designer\Projects\<Project_Name>), create a folder for the saved images (e.g. "SavedImages").
  3. Add a tag that will be used to associate the path and file name of the saved images.
    1. In the Tag Manager, add a tag (e.g. "PathFileName") with a String Data Type.
  4. Configure the Page with a VisionPro Display, a TextBox to enter a filename for the image, and a Button to initiate the save action.
    1. Add either a VisionPro Display, and set the Subject property to either an image output by a Device or a Tool Block.
    2. Add a TextBox.
    3. Add a Button, and in the Text property enter "Save Image".
    4. Right-click the Button, and from the menu, select the OnClick script point.

    5. In the Script Editor for the OnClick script, add the following code:

      $PathFileName = $System.Info.ProjectPath + "\\SavedImages\\" + $Pages.Page.TextBox.Text;
      $Pages.Page.VisionProDisplay.Save(true, $PathFileName);
      Note: When the fitImage argument is set to True, the unscaled image and graphics will be saved (however, the graphics are clipped at the image boundary). When it is set to False, only the image, as it currently displayed, will be saved.
  5. Enter Test Mode and enter a name for the image and press the Save Image Button. The image file should appear in the specified directory.


Design Applications Without Actual Camera Hardware

You can design applications in the development environment, without the hardware of the run time environment to be present. For example if someone is creating an eight-camera application, there is no need for the eight cameras to be present all the time.

To create an application without the actual hardware present, follow the steps below:

  1. Open Designer and create a new project.
  2. Once it is created, right-click on Cameras in the Explorer pane and select Add | 'Camera' Device.

  3. Enter a name for the camera, and click Accept.

  4. An error message appears that Designer cannot connect to the hardware device; click OK to acknowledge it.

  5. You can use these camera devices in your application and replace them with the actual hardware elements in runtime environment later.
Note:
  • If you connect a physical camera, you have to disconnect the "empty" camera device that is to be replaced to be able to assign the new device the same name. The side effect of this is that the device reference block pins in Tasks all get disconnected and you have to reconnect these pins.
  • From Designer 2.0, you do not have to replace the "virtual" devices with the real ones. When you connect the physical device, it automatically replaces the virtual one.


How To... Permissions

The topics in this section describe how to work with Cognex Designer user log-ins, domains, and other security and permissions issues.

Locating a User's Group Memberships


Locating a User's Group Memberships

When using Active Directory, you can identify the group to which a user belongs by defining a custom user field.

For example, if you want to verify that a user is part of the "Vision Software" active directory group, do the following:

  1. In the Explorer pane, double-click System > Users. The User Configuration dialog box opens.

  2. In the User Configuration dialog box, in the Authentication Mode drop-down box, select Active Directory.

  3. Click Configure The Parameter Configuration dialog box opens.

  4. Enter the domain name you are configuring in the Domain field. Select Local Fallback if applicable. Click Accept.

  5. Click Define User Properties. The User Field Editor opens.
  6. Click the plus (+) icon to add a new line.
  7. Enter IsMemberOfVision_Software in the Name field. Any non-alphabetic character entered in the Name field will be removed.
  8. Enter boolean in the Data Type field.
  9. Enter false in the Default Value field.
  10. Click Save.

You can now bind to the $System.Users.IsMemberOfVision_Software tag to see whether the currently logged-in user belongs to the 'Vision Software' group.

Tip: To list all groups the current logged-in user belongs to, run the following Windows PowerShell script. Each group will be listed on a separate line in the output. (New-Object System.DirectoryServices.DirectorySearcher("(&(objectCategory=User)(samAccountName=$($env:username)))")).FindOne().GetDirectoryEntry().memberOf


How To... Plugins

The topics in this section describe how to write and work with Cognex Designer plugins, as well as provide examples and sample code.

Write a Plugin

Write a Page Plugin

Working with Plugins

Deploying Plugins

Expose Functions and Properties from Non-UI Classes to Designer

Make a Method Accessible in the Tag Browser

Skip Loading DLLs

Update An Older Plugin

Updating a Visual Studio Plugin Project


Write a Task Plugin

How to Write a Task Plugin for Cognex Designer

This topic describes how to write a Cognex Designer plugin, focusing on creating a Task block plugin.

Note: For detailed information on creating a Page element plugin, see the How to Write a Page Plugin for Cognex Designer topic.

To write a plugin for Cognex Designer, you will need the following tools:

  • Microsoft Visual Studio 2012, 2013 or 2015

  • Cognex Designer
  • .NET 4.6
  1. Open Visual Studio.

  2. Create a new Project, and select Class Library.

  3. Name your project and click OK.

  4. In Solution Explorer, right-click on References and select Add Reference.... Add the following DLLs:

    • Cognex.Designer.Core
    • Cognex.Designer.Devices
    • Cognex.Designer.Scripting
    • Cognex.Designer.Sequences
    • Cognex.Designer.HMI (if you are creating an HMI control)

  5. By default, these DLLs will be copied into the plugin folder during deployment. Trying to load the same system DLLs twice could cause runtime errors. It is recommended to set the Copy Local property for these DLLs to False.

    Note: When referencing a Cognex.Designer assembly in a Visual Studio project, the XAML designer may crash on 64-bit platforms when using Visual Studio 2012 with updates or later. Please see the Known Issues and Changes In Behavior topic for more information.
  6. Right-click on the project, select Properties.

  7. In the Build tab, set the build output to: %ProgramData%\Cognex\Designer\Plugins. The recommended structure is the following: Plugin Folder \ {Company Name} \ {Plugin Name} \ { Version } \ { Architecture } \ Config file + DLLs. See an example below:

    Another alternative is to set the Output path to any arbitrary folder and use the /addPluginFolder=”{MyPluginsBinFolder} command line argument when starting Cognex Designer (see step 9 for more details).

  8. In the Debug tab, select Start external program:%Installation Path%\Cognex.Designer.exe and the following command line argument: /project={pathToProjectFolder}

  9. Two additional arguments:

    • /addPluginFolder={pathToPluginFolder} - Adds the folder to the search path when Designer discovers plugins.
    • /project={pathToProjectsFolder} - Loads the project in the given folder.

  10. Set the working directory to the folder containing the Designer executable (by default: C:\Program Files\Cognex\Designer\<version>)
  11. Save the project.

  12. Create the plugin.config file for the plugin (simple XML file).

    Note: For more information about the plugin.config file, please see the Plugin Configuration topic.

  13. In the plugin.config Properties, set the file to Copy if newer.

  14. Add the plugin to your project as described in Plugin Configuration.

Sample Code for a Block Plugin

Give Feedback for an Error Condition in a Block


Sample Code for a Block Plugin

Here is a small sample code for a block plugin and a little explanation after the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cognex.Designer.Core;
using Cognex.Designer.Scripting;
using Cognex.Designer.Sequences;
using Cognex.Designer.Scripting.Internal;

namespace Cognex.Designer.ExampleBlocks
{
    [DisplayName("My Custom Block")]
    [Category("Example Code.Math.Test.ETC")]
    public class MyCustomBlock : ConfigurableBlock
    {
        private GenericPin<double> _input1;
        private GenericPin<double> _output1;

        public MyCustomBlock()
            {
                _input1 = CreateInputPin<double>("Input1");
                _output1 = CreateOutputPin<double>("Output1");
            }

        [DisplayName("Multiplier")]
        [Category("Behavior")]
        [BlockProperty(ConfigurationOption.All, ConfigurationOption.Editable)]

        public double Multiplier { get; set; }

        protected override void ExecuteTask()
            {
                _output1.Value = _input1.Value*Multiplier;
            }
    }
}

This block in Cognex Designer:

  1. [DisplayName] and [Category] determine the name of the plugin and where you can find it.
  2. This block has one input and one output pin ("Input1" and "Output1").
  3. Multiplier appears in the Behavior [Category("Behavior")] section in Designer; it can be configured and it has all the configuration options.

  4. [BlockProperty] determines whether you can configure the block (right-click) and what options you can choose (ConfigurationOption.All, ConfigurationOption.Editable)].

    You can choose from the following options:

    • Input: Multiplier gets its value via an input pin (from another block).

    • Output: Multiplier provides a value (e.g the result) via an output pin.

    • Tag: Multiplier appears in the Toolbox and you can use it for scripting purposes, for example: $Tasks.Task.Task.MyCustomBlock.Multiplier

  5. In ExecuteTask, you can determine how your Block behaves, in this case, the Multiplier feature.

    public double Multiplier { get; set; }

protected override void ExecuteTask()
{
    _output1.Value = _input1.Value*Multiplier;
}


Give Feedback for an Error Condition in a Block

In general, Cognex recommends not throwing exceptions in a Task or Task, since it can affect performance. However, exceptions should still be thrown in case of an error.

An error is defined as something unexpected occurring during runtime, e.g. your input image is null, or something occurring that is not defined as a failed result, e.g. expecting a result at array index 0, but receiving an empty array, instead.

When you throw an exception in a Task block, e.g. checking for bad input values, the following occur:

  • Suffer a performance hit.
  • The exception will affect the Task.
  • The Task will stop.
  • The exception will be logged to the log files.
  • The exception will be logged to the Output window (if it occurs while running in development mode).
  • The OnError script will be run (which will contain the block name and an error message).
  • In the Task Editor, the block in error will have a red circle (if it occurs while running in development mode).


Write a Page Plugin

How to Write a Page Plugin for Cognex Designer

This topic describes how to write an Page plugin for Cognex Designer. The process is shown using a simple example: an LED (Light Emitting Diode) control, which you can use to indicate that an operation has finished, for example. You can manually reset the LED by left-clicking it, which behavior can be defined in script.

Note: When creating an HMI Element that will wrap a Windows Forms object, inherit from the Cognex.Designer.HMI.Controls.WindowsFormElement, instead of from the Element class. You can then set the WFHost.Child object to the forms control that you wish to use.

To write an HMI plugin for Cognex Designer, you will need the following tools:

  • Microsoft Visual Studio 2012, 2013 or 2015
  • Cognex Designer
  • .NET 4.6
  1. Open Visual Studio.

  2. Create a new Project, and select WPF User Control Library.

  3. Name your project and click OK.

  4. In Solution Explorer, right-click on References and select Add Reference... Add the following DLLs:

    Cognex.Designer.Core

    Cognex.Designer.Scripting

    Cognex.Designer.HMI

  5. By default, these DLLs will be copied into the plugin folder during deployment. Trying to load the same system DLLs twice could cause runtime errors. It is recommended to set the Copy Local property for these DLLs to False.

    Note: When referencing a Cognex Designer assembly in a Visual Studio project, the XAML designer may crash on 64-bit platforms when using Visual Studio 2012 with updates or later. Please see the Known Issues and Changes In Behavior topic for more information.
  6. Right-click on the project, select Properties.
  7. In the Build tab, set the build Output path to C:\ProgramData\Cognex\Designer\Plugins\{Plugin Folder Name} (assuming your ProgramData directory is on the C:\ drive). For this simple LED application set it to: C:\ProgramData\Cognex\Designer\Plugins\MyLED

  8. Generally, in case you intend to establish a more sophisticated plugin system, the recommended folder structure is the following: {Plugin Folder Name} \ {Company Name} \ {Plugin Name} \ {Version} \ {Architecture} \ Config file + DLLs. See an example below:

    Another alternative is to set the Output path to any arbitrary folder and use the /addPluginFolder=”{MyPluginsBinFolder} command line argument when starting Cognex Designer (see step 10 for more details).

  9. In the Debug tab, select Start external program:{Cognex Designer Installation Path}\Cognex.Designer.exe and the following command line argument: /project={pathToProjectFolder}

  10. Two additional arguments:

    • /addPluginFolder={pathToPluginFolder} - Adds the folder to the search path when Designer discovers plugins.
    • /project={pathToProjectsFolder} - Loads the project in the given folder.

  11. Set the working directory to the folder containing the Designer executable (by default: C:\Program Files\Cognex\Designer\<version>)
  12. Save the project.

  13. Create the plugin.config file for the plugin (simple XML file) and add it to the project.

    Note: For more information about the plugin config file, please see the Plugin Configuration topic.

  14. In the plugin.config Properties, set the file to Copy if newer.

  15. Edit your XAML file as described in the XAML Sample Code for a Page Plugin topic.
  16. Edit your CS file as described in the C# Sample Code for a Page Plugin topic.
  17. Build the project.
  18. Add the plugin to your project as described in the Plugin Configuration topic.

  19. Drag and drop the plugin to your Page, and the LED will appear in your Page:

  20. For example, you can assign a mouse left-click behavior to it that toggles its status using:

    $Pages.Page.MyLED.IsLEDOn = !($Pages.Page.MyLED.IsLEDOn);

Sample Code for a Page Plugin


Sample Code for a Page Plugin

This topic shows sample code for a green LED control. It is a WPF user control library, whose XAML code and the associated C# code are shown and discussed.

XAML Sample Code for a Page Plugin

C# Sample Code for a Page Plugin


XAML Sample Code for a Page Plugin

The LED is realized with a Rectangle whose Fill color is changed from the default Black to Spring Green when the led is turned on.

The XAML code:

<MyBase:Element x:Class="MyLEDWpfControlLibrary.MyLED"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
          xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
          mc:Ignorable="d"
          xmlns:MyBase="clr-namespace:Cognex.Designer.HMI.Controls;assembly=Cognex.Designer.HMI"
          Height="41" Width="77"
          >
<Rectangle Name="MyLEDBody" Fill="Black" HorizontalAlignment="Left" Margin="20,14,0,0" Stroke="Black"
           Width="38" Height="16" VerticalAlignment="Top" />
</MyBase:Element>

The resulting LED in the WPF designer (with its default black turned off color):

XAML code explained:

  • A WPF control to be used as a Cognex Designer plugin must always inherit from the Cognex.Designer.HMI.Controls.Element class.
    This class is present in Cognex.Designer.HMI.dll, thus, the
    xmlns:MyBase="clr-namespace:Cognex.Designer.HMI.Controls;assembly=Cognex.Designer.HMI" namespace declaration is used combined with the
    <MyBase:Element ...>...</MyBase:Element> root element declaration.
  • The properties of the Rectangle that defines the body of the LED define the default appearance of the LED, including its default width and height.


C# Sample Code for a Page Plugin

The C# code for the LED:

using System;
using System.Windows.Media;
using Cognex.Designer.Core;
using Cognex.Designer.Core.Functions;
using Cognex.Designer.Scripting;
namespace MyLEDWpfControlLibrary
{
 /// &lt;summary&gt;
 /// Interaction logic for MyLED.xaml
 /// &lt;/summary&gt;
 [DisplayName("Green LED"), Category("User Controls"), Description("Green LED indicator")]
 public partial class MyLED : Cognex.Designer.HMI.Controls.Element
 {

  #region Member Variables
  private bool _isLEDOn;
  private bool _eventsSubscribed = false;
  #endregion

  #region Constructors
  public MyLED()
  {
    InitializeComponent();
    SubscribeToEvents();
  }
  #endregion

  #region Public Properties
  [DisplayName("Is LED On"), Category("Common"), Editable(), Bindable(), Published()]
  public bool IsLEDOn
  {
    get { return _isLEDOn; }
    set {
      _isLEDOn = value;
      SetLED();
      NotifyChange("IsLEDOn");
        }
  }
  [DisplayName("LED Width"), Category("Common"), Editable(), Bindable()]
  public double MyLEDWidth
  {
    get { return MyLEDBody.Width; }
    set
      {
        MyLEDBody.Width = value;
      }
  }
  [DisplayName("LED Height"), Category("Common"), Editable(), Bindable()]
  public double MyLEDHeight
  {
    get { return MyLEDBody.Height; }
    set
      {
        MyLEDBody.Height = value;
      }
  }
  #endregion

  #region Protected Methods
  protected override void SetFocus()
  {
    MyLEDBody.Focus();
  }

  protected override ScriptablePoint[] GetAllScriptPoints()
  {
    ArgumentDescriptor rParam1 = new ArgumentDescriptor("sender", typeof(object));
    ArgumentDescriptor rParam2 = new ArgumentDescriptor("e", typeof(EventArgs));
    var runParams = new ArgumentDescriptor[] { rParam1, rParam2 };
    Type returnType = typeof(void);
    var leftClickScriptPoint = new ScriptablePoint("OnLeftClick", "On Mouse Left-Click",
    "Script that runs when the LED is Left-Clicked", runParams, returnType);
    return new ScriptablePoint[] { leftClickScriptPoint, MouseMoveScriptPoint, MouseEnterScriptPoint, MouseLeaveScriptPoint };
  }
  #endregion

  #region Private Methods
  private void SetLED()
  {
    SolidColorBrush mySolidColorBrush = new SolidColorBrush();
    switch (_isLEDOn)
    {
      case true:
        mySolidColorBrush.Color = Colors.SpringGreen;
        MyLEDBody.Fill = mySolidColorBrush;
        break;
      case false:
        mySolidColorBrush.Color = Colors.Black;
        MyLEDBody.Fill = mySolidColorBrush;
        break;
    }
  }
  void MyLEDBody_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  {
    NotifyChange("IsLEDOn");
    RunScript("OnLeftClick", sender, e);
  }
  private void SubscribeToEvents()
  {
    if (_eventsSubscribed)
      return;
    else
      _eventsSubscribed = true;

    MyLEDBody.MouseLeftButtonDown += MyLEDBody_MouseLeftButtonDown;
  }
  #endregion
  }
}

C# code explained:

This plugin exposes three public properties:

  • IsLEDOn – whether the LED is on
  • MyLEDWidth – the width of the LED
  • MyLEDHeight – the height of the LED

See as they appear in the property grid below in the figure about Properties.

Attributes used on the class:

  • The [DisplayName()] and [Category()] attributes determine the name of the plugin and where you can find it.

  • The [Description()] attribute determines the displayed description for the plugin.

Attributes used on the public properties:

  • [DisplayName()] – the name of the property as it is displayed.
  • [Category()] – the category under which the property appears.
  • [Editable()] – whether an editor will be displayed for this property. If this attribute is not applied on the property, then the property will not be displayed in the property grid (Properties). Therefore, Cognex recommends that you always apply this attribute on your public properties that you want to expose.
  • [Bindable()] – whether the value of this property can be bound using the Expression Builder.
    • If the property is bindable, a grey dot appears next to it. Refer to the Binding Properties topic for details.

  • [Published()] – whether the property is available from the script. The control has to have at least one published property to be visible while scripting.

Methods used:

  • Use the NotifyChange() method to notify Cognex Designer that the value of the property has changed. It is used for the IsLEDOn property because it may change often during runtime. However, the MyLEDWidth and MyLEDHeight properties are not intended to be changed during runtime, therefore, NotifyChange() is not used in their setters.
  • Use the SetFocus() method if the control can be used for user input. If the control has a TextBox, for example, this method sets the focus on the control so that the user can type into it. The LED sample exposes a mouse left-click scriptable point, so SetFocus() is used in this case as well.

Scriptable points declared:

Use scriptable points to add scripting capability to certain events. The scriptable points will be selectable from the context menu of the control.
The LED sample defines the following scriptable point (in addition to the default MouseMoveScriptPoint, MouseEnterScriptPoint, and MouseLeaveScriptPoint scriptable points):

var leftClickScriptPoint = new ScriptablePoint("OnLeftClick", "On Mouse Left-Click", "Script that runs when the LED is Left-Clicked", runParams, returnType); where

  • "OnLeftClick", the first argument, is the unique ID for the script. You use this ID as an argument in RunScript() invoked to call the script; in the LED sample: RunScript("OnLeftClick", sender, e);
  • "On Mouse Left-Click", the second argument, is the displayed name of the script.
  • "Script that runs when the LED is Left-Clicked", the third argument, is the tooltip (description) for the script.
  • runParams, the fourth argument, is an array of the expected parameters to the script event.
  • returnType, the fifth argument, sets the type of the value the script is expected to return.

The resulting context menu:

The list in the braces defines all the events that user-defined scripts can be attached to:

 return new ScriptablePoint[] { leftClickScriptPoint, MouseMoveScriptPoint, MouseEnterScriptPoint, MouseLeaveScriptPoint };


Working with Plugins

In order for a plugin to be usable by a Designer application in development or test mode, it must meet the following requirements:

  • All of the .DLL files that implement the plugin must be stored in a single plugin directory within %ProgramData%\Cognex\Designer\Plugins\ on the PC upon which you are running Designer.
  • The directory that contains the plugin .DLL files must also contain a Plugin Configuration file that describes the characteristics and compatibility information for the plugin.

Cognex recommends that you adopt the following convention for naming and arranging plugin directories within %ProgramData%\Cognex\Designer\Plugins\:

%ProgramData%\Cognex\Designer\Plugins\_company_name_\ _plugin_name_\_version_ \ _architecture_ \

where:

  • _company_name_ is the name of the company that created the plugin.
  • _plugin_name_ is the name of the plugin.
  • _version_ is the version of the plugin
  • _architecture_ is Any, x86, or x64

Using this naming scheme allows you to manage the concurrent installation of multiple versions of a given plugin.

Note: The use of this naming scheme is optional as long as the two requirements listed above are met. Whenever you create a new project in Designer, Designer will search all directories within %ProgramData%\Cognex\Designer\Plugins\. Any plugins within the directory, or any of its sub-directories, will be added to the project's list of plugin references.

The plugin manager supports multiple versions of a plugin installed at the same time. In the case of the VisionPro plugin (which is of course required to use Designer to create a VisionPro application), each plugin has a compatibility selector that specifies the range of VisionPro versions that it works with. This means that it is likely that the window that lists plugins will show multiple VisionPro plugins, but only one of the plugins will be compatible (the rest will be red).This is because only a single version of VisionPro may be installed on a given PC at a time.

For something to go red, it must be Not Installed (i.e. there is no plugin.config in the same folder where the plugin itself is) or Not Compatible.

For a plugin to be compatible, it has to meet the following requirements :

  • Target API test (the API of Cognex Designer):

    • If the Major versions are not equal, then they are not compatible.
    • If the Minor version is less than or equal to the API’s minor version, then they are compatible.
  • Architecture test (x86/x64/Any): The architecture of the plugin must be the same as the architecture of the Cognex Designer application, or Any.
  • All of the compatibility checks (if any are used)
Note: If you install a plugin onto your machine, the plugin by default will not be available in projects created before. If the plugin is needed in one of the projects created beforehand, you have to make it available for that project through the Project Plugin Configurator. Projects created after installing the plugin will have it by default.

Plugin Configuration

Plugin and Versioning Guidelines

Updating a Plugin To a Newer Version


Plugin Configuration

In addition to the .DLL file or files that implement the plugin, each plugin directory must include a Plugin.config file that provides information about the plugin.

The Plugin.config is used to identify the plugin; there should be only one such file in the directory and all its sub directories. This file contains meta-data about the plugin, to allow Designer to make a decision on whether to load that plugin or not.

A unique plugin is identified by its CompanyName, Name and Version. If two plugins are the same, and can be loaded (i.e. they are both compatible) then Designer will not load. You will receive an error message saying that duplicate Plugins were detected.

The Plugin.config file is an XML file that must adhere to the following structure:

<?xml version="1.0" encoding="utf-8"?>
<PluginConfig>
    <CompanyName>company</CompanyName>
    <Name>plugin name</Name>
    <DisplayVersion>version_string</DisplayVersion>
    <Version>version</Version>
    <TargetAPI>api_version</TargetAPI>
    <Architecture>architecture</Architecture>

    <CompatibilityChecks>

        <ExecutableCheck>
            <ExecutableFileName>PathToExe.exe</ExecutableFileName>
            <ExecutableParameters>/debug</ExecutableParameters>
        </ExecutableCheck>

        <InstalledProductCheck>
            <Type>ProductCode</Type>
            <ProductCode>95120000-00b9-0409-0000-0000000ff1ce</ProductCode>
        </InstalledProductCheck>

        <InstalledProductCheck>
            <Type>UpgradeCode</Type>
            <UpgradeCode>3f9aef1b-b1cd-11d4-866b-0050041addaf</UpgradeCode>
            <MinVersion>82.99.3.202</MinVersion>
            <MaxVersion>83.0.0.0</MaxVersion>
        </InstalledProductCheck>

    </CompatibilityChecks>
</PluginConfig>

where:

  • CompanyName: is the name of the company that created the plugin.
  • Name: is the name of the plugin.
  • DisplayVersion: is a string representing the customer-visible version of the plugin; plain text that is used for display purposes only.
  • Version: is the plug in version number, in X.Y.Z format. For more information on versioning plugins, see Plugin and Versioning Guidelines.
  • TargetAPI: is the Designer API version. You can find the actual API version in the .
  • Architecture: can be Any, x86, or x64.
  • CompatibilityChecks: Conditions that need to be checked before loading the plugin. Compatibility checks are optional.
    • ExecutableCheck: This check is done by an executable file and returns 0 for a pass.
    • InstalledProductCheck: Checks if the installed (and required) products are existent.
      • Type: ProductCode or UpgradeCode
      • ProductCode: Checks if a program with the given GUID is installed.
      • UpgradeCode: Checks if a product is installed with the matching GUID (and between the Min and Max versions specified).
      • MinVersion: The minimum version of the product installed with the matching GUID.
      • MaxVersion:The maximum version of the product installed with the matching GUID.

A simplistic, concrete example for the LED HMI sample plugin:

<?xml version="1.0" encoding="utf-8"?>
<PluginConfig>
 <CompanyName>MyCompany</CompanyName>
 <Name>My LED</Name>
 <DisplayVersion>1.0.0.0</DisplayVersion>
 <Version>1.0.0.0</Version>
 <TargetAPI>2.0</TargetAPI>
 <Architecture>Any</Architecture>
 <CompatibilityChecks />
</PluginConfig>


Plugin and Versioning Guidelines

The following guidelines provide information on how the developer should change their version number, that is they should follow the Semantic Versioning 2.0 specification. The Designer API follows the same versioning guidelines.

Given a version number MAJOR.MINOR.PATCH, increment the:

  1. MAJOR version when you make incompatible API changes.
  2. MINOR version when you add functionality in a backwards-compatible manner, and
  3. PATCH version when you make backwards-compatible bug fixes.

This is how Designer chooses whether a plugin can be updated or not. The developer should use the Display Version property (see the Plugin Configuration topic for more information) if the developer wishes to display a different version to the end user.


Updating a Plugin To a Newer Version

Updating a Designer Project To a Newer Version Of The Plugin It Uses

Cognex Designer plugins follow the Semantic Versioning rules (see Plugin and Versioning Guidelines), so it is possible to automatically update to the highest Minor version (Major.Minor.Patch) without breaking the project. Designer always prompts the user before making any changes.

  • If a project encounters a new plugin that has a higher compatible version, then Designer asks the users if they wish to upgrade.
  • If a higher Major version is available, Designer displays it as a possible option but does not select it automatically. If the user selects this version and clicks Apply, a warning message appears.
  • If the plugin is missing, Designer lets the user choose an alternative.

  • An update question is asked once. The next time Designer will ask about the same plugin is when an even newer version becomes available. Consider this scenario:

    1. The user creates a project using version 1.5.3 of a Test Plugin.
    2. Versions 1.5.6 and 1.7.3 are installed.
    3. The user starts the project and selects version 1.5.6
    4. The next time the user launches the project, there will be no questions as no newer versions have been installed.
    5. Version 1.5.9 is installed.
    6. The user starts the project and gets a dialog with 1.5.9 and 1.7.3 as upgrade options.

The Required Plugin is Available

The Required Plugin is Not Available

The Current Plugin is Missing


The Required Plugin is Available

When the required plugin is available, an update prompt appears that a higher compatible version is discovered. The test plugin below is version 1.1.1.

If there are more different versions available Designer will act as per below:

Other Available Versions | Action
All less than 1.1.1 | Nothing
Any versions between 1.1.1 and 2.0.0 | Choose Prompt (Also displaying any version greater than 2.0.0, if available)
All versions greater than or equal to 2.0.0 | Nothing


The Required Plugin is Not Available

When the required plugin is not available, Designer shows a prompt where it offers the possible options to replace the missing plugin with another (compatible or higher) version.

If there is no compatible or higher version Designer will offer any lower versions of the same plugin.

If the user wants to load a version that is not compatible, the following dialog appears:


The Current Plugin is Missing

When the plugin is missing and there are no other plugin versions to replace it with, the following dialog appears:

  • Edit: Displays a dialog (Figure 1) to attempt to resolve the issues.
  • Continue: Continues to load the project regardless of errors. Confirmation will be required as there is a high likelihood that some parts of the project will not be able to be loaded successfully.
  • Exit: Abort the start up immediately and close Designer.

Figure 1: Project Plugin Configurator

  • The OK button remains disabled as long as red items are in the list. To solve them, uncheck all red plugins but only do this if you want to disable a plugin that is no longer used, or if you are updating to a newer version.
  • Cancel will abort the launch and closes Designer.


Deploying Plugins

Whenever you deploy a Designer project, Designer automatically copies all of the plugins referenced by the project into the deployment folder. When the deployed application runs, it does not search the %ProgramData%\Cognex\Designer\Plugins directory; instead, it uses the plugin files in the deployment folder. This makes it easy to manage the deployment of multiple applications that use different plugins or plugin versions.


Expose Functions and Properties From Non-UI Classes to Designer

To expose functions and properties from non-UI classes to Designer, you can use the Published attribute on public properties and methods of the component, or create a public static class for helper methods (static properties cannot be published). In the following example, the category attribute tells Designer how to group the published method:

[Published, Category("MyCode")]
public static int Sum(int x, int y) { return x + y; }
Note: INotifyPropertyChanged must be used in order for Designer to know that the property's value has changed.


Make a Method Accessible in the Tag Browser

When creating a plug-in for use with Cognex Designer, some of the created methods may be exposed to the end-user. To do this, attach two attributes, Category and Published, to the method. The Published attribute is the most important, because it makes the method visible, and Category helps to keep the Tag Browser organized.

A reference to the Base.dll library is necessary to access these attributes:

[Category("MyCategory")]
[Published]
public static void HelloWorld(){}


Skip Loading DLLs

It is possible to prevent Designer from trying to load certain (mainly native) DLLs from the Plugin folder. The reason for this is that users might use certain DLLs that are not part of their Plugin (i.e. there is one Plugin DLL and there are some other ones that the Plugin itself uses in the same folder), so they should not be loaded into the Designer as .Net assemblies.

To skip loading a DLL, follow these steps:

  1. Place an empty text file next to the DLL which should not be loaded.
  2. Give the file the same name as the DLL but with .ref extension. For example, "Arbitrary.ThirdParty.DllName.dll" will have its text file as "Arbitrary.ThirdParty.DllName.ref".


Update An Older Plugin

How To Update An Older Plugin

This topic summarizes what to do if you have a Plugin developed with an older Designer and you want to make it work with the newer Designer version.

  • If the new release of Designer has an API version (see section Plugin and Versioning Guidelines), which is compatible with the older API Version, then you do not need to change anything.

  • If the version of the new Designer API is not compatible with the API version you used to build your plugin, you need to recompile your plugin (see topic Updating a Visual Studio Plugin Project).

    1. If it compiles without error, you only need update the Target API in the plugin.config to the new API version (since nothing has changed in the your plugin code, there is no need to change the plugin version).

    2. If the plugin does not compile, you will need to fix the bugs, recompile and then update the API and Plugin Version accordingly.


Updating a Visual Studio Plugin Project

This topic summarizes how to update a Visual Studio Plugin project after installing a newer version of Designer.

  1. Remove old assemblies and add the new DLLs that are part of the version of Designer that you wish to target.

  2. Make sure that you project targets .Net Framework 4.6.

  3. If you have set before the Start external program and Working directory fields on the Debug tab of the Project\Properties page, do not forget to update these as well.


How To... Scripting

These topics provide helpful guides on how to implement various scripts, and scripting examples, for your project.

Get Event Aguments

Use Methods With "Out" Parameters

Run Tasks Asynchronously

Set a Default Reference for a Script

Invoke a System Call

Comment Out Multiple Lines of Code


Get Event Aguments

Get Event Arguments

When you get hold of an object with the GetInternalObject function, you also gain access to the event arguments of that object as well. See the sample below:


Use Methods With "Out" Parameters

Use Methods With "out" and "ref" Parameters

Published (Cognex Designer or Plugin) methods with out and ref parameters cannot be compiled within a script. A possible workaround is to call these methods like any other standard .NET function. If the assembly containing the methods is included as a Common script reference, they can be accessed directly. For adding references, see the Adding References topic.

For instance, the following published method cannot be invoked from script as a published ($) function:

[Category("Utilities")]
[Published]
static public void Transform(int inputParam, out CogTransform2DLinear transform, out double error)
    {}


Run Tasks Asynchronously

To run a Task asynchronously from a script, there are two options: either the InvokeAsync or RunAsync $ functions can be used:

$System.InvokeAsync("Tasks.[TaskName].Run",new object[0]);

or

$Tasks.[TaskName].RunAsync();

The following example demonstrates how to call a (typically time-consuming) User Script asynchronously from another script using the InvokeAsync $ function. This example creates a Page with a Button that, by pressing on it, performs some time-consuming operation and then displays a message after the operation finished. The time-consuming operation and the message display is implemented in another User Script. In order to not block the UI while the lengthy operation is performed, we will call the User Script asynchronously:

  1. From the Project Explorer, create the following User Script:
    • Name: MyTimeConsuminScriptWithOneParam
    • Arguments
      • Name: message
      • Type: string
  2. Open the script by double-clicking on it and enter the following into the Script Editor:
    //Let the time-consuming operation be a Sleep for 2 seconds
System.Threading.Thread.Sleep(2000);
    //Show the message from the "message" string argument
$HMI.ShowMessage(message);
  3. Create a Page and place a Button on it.
  4. Right-click the button and select Scripts > On Mouse Click.
  5. Enter the following script:
    //Call my user script asynchronously with one argument that is the "End of script." message.
    $System.InvokeAsync("MyTimeConsuminScriptWithOneParam", new Object[1] {"End of script."});


Set a Default Reference for a Script

The following example illustrates how to set a default reference for a script. In the example below, TcpServerConnectionInfo is needed, which requires the Cognex.Designer.Devices.TcpIp.dll file.

ScriptablePoint point = new ScriptablePoint
(
    scriptId,
    displayName,
    description,
    new[]
    {
        new ArgumentDescriptor("client",typeof(TcpServerConnectionInfo))
    }
    null
);

point.DefaultReferences = new[] { "Cognex.Designer.Devices.TcpIp.dll" };


Invoke a System Call

If you need to invoke a Windows system command or launch an executable file, you can use the .NET function System.Diagnostics.Process.Start(); function from within any Designer script. For example, the following command will launch the Windows Task Manager:

System.Diagnostics.Process.Start("taskmgr.exe");


Comment Out Multiple Lines of Code

There is a quick and easy way to convert multiple lines of code into comments. Simply add /* to start your comment, and */ to end the comment block, e.g. /* my commented out code */

Alternatively, you can also use the following method:

  1. Place the cursor at the beginning of the first line that you want to comment out.
  2. Hold down the Alt key, and then press the left button of your mouse.

  3. Drag the mouse down to the last line that you want to comment out. A thin, vertical highlight line will be visible.

    Note: Release and start again if the first character is captured.
  4. Release the mouse and the Alt key when you have the desired lines.
  5. Type //.
Note: The comments can be removed by repeating the same concept.


How To... VisionPro

The topics in this section provide information on configuring VisionPro Tool Blocks and how to integrate VisionPro data in your project.

Configure VisionPro Tool Blocks

Displaying 3D Images and Tool Graphics

Edit a Pattern During Runtime

Display VisionPro Tool Records

Subscribe to VisionPro Events

Use Persistent Camera Enumeration

Update a VisionPro Display From a Task


Configure VisionPro Tool Blocks

These topics cover various configuration scenarios related to VisionPro Tool Blocks, through the use of the VisionPro QuickBuild Job Editor within Cognex Designer, and how to configure the CogToolBlocks for use with Cognex Designer.

Note: See VisionPro Tool Blocks for more information on adding a VisionPro Tool Block to a Task.
Related Topics
  • Using a CogToolBlock
  • QuickBuild - Working With Jobs
  • QuickBuild - Configuring Job Properties
  • QuickBuild - Adding Vision Tools

Configure VisionPro Tool Block Graphics


Configure VisionPro Tool Block Graphics

These topics cover how to configure the two types of graphics utilized by VisionPro Tool Blocks.

Within Cognex Designer, a VisionPro Tool Block graphic is considered to be a shape or object constructed out of colored lines and/or text that may be placed on top of an image in a VisionPro Display.

There are two types of graphics: static, which cannot be altered, and interactive, which can be manipulated.

VisionPro Tool Blocks use static graphics to display information about tool results on an image, and they use interactive graphics to allow users to modify tool input parameters, such as a region, setting or value.

The following topics illustrate a Cognex Designer application wherein a VisionPro Tool Block is configured with an interactive graphic that allows a user to select an affine rectangle in an input image display, and then displays the result of the affine sampling the input image in a second display. The application displays the position and orientation of the input region as it is adjusted, and performs a transformation whenever the rectangle changes or a new image is loaded.

Before beginning, add an Image File Device, and configure it to display a collection of images. To create and configure the application, the steps are broken down into sections for Scripts, Tags, Task and Page development.

Related Topics
  • Using a CogToolBlock
  • CogToolBlock Edit Control

Connect Through Tags

Build the Task

Construct the Page

Write the Scripts


Connect Through Tags

Within Cognex Designer, tags are used to exchange data between all of the elements in the application. When building an application, tags should be used to expose values and settings that can be configured by users. In this example, tags are used to facilitate the user-interaction with the rectangle, and to convey the data to other connected elements.

  1. From the System node of the Project Explorer, double-click Tag Manager to open it as a new tab.

  2. In the Tag Manager, add the following tags:

    • imageBuffer, as a buffer for acquiring and updating images
    • myRect, as an Object Data Type. This tag will store the VisionPro CogRectangleAffine object. The rectangle will be instantiated and initialized by the script that runs on the Checked event of the CheckBox on the Page.
    • outputImage, as a vproimage Data Type. This tag will store the result of the affine transform, and is bound directly to the second VisionPro Image Display.
    • rectAngle, as a Double Data Type. This tag, and the four below, will store the rectangle's angle, position and skew data, and these tags are bound to the TextBox and Label elements on the Page, and they are updated by the script that will run on mouseUp events.
    • rectCenterX, as a Double Data Type.
    • rectCenterY, as a Double Data Type.
    • rectSkew, as a Double Data Type.

  3. Associations to the newly created tags will be made in the Build the Task and Construct the Page steps of the application development.


Build the Task

Tasks are used to define the vision inspection and the flow of the inspection, through the use of a Task. In this sample application, the Task will be comprised of an Image File Device and a VisionPro Tool Block that will process the images from the device.

  1. To begin, right-click the Tasks node in the Project Explorer and select New Task.
  2. A new Task will automatically be populated and the new Task will open in a new tab.
  3. Rename the new task to "BufferImage".
  4. Create another Task as well, with the name "CopyRegion".

Add and Configure an Image File Device

Add and Configure a VisionPro Tool Block


Add and Configure an Image File Device

For this application, an Image File Device will be used to simulate a camera and will provide images to be processed for the VisionPro Tool Block.

  1. From the Toolbox, open the Devices node and drag and drop the Image File Device onto the BufferImage Task.
  2. Set the Image File Device to a directory of images.
  3. Assign the output pin of the the device block to the imageBuffer tag.
Note: For more information, please see Camera Blocks.


Add and Configure a VisionPro Tool Block

After images are available, they can be processed by vision tools and their algorithms. In this sample application, a simple Affine Transform tool will be used to illustrate the process.

Note: For more information about adding and configuring VisionPro Tool Blocks, see the VisionPro Tool Blocks topics.
  1. From the Toolbox, expand the Vision > VisionPro node and drag and drop a Tool Block onto the CopyRegion Task. By default, this toolblock is created with an input pin that waits for a VisionPro iCogImage.
  2. Right-click on this input pin and assign it to the imageBuffer tag.
  3. Press the Run [image] button to execute the Task and pass an image to the Tool Block.
  4. Double-click the VisionPro Tool Block to open the Tool Block in a new tab, where it can be configured.
  5. From the Toolbox, expand the Image Processing folder and drag and drop a CogAffineTransformTool between the [Inputs] and [Outputs] in the Tools tab.
  6. Link the [Inputs] Image to the CogAffineTransformTool InputImage parameter, and press the Run Tools button to force the tool to execute.
  7. Go to the Inputs/Outputs tab, select Browse and add a new input: Cognex.VisionPro.CogRectangleAffine. Name it "Region."
    Note: You can find this input under VisionPro | Cognex.VisionPro.Core.dll | Cognex.VisionPro | CogRectangleAffine.

  8. Add a new Output: Cognex.VisionPro.ICogImage. Name it "OuputImage."

  9. Go back to the Tools tab, right-click the CogAffineTransformTool and select Add Terminals from the menu.
  10. Select Region and press the Add Input button, and then the Close button.

  11. Link the [Inputs] Region to the CogAffineTransformTool Region parameter, and the CogAffineTranformTool OutputImage parameter to the [Outputs] OutputImage output.

  12. Press the Run Tools button to force the tool to execute again and ensure that the tool still passes.

  13. Go to the Task tab, and the Tool Block should appear with two input pins and one output pin.

  14. Right-click the unlinked input pin, and select Assign to Tag.
  15. Check the Show All Types checkbox, and select the myRect tag, which was created in the Connect Through Tags step, and press the Accept button.
  16. Right-click the unlinked output pin, and select Assign to Tag.
  17. Select the outputImage tag and press the Accept button.

  18. Press the Run button to execute the blocks and ensure the images are being passed through.


Construct the Page

The Page will be used to create the HMI display. To solve this application, two VisionPro Display elements will be used to display the image output by a tool, as well as the area of the image defined by a rectangle. In addition, a Button will be added to cycle through images, a CheckBox will be added to enable/disable the rectangle, and four TextBox and Label elements will be added to display the location of the rectangle.

Adding the VisionPro Displays

Adding the Button

Adding the CheckBox

Adding the TextBoxes and Labels


Adding the VisionPro Displays

On a Page, the VisionPro Display is used to display images output by a Camera Device or Image File Device, or an image output by a VisionPro Tool Block. In this example, a VisionPro Display will be configured to display images output by an Image File Device, and another VisionPro Display will be configured to display the output of a rectangular region.

  1. Open a Page, and from the Toolbox, drag and drop a VisionPro Display onto the Page.
  2. Click the grey dot beside the Subject property to launch the Expression Builder.
  3. Press the Add Tag button and navigate to the Image File Device, where the Image tag will be selected. Press the Accept button.
  4. Next, add another VisionPro Display to the Page, and configure the Subject property to the outputImage tag.


Adding the Button

On a Page, a Button can be used to initiate several different types of actions. For this example, a Button will be used to acquire a new image every time the button is pushed by a user.

  1. On the Page, from the Toolbox, drag and drop a Button onto the Page.
  2. In the Text property, enter the text "Acquire Image."
  3. Right-click the Button on the Page, and from the Scripts drop-down menu, select On Mouse Click. Enter the following script:
    $Tasks.BufferImage.Run();
$Tasks.CopyRegion.Run();
  4. Alternatively, set the Click Command property to the acquisition command (Devices.{CameraDeviceName}.Acquire).


Adding the CheckBox

On a Page, a CheckBox is used to enable/disable different controls. In this example, a CheckBox is being used to enable/disable the display of an interactive rectangular region.

  1. On the Page, from the Toolbox, drag and drop a CheckBox onto the Page.
  2. In the Text property, enter the text "Show Rectangle."
  3. The script will later call Checked and Unchecked script points to check and uncheck the CheckBox.


Adding the TextBoxes and Labels

On a Page, TextBoxes are used to display text strings output by a Tool Block, or as an input for a text string into a Tool Block or other Reference Block. Labels are typically used to display text. For this example, four TextBoxes are being added to display the numeric values output by a rectangular region, and four Labels are being used to label the TextBoxes.

  1. On the Page, from the Toolbox, drag and drop four separate TextBox elements onto the Page.

  2. For each TextBox element, bind the Text property (by using the grey circle and the Expression Builder) to one of the four tags created to define the rectangle: $rectCenterX, $rectCenterY, $rectAngle and $rectSkew.

  3. Drag and drop four separate Label elements onto the Page.
  4. For each Label, in the Text property, enter one of the following: "X", "Y", "ϴ" and "Skew".

  5. Arrange the TextBox and Labels together, i.e. the TextBox configured to rectCenterX goes with the Label "X" and the TextBox configured to rectCenterY goes with Label "Y", etc.

Note: In this example, a Panel element was added to create a cleaner grouping.


Write the Scripts

Scripts are a convenient means for allowing actions to be performed, based on user-interactions. Creating the scripts involves writing the script, specifying using statements and adding references before compiling. In this example, scripts will be used to construct the interactive ability of the input region, mouse interactions and initialization of values when the application is started.

OnStartup Script

OnClick Script

OnMouseUp Script

ToggleRectangle Script


OnStartup Script

The OnStartup script will be used to initialize tag values and Properties of Page elements, which ensures that any values modified while testing will be reset to their original settings at startup.

  1. Double-click the OnStartup script under the Scripting > Application node in the Project Explorer.

  2. Enter the following script:

    $myRect = null;
$Pages.Page.Checkbox.State = false;
$Tasks.BufferImage.Run();
$Tasks.CopyRegion.Run();
  3. In the Properties, add using statements to the Code property.

  4. Press the drop-down button, and in the blank text field, enter "Cognex.VisionPro" and "Cognex.VisionPro.Display".

  5. Press the browse button of the References property, using the Script References dialog, from the Discovered References pane, add Cognex.VisionPro.dll, Cognex.VisionPro.Core.dll and Cognex.VisionPro.Display.Controls.dll to the Local References, and press the Accept button.

  6. Press the Compile button to ensure the script correctly compiles.


OnClick Script

The OnClick script will be used in conjunction with the Acquire Image Button on the Page, and will be used to run the Image File Device, and subsequently, the Task.

  1. Right-click on the Acquire Image button and select Scripts | On Mouse Click.

  2. Enter the following script:

    $Tasks.BufferImage.Run();
$Tasks.CopyRegion.Run();
  3. In Properties, add using statements to the Code property.

  4. Press the drop-down button, and in the blank text field, enter "Cognex.VisionPro" and "Cognex.VisionPro.Display".

  5. Press the browse button of the References property, using the Script References dialog, from the Discovered References pane, add Cognex.VisionPro.dll, Cognex.VisionPro.Core.dll and Cognex.VisionPro.Display.Controls.dll to the Local References, and press the Accept button.

  6. Press the Compile button to ensure the script correctly compiles.


OnMouseUp Script

The OnMouseUp script will be used in conjunction with the VisionPro Display, and will be invoked whenever a user releases the mouse on the display (the script presumes that the user was manipulating the graphic). The script will update the values of the rectAngle, rectCenterX, rectCenterY and rectSkew tags, based on the position, angle and skew of the rectangle.

  1. Right-click on the left VisionPro Display control and select Scripts | On Mouse Up.

    1. Enter the following script:

      CogRectangleAffine aRect = (CogRectangleAffine)$myRect;
$System.Log.Write("Invoking mouseup" + aRect.ToString());
if (aRect != null)
{
    $System.Log.Write("with" + aRect.CenterX.ToString() + aRect.CenterY.ToString() + "and" + aRect.Rotation.ToString() + "and" + aRect.Skew.ToString());
    $rectCenterX = aRect.CenterX;
    $rectCenterY = aRect.CenterY;
    $rectAngle = CogMisc.RadToDeg(aRect.Rotation);
    $rectSkew = CogMisc.RadToDeg(aRect.Skew);
    $System.Log.Write("Tag" + $rectCenterX);
    $Tasks.CopyRegion.Run();
}
  2. In Properties, add using statements to the Code property.

  3. Press the drop-down button, and in the blank text field, enter "Cognex.VisionPro" and "Cognex.VisionPro.Display".

  4. Press the browse button of the References property, using the Script References dialog, from the Discovered References pane, add Cognex.VisionPro.dll, Cognex.VisionPro.Core.dll and Cognex.VisionPro.Display.Controls.dll to the Local References, and press the Accept button.

  5. Press the Compile button to ensure the script correctly compiles.


ToggleRectangle Script

The ToggleRectangle script will be called by the Checked and Unchecked events of the CheckBox on the Page. This script will initialize the interactive rectangle on the VisionPro Display, and adds or removes it from the display.

  1. Right-click the User Scripts node under Scripting in the Project Explorer and select Add Script.

  2. Enter ToggleRectangle as script name.

  3. Enter the following script:

    CogRectangleAffine aRect;
CogDisplay disp;

if($myRect == null)
{
    aRect = new CogRectangleAffine();
    aRect.CenterX = 100;
    aRect.CenterY = 100;
    aRect.SetOriginCornerXCornerY(50, 50, 100, 50, 50, 100);
    aRect.Visible = true;
    aRect.Color = CogColorConstants.Red;
    aRect.GraphicDOFEnable = CogRectangleAffineDOFConstants.All;
    aRect.Interactive = true;
    aRect.SelectedSpaceName = ".";
    $myRect = aRect;
    $rectCenterX = aRect.CenterX;
    $rectCenterY = aRect.CenterY;
    $rectAngle = aRect.Rotation;
    $rectSkew = aRect.Skew;
}
else
    aRect = (CogRectangleAffine)$myRect;

disp = (Cognex.VisionPro.Display.CogDisplay)$System.GetInternalObject("Pages.Page.ImageDisplay");

if ($Pages.Page.Checkbox.State == true)
    disp.InteractiveGraphics.Add(aRect, "Rect", false);
else
    disp.InteractiveGraphics.Remove("Rect");

$Tasks.CopyRegion.Run();
  4. In Properties, add using statements to the Code property.

  5. Press the drop-down button, and in the blank text field, enter Cognex.VisionPro and Cognex.VisionPro.Display.

  6. Press the browse button of the References property, using the Script References dialog, from the Discovered References pane, add Cognex.VisionPro.dll, Cognex.VisionPro.Core.dll, Cognex.VisionPro.Display.Controls.dll and System.Windows.Forms.dll to the Local References, and press the Accept button.

  7. Right-click on the Show Rectangle checkbox on Page, and select Scripts | On Checked. Enter "$ToggleRectangle();" in the editor. Do the same for Scripts | On Unchecked as well.

  8. Press the Compile button to ensure the script correctly compiles.


Displaying 3D Images and Tool Graphics

Displaying 3D Images and 2D Tool Graphics

These topics cover how to construct a project that can be used to display 3D images output by a DS1000 Series Sensor, and the graphics output by the VisionPro 3D Tools.

The Page below displays the Range Image acquired by the DS 1000 Series Sensor [Input Image (ICogVisionData)], the Range Image with the VisionPro Tool Block result graphics [Result Image (3D Graphics)], and the 2D graphics of the VisionPro Tool Block [Result Image (2D)].

Building the Task

Constructing the Page

Configuring the Tags

Writing the Scripts

Configuring the Components


Building the Task

A Task was constructed out of an Image File Device, referencing a sample VisionPro image data base file (C:\Program Files\Cognex\VisionPro\Images\RangeWithGrey.idb), and a VisionPro Tool Blocks, containing:

  • Cog3DRangeGreySplitterScriptTool: Produces a RangeImage result, and GreyImage result, which are used as an input to the CogPMAlignTool and CogFixtureTool, respectively.
  • CogPMAlignTool: Produces the Results.Item[0].GetPose() for the CogFixtureTool RunParams.UnfixturedFromFixturedTransform input.
  • CogFixtureTool: Produces the output image (GreyImage) for the CogOCRMaxTool and CogPixelMapTool.
  • CogOCRMaxTool: Produces the LineResult (must be added as an output).
  • CogPixelMapTool: Produces the output image for the IDTool.

  • CogIDTool: Produces Results (must be added as an output).

In addition, the VisionPro tags need to be added as outputs, and the Expose ToolBlock checkbox enabled.

Note: For more information about VisionPro tags, see the Adding Tags Using the VisionPro Tag Manager topic.

Once the VisionPro Tool Block is configured, it will appear as shown below:


Constructing the Page

The Page has been constructed using the following:

  • VisionPro Display 3D (uses the "Input Image (ICogVisionData)" Label)

    Properties | Setting
    Name | Display3DInputImage
    Auto-Fit Image | Set to $Display3D.FitImage tag
    Auto Resolution | Set to $Display3D.ResolutionAuto tag
    Resolution | Set to $Display3D.Resolution tag
    Subject | Set to $InputImage.Range tag

  • VisionPro Display Status Bar 3D

    Properties | Setting
    Name | VisionProDisplay3DStatusBar
    Selected Display | Pages.Page.Display3DInputImage

  • VisionPro Display 3D (uses the "Result Image (3D Graphics)" Label)

    Properties | Setting
    Name | Display3DResultImage
    Auto-Fit Image | Set to $Display3D.FitImage tag
    Fit Graphics | Set to $Display3D.FitGraphics tag
    Auto Resolution | Set to $Display3D.ResolutionAuto tag
    Resolution | Set to $Display3D.Resolution tag

  • VisionPro Display 3D Status Bar

    Properties | Setting
    Name | VisionProDisplay3DStatusBar1
    Selected Display | Pages.Page.Display3DResultImage

  • VisionPro Display (uses the "Result Image (2D)" Label)

    Properties | Setting
    Name | Display2D
    Subject | Pages.Page.Display3DResultImage

  • CheckBox

    Properties | Setting
    Name | chkAutoResolution
    Text | Auto Resolution
    State | Set to $Display3D.ResolutionAuto tag

  • CheckBox

    Properties | Setting
    Name | chkGreyImageDisplay
    Text | Grey Image Display
    State | Set to $Display3D.GreyImageOverlay tag

  • CheckBox

    Properties | Setting
    Name | chkFitImage
    Text | Fit Image
    State | Set to $Display3D.FitImage tag

  • CheckBox

    Properties | Setting
    Name | chkFitGraphics
    Text | Fit Graphics
    State | Set to $Display3D.FitGraphics tag

  • Numeric Entry (uses the "Resolution" Label)

    Properties | Setting
    Name | numDisplayResolution
    Show Buttons | Checked
    Decimal Places | 3
    Enabled | Set to $Display3D.ResolutionAuto==false
    Value | Set to $Display3D.Resolution tag

  • Button

    Properties | Setting
    Name | ButtonRunOnce
    Text | Run Once
    Scripts

    On Mouse Click

    $Tasks.Task.Run();
$UpdateDisplay();

  • Button

    Properties | Setting
    Name | ButtonRunContinuous
    Text | Run Continuous bound to If($Components.RunContinuousTimer.IsRunning, "Stop Continuous", "Run Continuous")
    Scripts

    On Mouse Click

    if ($Components.RunContinuousTimer.IsRunning)
{
  $System.Log.Write("Stop Run Continuous");
  $Components.RunContinuousTimer.Stop();
}
else
{
  $System.Log.Write("Start Run Continuous");
  $Components.RunContinuousTimer.Start();
}

  • Button

    Properties | Setting
    Name | ButtonShutdown
    Click Command | System.Shutdown
    Text | Shutdown


Configuring the Tags

The following Tags are used to pass values between the Page, Scripts and Task.

Note: The InputImage.Grey16 and InputImage.Range tags are assigned to the Range Image and Grey Image output pins using the Assign to New Tag option, while Building the Task.


Writing the Scripts

The project utilizes several different scripts: Application, Data Change and User Scripts.

Before writing the scripts, add the following Project References and Project Usings via the System > Project Settings > Scripts dialog:

Writing the Application Scripts

Writing the Data Change Scripts

Writing the User Scripts


Writing the Application Scripts

The project utilizes the OnShutdown and OnStartup Application Scripts:

  • OnShutdown:

    $Components.RunContinuousTimer.Stop();

  • OnStartup:

    $Components.RunContinuousTimer.Stop();

$Display3D.InputImage = $System.GetInternalObject("Pages.Page.Display3DInputImage");
$Display3D.ResultImage = $System.GetInternalObject("Pages.Page.Display3DResultImage");

$Pages.Page.Display3DInputImage.Clear();
$Pages.Page.Display3DResultImage.Clear();

$OverlayGreyImage($Display3D.GreyImageOverlay, "input");


Writing the Data Change Scripts

The project contains one Data Change script, which illustrates how to update the input and result image displays. The script contains one argument: "value" = Object.

Boolean overlay = (Boolean)value;

// Update input image display
$OverlayGreyImage(overlay, "input");

// Update result image display
$OverlayGreyImage(overlay, "result");


Writing the User Scripts

There are two User Scripts utilized in the project: OverlayGreyImage and UpdateDisplay.

  • OverlayGreyImage

    The sample script illustrates how to overlay a grey output image over a range image. The script contains two arguments: "overlay" = Boolean and "display" = Object.

    CogImage16Range range = $InputImage.Range;
CogImage16Grey grey = $InputImage.Grey16;

if(range != null)
{
  // Update display
  Cog3DRangeImageGraphic rangeGraph = (overlay == true && grey != null?
    new Cog3DRangeImageGraphic(range, grey) : new Cog3DRangeImageGraphic(range));

  if (displayName.ToLower().Contains("input"))
  {
    $Pages.Page.Display3DInputImage.Clear();
    $Pages.Page.Display3DInputImage.AddGraphics(null, rangeGraph, "InputImage");
    $Pages.Page.Display3DInputImage.Fit(true);
  }
  else
  {
    $Pages.Page.Display3DResultImage.Clear();
    $Pages.Page.Display3DResultImage.AddGraphics(null, rangeGraph, "InputImage");
    $Pages.Page.Display3DResultImage.Fit(true);
  }
}

  • UpdateDisplay

    The sample script below illustrates how to take a 2D shape and transform it into a 3D graphic shape, take a 3D shape and turn it into a 3D graphic shape, and how to add a 3D graphic shape to the VisionPro Display 3D.

    Note: The following code does not include code for retrieving the existing geometric graphics from the display when the OverlayGreyImage value has changed. This will need to be implemented if the display is redrawn, and the existing graphics are to remain. For more information on incorporating how to get a list of graphics already on the display, please see the VisionPro® Online Documentation topic "Adding a 3D Display to Your Application"
    $OverlayGreyImage($Display3D.GreyImageOverlay, "input");

$Pages.Page.Display3DResultImage.Clear();

// Update result image display
if ($Tasks.Task.Task.ToolBlock.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
{
  CogImage16Range range = $InputImage.Range;
  CogImage16Grey grey = $InputImage.Grey16;

  Cog3DRangeImageGraphic rangeGraph = $Display3D.GreyImageOverlay == true ?
    new Cog3DRangeImageGraphic(range, grey) : new Cog3DRangeImageGraphic(range);

  $Pages.Page.Display3DResultImage.AddGraphics(null, rangeGraph, $Display3D.GroupResultGraphics);

  // Now add result graphics
  ICogTransform2D xform2D = grey.GetTransform("#", ".");
  ICog3DTransform xform3D = range.GetTransform3D("Sensor3D", "@");

  Boolean visible;
  UInt16 height;
  double mappedX, mappedY;

  CogOCRMaxLineResult lineResult = $Tasks.Task.Task.ToolBlock.ItemLineResult.Value as CogOCRMaxLineResult;
  if (lineResult != null && lineResult.Count > 0)
  {
    for(int id = 0; id < lineResult.Count; id++)
    {
      CogOCRMaxPositionResult r = lineResult[id];
      //#1 Figure out the XY pixel coordinate from the XY mm value of 2D graphics/shape
      xform2D.MapPoint(r.MarkRect.CenterX, r.MarkRect.CenterY, out mappedX, out mappedY);
      //#2. Get the height value at the XY from the range image
      range.GetPixel((int)mappedX, (int)mappedY, out visible, out height);
      //#3. Now map the XYZ from pixel to mm space
      Cog3DVect3 centerOfResultInMM = xform3D.MapPoint(new Cog3DVect3((int)mappedX, (int)mappedY, height));
      //#4. Create 3D rectangle shape right on top of the image
      Cog3DRectangle rect = new Cog3DRectangle();
      rect.SetOriginVertexXVectorYVector(new Cog3DVect3(-r.MarkRect.SideXLength/2, -r.MarkRect.SideYLength/2, 0),
         new Cog3DVect3(r.MarkRect.SideXLength, 0, 0),
         new Cog3DVect3(0, r.MarkRect.SideYLength, 0));
      //#5. Get rotation info
      Cog3DTransformRotation rotation = new Cog3DTransformRotation(new Cog3DEulerXYZ(0, 0, r.MarkRect.Rotation));
      rect = rect.MapShape(new Cog3DTransformRigid(rotation, centerOfResultInMM)) as Cog3DRectangle;
      //#6. create the 3D rectangle graphic from 3D shape
      if (rect != null)
      {
        Cog3DRectangleGraphic rectGraph = new Cog3DRectangleGraphic(rect);
        rectGraph.Color = CogColorConstants.Cyan;
        rectGraph.DisplayState = Cog3DGraphicDisplayStateConstants.SurfaceWithWireFrame;
        $Pages.Page.Display3DResultImage.AddGraphics(rectGraph, rangeGraph, $Display3D.GroupResultGraphics);
      }
    }
  }

  CogIDResults idResults = $Tasks.Task.Task.ToolBlock.ItemIDResults.Value as CogIDResults;
  if (idResults != null && idResults.Count > 0)
  {
    double boxSize = 5.1; // The DM code is approx. 5.1mm
    double boxHeight = 2;
    for(int id = 0; id < idResults.Count; id++)
    {
      CogIDResult r = idResults[id];
      //#1 Figure out the XY pixel coordinate from the XY mm value
      xform2D.MapPoint(r.CenterX, r.CenterY, out mappedX, out mappedY);
      //#2. Get the height value at the XY from the range image
      range.GetPixel((int)mappedX, (int)mappedY, out visible, out height);
      //#3. Now map the XYZ from pixel to mm space
      Cog3DVect3 centerOfResultInMM = xform3D.MapPoint(new Cog3DVect3((int)mappedX, (int)mappedY, height));
      //#4. Create shape
      Cog3DBox box = new Cog3DBox();
      box.SelectedSpaceName3D = r.BoundsPolygon.SelectedSpaceName;
      box.SetOriginVertexXVectorYVectorZ(new Cog3DVect3(-boxSize/2, -boxSize/2, boxHeight/2),
         new Cog3DVect3(boxSize, 0, 0),
         new Cog3DVect3(0, boxSize, 0), boxHeight);
      //#5. Get rotation info
      Cog3DTransformRotation rotation = new Cog3DTransformRotation(new Cog3DEulerXYZ(0, 0, r.Angle));
      box = box.MapShape(new Cog3DTransformRigid(rotation, centerOfResultInMM)) as Cog3DBox;
      //#6. create the graphic
      if (box != null)
      {
        Cog3DBoxGraphic boxGraph = new Cog3DBoxGraphic(box);
        boxGraph.Opacity = 0.5;
        boxGraph.Color = CogColorConstants.Green;
        boxGraph.DisplayState = Cog3DGraphicDisplayStateConstants.SurfaceWithWireFrame;
        $Pages.Page.Display3DResultImage.AddGraphics(boxGraph, rangeGraph, $Display3D.GroupResultGraphics);
      }
    }
  }
  $Pages.Page.Display3DResultImage.Fit(true);
}
else
{
  $System.Log.Write("ToolBlock failed: " + $Tasks.Task.Task.ToolBlock.ToolBlock.RunStatus.Message);
}


Configuring the Components

From the Components > Timers, a Standard Timer is used to provide a timing interval.

Properties | Setting
Name | RunContinuousTimer
Interval | 1000ms
Scripts

On Tick

$Tasks.Task.Run();
$System.Log.Write("Task time = " + $Tasks.Task.ExecutionTime);
$UpdateDisplay();


Edit a Pattern During Runtime

This topic covers how to edit a pattern for a CogPMAlignTool during Runtime, without using a VisionPro Tool Editor or a VisionPro ToolBlock Editor. This example references a Task with a single Task, with a Camera Device and a VisionPro Tool Blocks, and a single Page, with a VisionPro Display and two Button elements, all using their default names.

  1. Configure the Task.

    1. Add a Camera Device (named Camera1) connected to a VisionPro Tool Block.
    2. Within the VisionPro Tool Block, add and configure a CogPMAlignTool.
    Related Topics For more information about configuring the CogPMAlignTool, see the PatMax Software topic in the VisionPro® Online Documentation.
    3. From the VisionPro Tool Block, press the Edit Tags button and add the CogPMAlignTool as a tag (CogToolBlock > Tools > Item > CogPMAlignTool).

    4. Execute the Task.

  2. Construct the Page.

    1. In the Page, add a VisionPro Display and configure the Subject property to the Input Image of the CogPMAlignTool (e.g. $Tasks.Task.Task.ToolBlock.LastRun.CogPMAlignTool1.InputImage).
    2. Add a Button, and for the Name property use "StartTrainButton" and for the Text property enter "Start Train".
    3. Right-click on the Button element, and from Scripts select On Mouse Click.
    4. In the On Mouse Click script properties, add Cognex.VisionPro.PMAlign and Cognex.VisionPro to the Using statements.

    5. Add the following as References:

      • Cognex.VisionPro.Controls.dll
      • Cognex.VisionPro.Display.Controls.dll
      • Cognex.VisionPro.PMAlign.dll
      • Cognex.VisionPro.ToolGroup.dll
      • System.Windows.Forms.dll

    6. In the Script Editor, use the following script:

      // Get the CogPMAlignTool from the VisionPro Tool Block
CogPMAlignTool patternTool = $Tasks.Task.Task.ToolBlock.CogPMAlignTool;

// Set the Train Image to the current image
patternTool.Pattern.TrainImage = $Devices.Camera1.Image;

// Generate the records for the tool
ICogRecord currentRecord = patternTool.CreateCurrentRecord();

// Retrieve the TrainImage record, which will include the rectangle and handles, so the user may edit
currentRecord = currentRecord.SubRecords["TrainImage"];

// Get the VisionPro Display control, and set its record
CogRecordDisplay display = (CogRecordDisplay)$System.GetInternalObject("Pages.Page.VisionProDisplay");
display.Record = currentRecord;
    7. Add a second Button, and for the Name property use "EndTrainButton" and for the Text property enter "End Train".
    8. Right-click on the Button element, and from Scripts select On Mouse Click.
    9. In the On Mouse Click script properties, add Cognex.VisionPro.PMAlign and Cognex.VisionPro to the Using statements.

    10. Add the following as References:

      • Cognex.VisionPro.PMAlign.dll
      • Cognex.VisionPro.ToolGroup.dll

    11. In the Script Editor, use the following script:

      // Get the Pattern Tool
CogPMAlignTool patternTool = $Tasks.Task.Task.ToolBlock.CogPMAlignTool;

// Train the pattern
patternTool.Pattern.Train();

  3. Enter Test Mode.

    1. Press the Start Train button to configure the pattern training region.

    2. Press the End Train button once you've properly configured the training region and you want to save the newly trained pattern.


Display VisionPro Tool Records

Cognex Designer automatically creates tags for all VisionPro tool records. These records are created after the first execution of a VisionPro Tool Block, and the tags are named using the following format:

$Tasks.{TaskName}.{TaskName}.{BlockName}.{RecordName} (for example: $Tasks.Task.Task.FindBlobs.BlobTool.BlobImage)

Note: In order for the dynamic tag to be created, the Tool Blocks in the Task must be run first.

To display and select VisionPro Tool Block records:

  1. With a Page open, expand the Vision node of the Toolbox, and drag and drop a VisionPro Display onto the Page.

  2. Select the VisionPro Display Subject parameter and press the grey dot to launch the Expression Builder and bind the display to a record.

    Note: Please see the Binding Properties topic for more information on binding a Page parameter to a tag.
  3. In the Expression Builder, press the Add Tag button, and from the Tag Browser, navigate to the appropriate record and click Accept.
  4. Test the project and ensure that the correct tool record is being displayed.

Each tool block has an additional property (Record Graphics) for the user to customize the behavior (Enabled (Copy Image) by default).

  • Disabled - This disables the creation of the record tags. This will reduce processing time if the user does not need to display any records from the tool block.
  • Enabled (Copy Image) - Cognex Designer 1.0 behavior. Each record has a copied instance of the image. This ensures safe behavior into multi-threading scenarios. Slightly lower performance due to copy.
  • Enabled (No Copy) - Can cause issues in multi-threaded scenarios; only use this if this tool block is the last block in the Task.


Subscribe to VisionPro Events

To subscribe to VisionPro events:

  1. Subscribe to the event(s) in the Startup script.

    1. Get the object you want with GetInternalObject.
    2. Create an "eventHandler" tag in Tag Manager. This tag should be an object.
    3. Cast your lambda expression to the delegate type required for your event (CogChangedEventHandler in this case).

    4. Subscribe to the event of the object with the Event Handler.

      var toolblock = $System.GetInternalObject("Tasks.Task.Task.VisionProToolBlock1") as Cognex.VisionPro.ToolBlock.CogToolBlock;

$eventHandler = (CogChangedEventHandler)((sender, e) =>
    {
        System.Diagnostics.Debug.WriteLine(e.StateFlags);
    });

toolblock.Changed += ($eventHandler);

  2. Unsubscribe from the event in the OnShutdown script.

    toolblock.Changed -= ($eventHandler);


Use Persistent Camera Enumeration

Cognex Designer and its integrated VisionPro software provide an advanced capability called Persistent Camera Enumeration (PCE). PCE allows you to directly assign a specific Camera Device within Designer to a specific camera.

Persistent Camera Enumeration is an advanced capability that is turned off by default, which means that Designer and VisionPro will manage the assignments for you. Having Designer automatically manage the camera assignments will be acceptable in most situations. Instances where you may experience inconsistent assignments include when cameras are frequently failing which may cause the camera assignments to change.

Recommendation: It is only recommended to consider using PCE if you are for working with multi-camera applications AND experiencing inconsistencies with how Designer is assigning specific Camera Devices to specific cameras. PCE provides no perceived benefit for single camera applications.

Related Topics For more information on PCE and how to use it, consult the Using Persistent Camera Enumeration topic in the VisionPro® Online Documentation.


Update a VisionPro Display From a Task

Using the following code, you can perform a cross thread call to a Page thread, which could be used to update a VisionPro Display from Tasks.

System.Windows.Application.Current.Dispatcher.Invoke( () =>
{
CogRecordDisplay display = (CogRecordDisplay)$System.GetInternalObject("Pages.Diagnostics.DisplayTrainImage");
display.DisplayRecord = someOtherRecord;
});
Note: A random performance penalty will be encountered when making this call.


Precision I/O

The Cognex Communication Card and the Vision Controller both support 8 discrete input lines and 16 discrete output lines, and they support connections to external devices through an I/O terminal block or a breakout cable. The card also supports an Ethernet port for communication with industrial Ethernet devices using a supported Industrial Communications protocol.

Note: See the Communication Card Installation Manual for details on how to install the hardware and connect it to external devices.

The Cognex Communication Card allows you to create a configurable I/O event system capable of handling the signals between your vision application and the discrete I/O equipment in your production environment, without interaction with, or intervention from, the host PC as your vision application operates. This can avoid common issues related to Microsoft Windows latency when processing I/O events using typical I/O solutions.

Within a Task, the Read IO and Write IO allow you to read and write to the I/O lines, and the Cancel Event and Schedule Event allow you to handle events.

There are two ways to configure the I/O events: The Precision IO Configuration Editor, or the VisionPro programming interface, using the Cognex Communication Card API.

Note: When using either the Precision IO Configuration Editor or the Cognex Communication Card API, this type of configurable I/O event system is called precision I/O. Using a Factory Floor Protocol does not qualify as precision I/O because they require interaction with the host PC.

Precision I/O Overview

Precision IO Configuration in a Sequence

Configuring Precision I/O Events via API

Subscribing to Precision I/O Events


Precision I/O Overview

In a typical production environment, the vision application on the host PC must acknowledge and process incoming I/O signals before responding with appropriate outgoing signals:

By defining a precision I/O event system, the vision application can load a predefined set of precision I/O events onto the Cognex Communication Card and allow the processor on the card to read input lines and generate the appropriate response by setting desired output lines:

Subscribing to Precision I/O Events


Subscribing to Precision I/O Events

Precision I/O Events

A single precision I/O event is defined by its name, its causes and its responses.

For example, the following event immediately sets the Output 0 line High for 10 milliseconds when the Cognex Communication Card detects that Input 0 is High:

Name | Cause | Response
"Part Present Sensor" | Input_0 High | Output_0 High, 10 msec

A more complex event can support a collection of causes and responses. In this example, the "Stop Inspections" event will occur whenever Input lines 0, 1 or 2 are set to High:

Name | Cause | Response
"Stop Inspections" | Input_0 High | Output_0 Low
 | Input_1 High | Output_1 High, delay 10 msec
 | Input_2 High | Output_1 Low, delay 40 msec

Whenever any of these causes occur, the event will generate all the responses, specifically by setting Output 0 line to Low and pulse Output line 1 for 30ms after a 10ms delay.

Once your event collection has been defined with causes and responses, you enable the event system and allow the Cognex Communication Card to respond to signals detected over discrete I/O devices.

There are two different methods to configure an event system to schedule and respond to I/O transitions without involving the host PC (your vision application can contain any number of precision I/O events):

  • Precision IO Configuration Editor
  • Configuring Precision I/O Events via API


Adding and Configuring Events

These topics describe how to add and configure events for a communication card using the Precision IO Configuration Editor.

Adding an Event

Event Causes

Event Responses

Factory Floor Protocol

I/O Handler Script


Adding an Event

Press the plus-sign in the top-right corner of the Configured Events section to add a new event.

After adding the event, give it a descriptive name in the Event Description section.


Event Causes

The event can be given a cause. It is configured by defining the input bank and line number on which it is received, as well as the signal transition.

Note: Multiple events can be defined, however, the events will be in based on an AND/OR relationship. For more information, please see the Precision I/O Events topic.


Event Responses

The event can also be given a response. It is configured by defining the output bank and line number on which it will be sent, the signal transition, pulse width, and optionally, a delay that specifies when the output will be fired, after a specific amount of time (0 to 10000 ms).

Note: The DS1000OutputBank is only available when connected to a Vision Controller Communication Card.


Factory Floor Protocol

The Factory Floor Protocols may also be used to generate an event. In this scenario, either a TriggerAcquisition or TriggerSoftEvent can be used to cause an event. For example, a Soft Event could be used to start a Task.

Note: A Factory Floor Protocol generated event is not a precision I/O event, due to the interaction of the host PC.


I/O Handler Script

Scripts can be added to assign host notification events that allow the Cognex Communication Card to report that an event was fired on the card.

The script can be a previously created script (with arguments that match, such as non-parameter scripts or scripts with two parameters, the first being an object and the second parameter being an EventArg or CogPrioEventArg), available in the User Script directory, or a new script can be added by pressing the plus button in the I/O Handler Script section.

Pressing the plus button will launch the New Script Name dialog, where the script must be given a name.

This will create a new User Script, which will automatically be assigned the parameters of the arguments exposed by the original host notification event, and the script will also be automatically selected as the host notification script. Press the ... button to open the selected script in the Script Editor.

When the project enters either Test Mode or Deployment Mode, the precision I/O events are enabled. You can disable the host notification event by selecting None in the I/O Handler Script drop-down.


Configuring Precision I/O Events via API

Note: Precision I/O configuration is supported through the Precision IO Configuration Editor and the VisionPro programming interface (API). This topic covers the API implementation.

The API supports the CogPrio, the CogPrioEvent, and the CogPrioEventCollection classes for creating precision I/O events and configuring them to interact with a precision I/O event system.

Each precision I/O event holds a possible collection of CogPrioEventCauseLine and CogPrioEventResponseLine objects, and events do not interrupt the PC unless you explicitly configure it to do so by subscribing for HostNotification. Once your precision I/O event collection has been defined, your vision application calls the EnableEvents method to allow the Cognex Communication Card to respond to any signals that are defined as event causes.

The following example creates a single precision I/O event that triggers a light connected to discrete output line 0 in response to a signal on discrete input line 0, and then adds this event to an event collection (you would typically include this code as part of your application's OnStartup script):

Note: This example assumes that your application has a connected Communications Card device named CommCard. Also, keep in mind that your script must include a reference to Cognex.VisionPro.Comm and a similar Using statement.
// Get the connected comm card
//
if(! $Devices.CommCard.IsConnected)
    {
    $System.Log.Write("Connected CommCard Device not found.");
    return null;
    }

// Access the underlying VisionPro object

CogCommCard card = $System.GetInternalObject("Devices.CommCard") as CogCommCard;

// access the discrete io object

CogDiscreteIOAccess dioAccess = card.DiscreteIOAccess;
CogPrio mPrio = dioAccess.GetActivePrecisionIO();

// create the precision I/O event.

if (mPrio != null)
    {
    mPrio.Events.Clear();
    mPrio.DisableEvents( );

    CogPrioEvent turnOnLight = new CogPrioEvent( );
    turnOnLight.Name = "Enable the Red Light";

    CogPrioEventCauseLine mCause = new CogPrioEventCauseLine
    (CogPrioBankConstants.InputBank0, 0, CogPrioLineTransitionConstants.LowToHigh);
    turnOnLight.CausesLine.Add(mCause);

    // Turn on the light for 1 second after a 3 second delay

    CogPrioEventResponseLine mResponse = new CogPrioEventResponseLine
    (CogPrioBankConstants.OutputBank0, 0, CogPrioOutputLineValueConstants.SetHigh, 1000, CogPrioDelayTypeConstants.Time, 3000);
    turnOnLight.ResponsesLine.Add(mResponse);

    // Adds this event to the event collection

    mPrio.Events.Add(turnOnLight);

    // Verify validity (and display cause if not valid)

    if (!mPrio.Valid)
        {
        $System.Log.Write("Invalid PrIO state: " + mPrio.ValidationErrorMsg);
        }
    else
        {
        mPrio.EnableEvents();
        }
    }

Collection Validity


Collection Validity

The Cognex Communication Card API uses the Valid property to indicate whether the configuration of the precision I/O events in a collection are valid (true) or not (false). The property is updated automatically as events are added to the collection.

The precision I/O event collection cannot function while its Valid property is false, which can happen if you do any of the following:

  • Set LineBank to a value not supported by the Cognex Communication Card.
  • Set LineNumber to a value not supported by the Cognex Communication Card.
  • Configure two or more events to share the same LineBank, LineNumber and LineTransition.
  • Set OutputLineNumber to a value greater than the number of lines supported by the current bank.
  • Configure two or more events to share the same OutputLineBank, OutputLineNumber, and OutputLineValue.
  • Set DelayValue to a negative value when DelayType is set to Time (2).

Cognex strongly recommends your application check the status of the Valid property as it launches, and use the ValidationErrorMsg property as necessary to view the error messages that describe issues with the events collection.


Subscribing to Precision I/O Events

By default a precision I/O event does not notify the vision application when it fires. If you want your application to be notified when a configured precision I/O event fires, you must write a script function and then add a delegate function that calls the script function to the event collection's HostNotification event delegate collection.

You do this by modifying the OnStartup script that configures and adds a precision event as shown in the red lines, shown in theSubscribing to Precision I/O Events - OnStartup (the original script can be found in the Configuring Precision I/O Events via API topic).

Note: It is important to distinguish between the script function and the event delegate function. The event delegate function must be created as a block of inline code written in the OnStartup script. This function, in turn, calls the script function that you write.

In addition to adding the event handler to the HostNotification event collection on startup, it also important that you remove the handler from the HostNotification collection on shutdown. If you do not do this, an additional instance of the handler will be added to the collection each time you enter test mode.

To do this, you must do the following:

  • In the OnStartup script, you must store the delegate function in a global tag.
  • In the OnShutdown script you must remove the delegate function from the HostNotification collection.

Subscribing to Precision I/O Events - OnStartup


Subscribing to Precision I/O Events - OnStartup

Note: This example assumes that your application has a connected Communications Card device named CommCard. Also, keep in mind that your script must include a reference to Cognex.VisionPro.Comm and a similar Using statement.

The following OnStartup script configures the event and adds it to the HostNotification collection:

// Get the connected comm card
//
if(! $Devices.CommCard.IsConnected)
    {
    $System.Log.Write("Connected CommCard Device not found.");
    return null;
    }

// Access the underlying VisionPro object

CogCommCard card = $System.GetInternalObject("Devices.CommCard") as CogCommCard;

// access the discrete io object

CogDiscreteIOAccess dioAccess = card.DiscreteIOAccess;
CogPrio mPrio = dioAccess.GetActivePrecisionIO();

// create the precision I/O event.

if (mPrio != null)
    {
    mPrio.Events.Clear();
    mPrio.DisableEvents( );

    CogPrioEvent turnOnLight = new CogPrioEvent( );
    turnOnLight.Name = "EventCapture";

    CogPrioEventCauseLine mCause = new CogPrioEventCauseLine
    (CogPrioBankConstants.InputBank0, 0, CogPrioLineTransitionConstants.LowToHigh);
    turnOnLight.CausesLine.Add(mCause);

    // Turn on the light for 1 second after a 3 second delay
    CogPrioEventResponseLine mResponse = new CogPrioEventResponseLine
    (CogPrioBankConstants.OutputBank0, 0, CogPrioOutputLineValueConstants.SetHigh, 1000, CogPrioDelayTypeConstants.Time, 3000);
    turnOnLight.ResponsesLine.Add(mResponse);

       // Now create an event handler and assign it to a tag.
       // The event handler will call the user script
       // $HandlePrIOEvent

       $PRIOEventHandler = (CogPrioEventHandler)((sender, e) =>
       {

       // Note that you should never allow event handlers to
       // throw unhandled exceptions as this will cause
       // Designer to crash.

    try
      {
        $HandlePrIOEvent(sender, e);
    }
    catch(Exception exception)
    {
        $System.Log.Write(exception.Message);
    }});

    turnOnLight.HostNotification += (CogPrioEventHandler) $PRIOEventHandler;

    // Adds this event to the event collection

    mPrio.Events.Add(turnOnLight);

    if (!mPrio.Valid)
        {
        $System.Log.Write("Invalid PrIO state: " + mPrio.ValidationErrorMsg);
        }
    else
        {
        mPrio.EnableEvents();
        }
    }

Your event handling script ($HandlePrIOEvent in the example above), is called with two arguments, the object that invoked the event and a CogPrioEventArgs that provides information about the state of the Precision I/O substation at the time that the event fires.

There are some important restrictions to keep in mind while writing event notification functions:

  • You should avoid writing an event handler that takes a long time to execute.
  • Your event handler must not throw any unhandled exceptions
  • Your event handler should not attempt to manipulate any HMI elements
  • You should unregister your delegate function on application shutdown.

The following script shows how you can access the information in the CogPrioEventArgs object to update system tags:

Note: Your script must include a reference to Cognex.VisionPro.Comm and a similar Using statement.
// Cast the argument to the correct type
//
CogPrioEventArgs eArgs = (CogPrioEventArgs) e;

// Set tag values for the line state and timestamp
//
$LineState = eArgs.State.Line(CogPrioBankConstants.InputBank0 ,0);
$TimeStamp = eArgs.State.TimeStamp.ToString();

The following OnShutdown script shows how you remove the notification handler delegate function:

// Get the connected comm card
if(!$Devices.CommCard.IsConnected)
{
  $System.Log.Write("Connected Comm Card Device not found.");
  return null;
}

// Access the underlying VisionPro object

CogCommCard card =  $System.GetInternalObject("Devices.CommCard") as CogCommCard;

if(card == null)
{
  $System.Log.Write("Comm Card Internal Object not found.");
  return null;
}

// Get a reference to the Prio object.
CogPrio prio =  card.DiscreteIOAccess.GetActivePrecisionIO();

if (prio == null)
{
  $System.Log.Write("Precision I/O Internal Object not found.");
  return null;
}

// Disable events during configuration

prio.DisableEvents( );

// remove the host notification event handler, retrieving it from the global tag.

prio.Events["EventCapture"].HostNotification -=  (CogPrioEventHandler) ($PRIOEventHandler);

// Always check the valid state of the prio object.
// If Valid is false the events will not be configured on the Comm Card.

if (!prio.Valid)
{
  $System.Log.Write("Invalid PrIO state: " + prio.ValidationErrorMsg[0]);
}
else
{
  // Done configuring events. Call Enable.
  prio.EnableEvents();
}


Setting Timeout for WebHMI

To add extra security, you may want to enable an automatic timeout (in minutes) to prevent authentication with WebHMI after a certain period of inactivity by the user. When the set Inactivity Timeout value expires, the dialog is locked and authentication is required to proceed.

Note: You cannot set an automatic timeout in test mode.

Set this timeout setting in the Project Settings panel, as follows.

  1. In the Explorer pane, go to System > Settings. Open the Project Settings dialog by double-clicking on Settings.
  2. In the Project Settings dialog, in the left navigational pane, select WebHMI.
  3. Select the Enable Built-In Authetication checkbox.
  4. Select the Inactivity Timeout checkbox .Select the time timeout value (the number of minutes before authentication to WebHMI timesout), using the arrow keys in the (min) field.
  5. Click Apply and OK.


Web Pages

Web Pages are used to create a Human Machine Interface (HMI) user interface (UI) while in deployed mode. These can be displayed on an Internet Web Browser (Internet Explorer and Google Chrome), using HTML5, or in the deployed mode tab of the application.

The HMI gives operators the ability to visualize data (images, graphics and/or data), and interact with the vision system. Web Pages allow the application developer to create a run-time display that shows only pertinent project data.

When graphics controls are included in the WebPage, the operator on the production floor can make simple adjustments to the project, but they cannot modify formulas directly in the Vision Tools.

When designing your HMI, consider what parameters should be configurable, the level of interaction the operator will be responsible for, and the layout and presentation of the interface.

Note: The project must be in deployed mode to interact with the WebPage Elements. While the project is in Program Mode, none of the WebPage Elements are active.