Skip to main content
Version: 8.1

Gateway Event Scripts

Gateway Event Scripts Overview​

Gateway Event Scripts are scripts that run directly on the Gateway. They are useful because they always run, regardless if any sessions or clients are open. They also provide a guaranteed way to make sure only a single execution of a particular script occurs at a time, as opposed to placing a script in a window, as there could be multiple instances of the window open at a given point of time.

Note that even though Gateway Event Scripts run on the Gateway, they're still considered a project resource. Project backups will include any Gateway Event Scripts.

The Gateway Event scripting workspace is located in the Scripting menu of the Designer or in the Project Browser under Scripting > Gateway Events.

Other Event Scripts​

Inductive University

Gateway vs Client Event Scripts

Watch the video

The content on this page will focus primarily on Gateway Event Scripts. However, there is some overlap with Client Event Scripts, as they have similar events. More information can be found on the Client Event Scripts and Perspective Session Event Scripts pages.

note

System functions are available for both Client Event Scripts and Gateway Event Scripts, but some system functions are specific to either one or the other. When you're writing event scripts, it's important to remember the scope of where you're writing the script: Client or Gateway. You can check System Functions in the Appendix to see list of all system functions, their descriptions, and what scope they run in.

Startup Script​

Inductive University

Startup Scripts

Watch the video

The Startup Script event runs at the startup of the Gateway. Additionally, if the project is restarted in someway, such as by making a change to a Gateway Event Script and saving, then the Startup Script will be called. This means that while editing scripts frequently in the Designer, the startup and shutdown events may happen frequently.

Gateway Startup Behavior​

There is a specific order to when the various startup scripts are run. When troubleshooting your Gateway startup times, consider the following:

  1. Gateway starts - The Gateway will start as an OS service, and start the context. No startup scripts can run before this is complete.
  2. Projects are started - This includes all of the Gateway scoped items in the projects such as Transaction Groups, SFCs, etc. This does not refer to launching clients, and no clients can be automatically launched at this time. All Gateway Startup Scripts are run at this time for each project. Note: if you copied a project, always check for Gateway scoped events such as these. You generally don't want a Gateway Startup Script to run twice because it is in two projects.

Update Script​

The Update Script event runs after a project is saved or updated on the Gateway. This enables you to insert a script that will run every time a project is saved.

​

New in 8.1.14
This script now reports which resources were modified during a project save. The following parameters have been added:

ParameterDescriptionType
actorThe user or system responsible for the project update.String
resourcesA dictionary that holds the following keys: See resources.Dictionary

'resources'​

KeyDescription
addedList of dictionaries containing information about resources that were added to the project.
removedList of dictionaries containing information about resources that were removed from the project.
modifiedList of dictionaries containing information about resources that were modified.
manifestChangedA boolean variable indicating whether or not a change has been made to the project settings on the Gateway.

Shutdown Script​

Inductive University

Shutdown Scripts

Watch the video

The Shutdown Script event runs at the shutdown of the project, which means it can be used as a way to trigger a script when the Gateway has to be restarted. It allows you to run a piece of code as the shutdown is occurring. After the script completes, the shutdown will finish.

Note that the Shutdown Script event only gets called if the Gateway is requested to shut down: if the computer power is lost abruptly (power outage, hard restart, etc.) this shutdown script will not run.

Gateway Shutdown Behavior​

Similar to how a Gateway Event Scripts#Startup Script behaves, "Shutdown" in the context of this event means "project shutdown", so shutting down the Gateway would trigger this event, as well as disabling the project containing a script on this event. Additionally, making a change to a Gateway Event Script in the Designer, and then saving the project will cause the project to restart, which means this event can get called by simply making changes in the Designer and saving.

Timer Script​

Inductive University

Timer Scripts

Watch the video

The Timer Scripts execute periodically on a timer at a fixed delay or rate. This allows you to set up a sort of heartbeat that can run on the Gateway. This is the ideal event to use if you need the Gateway to periodically perform some scripting task.

Since multiple Timer Scripts can be added, there are separate buttons that allow you to manage each Timer Script.

  • Add Timer Script - Adds a new Timer Script.
  • Remove Timer Script - Will delete the selected Timer Script.
  • Modify Timer Script - Will modify the settings for the selected Timer Script.

Timer Script Settings​

Below is an overview of the settings for a Timer Script.

  • Name: The name of the Timer script. Names must be unique per project, so two timer scripts in the same project cannot have the same name.
  • Delay: The delay period in milliseconds. The meaning of this setting is dependent on the Delay Type setting.
  • Enabled: Allows you disable the Timer Script when set to false.
  • Delay Type: Determines how the Delay setting is utilized.
    • A Fixed Delay timer script (the default) waits for the given Delay between each script invocation. This means that the script's rate will actually be the delay plus the amount of time it takes to execute the script. This is the safest option since it prevents a script from mistakenly running continuously because it takes longer to execute the script than the delay.
    • Fixed Rate scripts attempt to run the script at a fixed rate relative to the first execution. If the script takes too long, or there is too much background process, this may not be possible. See the documentation for java.util.Timer.scheduleAtFixedRate() for more details.
  • Threading: Determines which thread this script should run in. In other words, this setting allows you to specify if you want this timer script to share execution resources or not. The rule of thumb here is that quick-running tasks should run in the shared thread, and long-running tasks should get their own dedicated thread.
    • The Shared setting means that all timer scripts will share a thread. This is usually desirable, as it prevents creating lots of unnecessary threads: threads have some overhead, so a small amount of resources are used per thread. However, if your script takes a long time to run, it will block other timer tasks on the shared thread.
    • The Dedicated setting will create a separate thread specifically for the timer script to use. This setting is desirable when your scripts executions must be as consistent as possible, as other timer scripts can't slowdown or otherwise impact the execution of a script in a separate thread.

Tag Change Scripts​

Inductive University

Tag Change Scripts

Watch the video

The Tag Change Script event allows you to specify any number of Tags, and trigger a script when one of them change. Since these execute based on a Tag changing value, Tag Change Scripts are ideal when you need a script to run based on some signal from a PLC.

Having the Tag Change Scripts run in the Gateway Scope means that the scripts are active as long as the Gateway is running. Thus, you do not need a client or session to be open for a Gateway Tag Change Script to execute. When executing, each Tag Change Script runs in a separate thread. This prevents long running scripts from blocking the execution of other Tag Change Scripts.

note

Due to their nature, Client Tags will not trigger Gateway Tag Change Scripts. However, there are other similar events, such as a Client Event Script, that enable you to trigger a script based on a Client Tag changing value.

Tag Change Script Interface​

Tag List​

Lists all of the available Tag Change scripts in the project. Two icons are available below the list:

  • Add Script - Adds a new Tag Change Script to the list.
  • Remove Script - Removes the currently selected script from the list.

Tags Tab​

The Tags tab contains settings for the script. See the Script Settings description below:

  • Script Name - The name of the script. Script names must be unique per project.

  • Enabled - Determines if the script is active or not. Set to false to disable the script.

  • Change Triggers - When the Tag changes, the script can trigger based on the Value, Quality, and/or Timestamp. Note that regardless of how many triggers changed, the script only executes once per tag, so leaving all triggers enabled will not trigger three executions each time the Tag changes.

  • Tag Paths - A list of Tag paths to monitor. When any of the Tags listed in this area change, the script will trigger. Note that the list is not comma separated: new paths are specified each line.

    • Tag Browser - Opens a Tag Browser window, allowing you to quickly lookup and add Tag paths to the Tag Change Script.

    • Path Diagnostic - Click this icon to verify the paths specified under the Tag Paths list. This is useful for checking for typos in the list.

    • Wildcards can be used at the end of configured tag paths. Using a wildcard will execute the script for all tags within the same folder. In the below example, the script "New Script" will run when the value of any tag in the "folder" folder changes.

      note

      Wildcards can only be used at the folder level and cannot be used at the tag level. For example, configuring a tag path like [default]folder/* will execute a script on all tags within the folder, but [default]folder/ramp* will not.

Script Tab​

The Script tab is where the Python script associated with this event will be placed.

Tag Change Objects​

Tag Change Scripts contain several built-in objects that are useful for inspecting the event, such as seeing what value the Tag changed to. These objects are listed below.

The initialChange Value​

The boolean initialChange variable indicates if an event is due to an initial subscription. The initialChange value is true only when the script runs for the first time after the project updates, which happens when the executionCount is 0. The initialChange variable can be used to filter out an event preventing a script from running when the values haven’t actually changed.

note

Whenever you make changes to your project that affect scriptsβ€”like updating your project library or modifying event scriptsβ€”all the event scripts, including timers, scheduled scripts, and tag change scripts, are restarted. Once restarted, your executionCount will be reset to 0.

if not initialChange:

# Do something useful here

The executionCount Value​

An integer representing a number of event executions since gateway scripts were restarted (typically by applying a change to a script and saving the project).

if executionCount <= 1:
pass

The newValue Object​

A QualifiedValue object that represents the current value on the tag.

MethodReturnsDescriptionUsage Example
getValue()VariesReturns the new value on the tagnewValue.getValue()
getQuality()QualityCodeReturns the new quality on the tagnewValue.getQuality()
getTimestamp()DateReturns the new timestamp valuenewValue.getTimestamp()

The previousValue Object​

A QualifiedValue object that represents the previous value of the tag.

MethodReturnsDescriptionUsage Example
getValue()VariesReturns the previous value on the tagpreviousValue.getValue()
getQuality()QualityCodeReturns the previous quality on the tagpreviousValue.getQuality()
getTimestamp()DateReturns the previous timestamp valuepreviousValue.getTimestamp()

The Event Object​

This object offers some additional utility, such as accessing the previous values on the tag.

Method/AttributeReturnsDescriptionUsage Example
getCurrentValue()QualifiedValueReturns a QualifiedValue object (similar to the newValue object), representing the current value on the tag.event.getCurrentValue().getValue()
getPreviousValue()QualifiedValueReturns a QualifiedValue object, representing the values on the tag before the change.event.getPreviousValue().getValue()
getTagPath()TagPathReturns a TagPath object, that can be further examined for details about the path on the tag that changed. See the TagPath Object table below. Additionally, the TagPath object can easily be turned into a string, providing quick access to the path of the tag that changed value.event.getTagPath()
getValue()QualifiedValueReturns a QualifiedValue object (similar to the newValue object), representing the current value on the tag. This method is functionally identical to getCurrentValue(), and maintained mostly for backwards compatibility reasons.event.getValue().getValue()
changesTagChangeTypeA RegularEnumSet typed attribute that describes what changed: the value, quality, or timestamp. Values in the set are TagChangeType objects, which can be converted to string with either Python's built-in str() or Java's toString().
for i in event.changes:
if i.toString() == "ValueChange"
foo()
tagPathAn attribute that describes the tag path on the tag that changed. See tagPath.event.tagPath.getItemName()
event.tagPath.getParentPath()
tagPath​
Method/AttributeReturnsDescription
getItemName()stringReturns the name of the item at the end of the tag path, which can be used to get the name of the tag that changed.
getParentPath()BasicTagPathReturns a BasicTagPath of the tag's parent folder. Python's str() method can be used to convert the path to a string.

Message Scripts​

Inductive University

Script Messaging

Watch the video

Message Handlers allow you to write a script that will run in the scope they are located in, but they can be invoked by making a call from other projects or even other Gateways. They can be called using three different scripting functions: system.util.sendMessage, system.util.sendRequest, and system.util.sendRequestAsync.

Under the list of handlers, three small buttons allow you to add, remove and manage your handlers.

  • Add Message Handler - Will add a message handler.
  • Remove Message Handler - Will delete the highlighted message handler.
  • Modify Message Handler - Will modify the settings for the highlighted message handler.

Gateway Message Handler Settings​

When adding or modifying a message handler, a Message Handler settings window will popup.

The following settings are available:

  • Name - The name of the message handler. Each message handler must have a unique name per project.
  • Threading - Determines the threading for the message handler. Contains the following options:
    • Shared - The default way of running a message handler. Will execute the handler on a shared pool of threads in the order that they are invoked. If too many message handlers are called all at once and they take long periods of time to execute, there may be delays before each message handler gets to execute.
    • Dedicated - The message handler will run on its own dedicated thread. This is useful when a message handler will take a long time to execute, so that it does not hinder the execution of other message handlers. Threads have a bit of overhead, so this option uses more of the Gateway's resources, but is desirable if you want the message handler to not be impeded by the execution of other message handlers.
  • Security - Allows you to specify security zone and role combinations that are allow to request this message handler.

The Payload​

Inside the message handler is your script. The script will have a single object available to it, the payload. The payload is a dictionary containing the objects that were passed into it. In essence, the payload is the mechanism that allows you to pass the message handler values.

The payload is simply a python dictionary, so extracting values involves specifying the key:

Pseudocode - Payload Values
value1 = payload["MyFirstValue"] # "MyFirstValue" is the key that is associated with a value. We are taking the value associated with MyFirstValue, and assigning it to value1.
value2 = payload["MySecondValue"] # Similarly, we are taking the value associated with MySecondValue and assigning it to value2.

Calling Message Handlers​

Once you have your message handlers created, you can then call them from a script using one of three scripting functions: system.util.sendMessage, system.util.sendRequest, and system.util.sendRequestAsync. These functions allow you to call a message handler in any project, even if the project that the message handler resides on is different from the one you are calling it from. The message handler will then execute in the scope in which it was created, and will use any parameters that you pass in through the payload.

Pseudocode - Calling a Message Handler
project="test"
messageHandler="My Message Handler"
myDict = {'MyFirstValue': "Hello", 'MySecondValue': "World"}
results=system.util.sendMessage(project, messageHandler, myDict)

Gateway Scheduled Scripts​

​

New in 8.1.6
Scheduled scripts are events that execute at fixed times of the day, based off of the Gateway's system time. Configuration for the event is split between two tabs: Settings and Script.

Settings Tab​

The settings tab allows you to give the event a unique name and determine how often it executes. Schedules are driven by cron job scheduling.

The Common Settings dropdown contains several common selections, which can be further modified with the fields and dropdowns under each unit of time.

Each unit of time consists of a field, and corresponding dropdown. The dropdown is filled with suggestions and simple options, but more complex values can be provided in the field on the left. See Crontab Formatting Reference.

Script Tab​

The script tab houses the Python script that will execute when the scheduled event executes.

Troubleshooting Gateway Scripts​

While they are technically project resources, remember that Gateway Event Scripts technically run on the Gateway. Thus the Status section of the Gateway is useful for diagnosing issues with Gateway Event Scripts.