SlideShare a Scribd company logo
Design Like a Pro: Scripting Best Practices
Moderator
Don Pearson
Chief Strategy Officer
Inductive Automation
Today’s Agenda
• Introduction to Ignition
• Things to Remember When Scripting
• Scripting Best Practices
• Q&A
About Inductive Automation
• Founded in 2003
• HMI, SCADA, MES, and IIoT software
• Installed in 100+ countries
• Over 1,500 integrators
• Used by 44% of Fortune 100 companies
Learn more at: inductiveautomation.com/about
Used by Major Companies Worldwide
Ignition: Industrial Application Platform
One Universal Platform for SCADA, MES & IIoT:
• Unlimited licensing model
• Cross-platform compatibility
• Based on IT-standard technologies
• Scalable server-client architecture
• Web-managed
• Web-launched on desktop or mobile
• Modular configurability
• Rapid development and deployment
Presenter
Kevin McClusky
Co-Director of Sales Engineering,
Inductive Automation
Why Scripting Exists
• It’s possible to create complete, powerful projects with HMI/SCADA
software without writing code
• However, many designers find that to complete all project
requirements, they need to use scripting.
• Typically, 80-90% of required functionality can be accomplished
through native features. Scripting exists to fill the other 10-20%.
Why Use Scripting?
• More flexibility
• Extend the logic
• Do more with the product than what’s built into it
• But it has to be used in the right way
When to Use Scripting and When Not To
• Use scripting when you simply can’t accomplish a requirement with
built-in tools.
• Don’t just use scripting for scripting’s sake.
• You may want to ask other users in forums or call tech support.
• Scripting can make it more difficult for another engineer to
understand, so make sure it is applicable and comment your code.
When to Use Scripting: Examples
• Exporting data through scripting that wasn’t built-in to binding or
component
• Custom calculations
When Not to Use Scripting: Examples
• Dynamic SQL query in binding vs. scripting
• Logging data (contextually) from a tag change script when you can
use transaction groups
Which Scripting Language?
Best programming languages to use:
• Use the scripting language that comes with your HMI, SCADA, IIoT
or MES platform.
• Although scripting outside the platform may be possible, it’s best to
use native scripting tools because it eases maintainability and has
the fullest possible integration with the platform.
Understanding Where and When Your Script is Running
• Extremely important to know exactly where and when your code is
running
• Requires knowledge of the software platform you are using
• Avoid unnecessary code from running and performing duplicate
work
Understanding Where and When Your Script is Running
• Where scripts run in Ignition:
• Gateway (server)
• Client
• When scripts run in Ignition:
• Timer
• Tag change
• User in client (button press)
• SFC
• Alarm pipeline
• Etc.
Organization and Standards
• Develop a code standard and be consistent
• Organize well and make sure folders, functions & variables are
named appropriately
• Avoid language shortcuts
• Indent style (tabs or spaces)
• Programming style
• Comment conventions
• Naming conventions
Organization and Standards
• Develop a code standard and be consistent
• Organize well and make sure folders, functions & variables are
named appropriately
• Avoid language shortcuts
• Indent style (tabs or spaces)
• Programming style
• Comment conventions
• Naming conventions
Organization and Standards
• Avoid language shortcuts (example)
1. Example with shortcut:
numbers = [1,2,3,4,5,6]
even = [number for number in numbers if number%2 == 0]
2. Example without:
numbers = [1,2,3,4,5,6]
even = []
for number in numbers:
if number%2 == 0:
even.append(number)
Organization and Standards
• Develop a code standard and be consistent
• Organize well and make sure folders, functions & variables are
named appropriately
• Avoid language shortcuts
• Indent style (tabs or spaces)
• Programming style
• Comment conventions
• Naming conventions
Commenting Code
• A comment is a programmer-readable explanation or annotation in
the source code.
• Added to make the source code easier for humans to understand,
generally ignored by compilers and interpreters.
• You need to do it!
• Helps the next developers and makes code easier to understand
and troubleshoot
Commenting Code (Examples)
• Individual Lines:
# this is a comment
print 'Hello world' # this is also a valid comment
• Blocks of Lines:
'''
This is a lot of text
that you want to show as multiple lines of
comments
Script written by Professor X.
Jan 5, 1990
'''
print 'Hello world'
Commenting Code (Examples)
• Use the Ctrl-/ keyboard shortcut to comment several lines of code at
once. Just highlight one or more lines of code and hold the Ctrl key
and press /
Organization and Standards
• Develop a code standard and be consistent
• Organize well and make sure folders, functions & variables are
named appropriately
• Avoid language shortcuts
• Indent style (tabs or spaces)
• Programming style
• Comment conventions
• Naming conventions
Best Practice: Variables
• Use naming conventions
• Define variables at the top of the script
Example:
name = event.source.parent.getComponent('Name').text
desc = event.source.parent.getComponent('Description').text
building = event.source.parent.getComponent('Building').selectedValue
id = system.db.runPrepUpdate("INSERT INTO machines (machine_name,
description) VALUES (?, ?)", [name, desc])
Best Practice: Define Scripting Functions
• Functions are code that can be called repeatedly from other places
• Can have parameters passed into them, and may return a resulting
value
• Types of functions:
1. Built-in to the language, like len()
2. Part of software package, like system.gui.getMessageBox() for
Ignition
3. Provided by language standard library, like math.sqrt()
4. User-defined functions
Best Practice: Define Scripting Functions
Benefits:
• Keeps code organized
• Easier to find and troubleshoot
• Keeps windows and tags cleaner
• Ability to re-use
Best Practice: Define Scripting Functions
• Default values for arguments (keyword arguments)
Argument specified by position:
print checkBounds(150, 0, 250)
Argument specified by keyword:
print checkBounds(150, range=250)
Best Practice: Define Scripting Functions
• Variable arguments (*args and **kwargs)
Example:
def add(firstValue, *args):
finalValue = firstValue
for value in args:
finalValue = finalValue + value
return finalValue
def checkBounds(value, offset=0, range=200):
if value + offset > range:
return true
else:
return false
Best Practice: Exception Handling
• Exceptions are errors detected during execution
• Not unconditionally fatal
• Most exceptions aren't handled by programs
• You can write programs that handle exceptions
Example:
try:
window = system.gui.getWindow('Overview')
system.gui.closeWindow(window)
except:
system.gui.warningBox("The Overview window isn't open")
Best Practice: Error Console
• One of the most important troubleshooting tools of any package
• Shows a wealth of information about the running state of the
system, system errors, and errors from custom scripts
• Depending on where your script is running, there may be a different
console
• Clear up any known errors
Best Practice: Error Console
Tips:
• Know how long your script takes (Log start, end, and duration)
• Use loggers effectively to troubleshoot your code (debug vs. info vs.
warn vs. error)
Best Practice: Loops
• When to use loops:
- Dealing with multiple items
- Iterating over finite list
• When not to use loops:
- To make your code wait (use a timing mechanism
instead)
Best Practice: Loops
• Stay away from infinite loops (While True or long for loops)
• Use breaks effectively (Don’t do unnecessary work)
Example:
found = False
for row in result:
if row[“name”] == “MyName”:
found = True
break
Best Practice: Timers
• Timers run at a set interval 24x7
• Understanding fixed rate vs. fixed delay:
◦ Fixed delay timer script (default) waits for given delay between
each script invocation. The script's rate will be the delay plus the
time it takes to execute the script. This is the safest option.
◦ Fixed rate scripts attempt to run the script at a fixed rate relative
to the first execution. If script takes too long, or there is too much
background process, this may not be possible.
Best Practice: Timers
• Avoid scripts that run quickly that fill up queues
(such as tag writes)
• Provide ability to enable/disable through a setting
(such as a memory tag)
Best Practice: Tag Change
• Tag change scripts run when the value or quality of a tag
changes.
• Make sure to check the quality of the tag. It is possible the
value didn’t change but the quality did. Don’t run code at
the wrong times.
• You may want to check the value, and whether the value is
different from the previous value.
• Decide whether you want the script to run initially (when
the server reboots)
Best Practice: Avoid Race Conditions
• Race condition or race hazard: the behavior of a system
where the output is dependent on the sequence or timing
of other uncontrollable events
• Expect one script to be completed before running the other
• Becomes a bug when events do not happen in the order
the programmer intended
• Typically due to asynchronous problems (tags, properties)
Best Practice: Avoid Race Conditions
Examples:
• A propertyChange script that refers to two properties but is
only filtered on one. The second property may not have
updated. Instead try to put in a single property, if possible,
or run the code multiple times, looking at all props.
• Writing to a tag and reading the tag on the next line
Best Practice: Understand Threading
• A lot of languages, such as Java, are multi-threaded
• Two or more parts that can run concurrently, and each part
can handle a different task at the same time.
Best Practice: Understand Threading
• Are scripts running in a shared or dedicated thread?
• Scripts running in a shared thread will all execute in the
same thread. This is usually desirable, to prevent creating
unnecessary threads. However, scripts that take a long
time to run will block other scripts on the shared thread.
Best Practice: Understand Threading
• Rule of thumb: quick-running tasks should run in the
shared thread, and long-running tasks should get their own
thread.
• Understand what else could be affected if running in the
same thread
Best Practice: Understand Threading
UI thread vs separate thread (asynchronous)
• UI can hang
• Use progress bars instead (asynchronous)
• Callbacks to the UI thread invokeLater
Other Tips: Restoring Backups on Other Machines
• Scripts could be running in two places
• Make sure to restore disabled or have a code check if it is
a certain machine (by IP or hostname).
Other Tips: Scripting Timesavers
• Software package functions vs. libraries
• Language functions vs. custom code (example: the Python
CSV library)
Recap - Things to Remember When Scripting:
• Understand the basic purpose of scripting
• Know when to use scripting and when not to
• Understand where and when your script is running
• Use organization and standards
• Include comments in your code
Recap of Scripting Best Practices:
• Use variable naming conventions
• Define common functions
• Use exception handling
• Use the error console
• Avoid infinite loops
• Use appropriate threads with timers
• Plan tag change scripts
• Avoid race conditions
• Understand threading
One Last Tip …
Looking for some scripting help? Here are a few good resources:
• User forum at: www.inductiveautomation.com/forum
• Python language tutorial: www.python-course.eu/course.php
Design Like a Pro: Scripting Best Practices
Design Like a Pro Series
Available at: inductiveautomation.com/resources
Design Like a Pro: Scripting Best Practices
Questions & Comments
Jim Meisler x227
Vannessa Garcia x231
Vivian Mudge x253
Account Executives
Myron Hoertling x224
Shane Miller x218
Ramin Rofagha x251
Maria Chinappi x264
Dan Domerofski x273
Lester Ares x214
800-266-7798 x247
Melanie Moniz
Director of Sales:
Jeff Osterback x207
Design Like a Pro: Scripting Best Practices

More Related Content

What's hot (20)

PPTX
Non-functional Testing (NFT) Overview
Assaf Halperin
 
PPTX
Introduction to Automation Testing
Archana Krushnan
 
PDF
Cluster-as-code. The Many Ways towards Kubernetes
QAware GmbH
 
PPTX
Static Testing
Dharita Chokshi
 
PPTX
Coding standards and guidelines
brijraj_singh
 
PPT
Automation testing
Biswajit Pratihari
 
PPT
Testing Frameworks
Moataz Nabil
 
PPTX
Deploying Azure DevOps using Terraform
Adin Ermie
 
PPTX
Top 10 Design & Security Tips to Elevate Your SCADA System
Inductive Automation
 
PPTX
Power shell basics day 4
Ashish Raj
 
PDF
클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSA
VMware Tanzu Korea
 
PPTX
Jmeter
Sun Technlogies
 
PPTX
Software Testing Introduction
ArunKumar5524
 
PPTX
Confidential Computing overview
Mark Argent
 
PDF
Introducing Lenovo XClarity: Simplified Hardware Resource Management
Lenovo Data Center
 
PDF
Enabling SSL Elasticsearch on server
Omkar Rane
 
PDF
Ansible Automation Platform.pdf
VuHoangAnh14
 
PDF
Infographic: Importance of Performance Testing
KiwiQA
 
PPTX
Kubernetes PPT.pptx
ssuser0cc9131
 
PPTX
Amazon services ec2
Ismaeel Enjreny
 
Non-functional Testing (NFT) Overview
Assaf Halperin
 
Introduction to Automation Testing
Archana Krushnan
 
Cluster-as-code. The Many Ways towards Kubernetes
QAware GmbH
 
Static Testing
Dharita Chokshi
 
Coding standards and guidelines
brijraj_singh
 
Automation testing
Biswajit Pratihari
 
Testing Frameworks
Moataz Nabil
 
Deploying Azure DevOps using Terraform
Adin Ermie
 
Top 10 Design & Security Tips to Elevate Your SCADA System
Inductive Automation
 
Power shell basics day 4
Ashish Raj
 
클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSA
VMware Tanzu Korea
 
Software Testing Introduction
ArunKumar5524
 
Confidential Computing overview
Mark Argent
 
Introducing Lenovo XClarity: Simplified Hardware Resource Management
Lenovo Data Center
 
Enabling SSL Elasticsearch on server
Omkar Rane
 
Ansible Automation Platform.pdf
VuHoangAnh14
 
Infographic: Importance of Performance Testing
KiwiQA
 
Kubernetes PPT.pptx
ssuser0cc9131
 
Amazon services ec2
Ismaeel Enjreny
 

Similar to Design Like a Pro: Scripting Best Practices (20)

PPTX
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
PDF
Scripting Recipes for Testers
Adam Goucher
 
PPTX
Javascript Programming according to Industry Standards.pptx
MukundSonaiya1
 
PDF
Guidelines to clean coding
Janak Porwal
 
PDF
Software maintenance PyConPL 2016
Cesar Cardenas Desales
 
ODP
Path dependent-development (PyCon India)
ncoghlan_dev
 
PDF
Systems se
Franco Bressan
 
PPTX
7a Good Programming Practice.pptx
DylanTilbury1
 
PPTX
Austin Python Learners Meetup - Everything you need to know about programming...
Danny Mulligan
 
DOCX
Unix commands
saywhatyousee
 
PDF
Ohio Valley Oracle Application User Group
Kyle Goodfriend
 
PPTX
The Challenges & Pitfalls of Database Continuous Delivery
Perforce
 
PDF
Crafting high quality code
Allan Mangune
 
PPTX
sat_presentation
Mookambika A
 
PPTX
Programming style guildelines
Rich Nguyen
 
PPT
System administration with automation
Shivam Srivastava
 
PDF
Research Software Engineering A Guide To The Open Source Ecosystem Matthias B...
kleksramble
 
PDF
Performance tesing coding standards & best practice guidelines v1
Argos
 
ODP
Path Dependent Development (PyCon AU)
ncoghlan_dev
 
PDF
Getting It Done
Wez Furlong
 
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
Scripting Recipes for Testers
Adam Goucher
 
Javascript Programming according to Industry Standards.pptx
MukundSonaiya1
 
Guidelines to clean coding
Janak Porwal
 
Software maintenance PyConPL 2016
Cesar Cardenas Desales
 
Path dependent-development (PyCon India)
ncoghlan_dev
 
Systems se
Franco Bressan
 
7a Good Programming Practice.pptx
DylanTilbury1
 
Austin Python Learners Meetup - Everything you need to know about programming...
Danny Mulligan
 
Unix commands
saywhatyousee
 
Ohio Valley Oracle Application User Group
Kyle Goodfriend
 
The Challenges & Pitfalls of Database Continuous Delivery
Perforce
 
Crafting high quality code
Allan Mangune
 
sat_presentation
Mookambika A
 
Programming style guildelines
Rich Nguyen
 
System administration with automation
Shivam Srivastava
 
Research Software Engineering A Guide To The Open Source Ecosystem Matthias B...
kleksramble
 
Performance tesing coding standards & best practice guidelines v1
Argos
 
Path Dependent Development (PyCon AU)
ncoghlan_dev
 
Getting It Done
Wez Furlong
 
Ad

More from Inductive Automation (20)

PPTX
De-Risk Your Digital Transformation — And Reduce Time, Cost & Complexity
Inductive Automation
 
PPTX
Overcoming Digital Transformation Pain Points
Inductive Automation
 
PPTX
How Ignition Eases SCADA Pain Points
Inductive Automation
 
PPTX
New Ignition Features In Action
Inductive Automation
 
PPTX
Solving Data Problems to Accelerate Digital Transformation.pptx
Inductive Automation
 
PPTX
Security Best Practices for Your Ignition System
Inductive Automation
 
PPTX
Turn Any Panel PC Into an Ignition HMI
Inductive Automation
 
PPTX
5 Mobile-Responsive Layout Strategies
Inductive Automation
 
PPTX
Bringing Digital Transformation Into Focus
Inductive Automation
 
PPTX
Integrators Explore the Road Ahead
Inductive Automation
 
PPTX
The Art of Displaying Industrial Data
Inductive Automation
 
PPTX
Common Project Mistakes: Visualization, Alarms, and Security
Inductive Automation
 
PPTX
First Steps to DevOps
Inductive Automation
 
PPTX
Choosing a SCADA System for the IIoT Era
Inductive Automation
 
PPTX
Design Like a Pro: How to Pick the Right System Architecture
Inductive Automation
 
PPTX
The Evolution of Industrial Visualization
Inductive Automation
 
PPTX
Unlocking Greater Efficiency: The Why and How of OEE Implementation
Inductive Automation
 
PPTX
Leveraging Ignition Quick Start to Rapidly Build Real Projects
Inductive Automation
 
PPTX
Design Like a Pro: Developing & Deploying Perspective Applications as HMIs
Inductive Automation
 
PPTX
Integrator Discussion: Leading Through Innovation During COVID-19 and Beyond
Inductive Automation
 
De-Risk Your Digital Transformation — And Reduce Time, Cost & Complexity
Inductive Automation
 
Overcoming Digital Transformation Pain Points
Inductive Automation
 
How Ignition Eases SCADA Pain Points
Inductive Automation
 
New Ignition Features In Action
Inductive Automation
 
Solving Data Problems to Accelerate Digital Transformation.pptx
Inductive Automation
 
Security Best Practices for Your Ignition System
Inductive Automation
 
Turn Any Panel PC Into an Ignition HMI
Inductive Automation
 
5 Mobile-Responsive Layout Strategies
Inductive Automation
 
Bringing Digital Transformation Into Focus
Inductive Automation
 
Integrators Explore the Road Ahead
Inductive Automation
 
The Art of Displaying Industrial Data
Inductive Automation
 
Common Project Mistakes: Visualization, Alarms, and Security
Inductive Automation
 
First Steps to DevOps
Inductive Automation
 
Choosing a SCADA System for the IIoT Era
Inductive Automation
 
Design Like a Pro: How to Pick the Right System Architecture
Inductive Automation
 
The Evolution of Industrial Visualization
Inductive Automation
 
Unlocking Greater Efficiency: The Why and How of OEE Implementation
Inductive Automation
 
Leveraging Ignition Quick Start to Rapidly Build Real Projects
Inductive Automation
 
Design Like a Pro: Developing & Deploying Perspective Applications as HMIs
Inductive Automation
 
Integrator Discussion: Leading Through Innovation During COVID-19 and Beyond
Inductive Automation
 
Ad

Recently uploaded (20)

PPTX
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
PPTX
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
PDF
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
PDF
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
PPTX
NeuroStrata: Harnessing Neuro-Symbolic Paradigms for Improved Testability and...
Ivan Ruchkin
 
PDF
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
PDF
Rewards and Recognition (2).pdf
ethan Talor
 
PPTX
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
PDF
Difference Between Kubernetes and Docker .pdf
Kindlebit Solutions
 
PPTX
For my supp to finally picking supp that work
necas19388
 
PDF
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
 
PPTX
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
 
PDF
LPS25 - Operationalizing MLOps in GEP - Terradue.pdf
terradue
 
PDF
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 
PDF
Cloud computing Lec 02 - virtualization.pdf
asokawennawatte
 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
PDF
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
PPTX
CONCEPT OF PROGRAMMING in language .pptx
tamim41
 
PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
PPTX
computer forensics encase emager app exp6 1.pptx
ssuser343e92
 
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
NeuroStrata: Harnessing Neuro-Symbolic Paradigms for Improved Testability and...
Ivan Ruchkin
 
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
Rewards and Recognition (2).pdf
ethan Talor
 
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
Difference Between Kubernetes and Docker .pdf
Kindlebit Solutions
 
For my supp to finally picking supp that work
necas19388
 
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
 
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
 
LPS25 - Operationalizing MLOps in GEP - Terradue.pdf
terradue
 
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 
Cloud computing Lec 02 - virtualization.pdf
asokawennawatte
 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
CONCEPT OF PROGRAMMING in language .pptx
tamim41
 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
computer forensics encase emager app exp6 1.pptx
ssuser343e92
 

Design Like a Pro: Scripting Best Practices

  • 2. Moderator Don Pearson Chief Strategy Officer Inductive Automation
  • 3. Today’s Agenda • Introduction to Ignition • Things to Remember When Scripting • Scripting Best Practices • Q&A
  • 4. About Inductive Automation • Founded in 2003 • HMI, SCADA, MES, and IIoT software • Installed in 100+ countries • Over 1,500 integrators • Used by 44% of Fortune 100 companies Learn more at: inductiveautomation.com/about
  • 5. Used by Major Companies Worldwide
  • 6. Ignition: Industrial Application Platform One Universal Platform for SCADA, MES & IIoT: • Unlimited licensing model • Cross-platform compatibility • Based on IT-standard technologies • Scalable server-client architecture • Web-managed • Web-launched on desktop or mobile • Modular configurability • Rapid development and deployment
  • 7. Presenter Kevin McClusky Co-Director of Sales Engineering, Inductive Automation
  • 8. Why Scripting Exists • It’s possible to create complete, powerful projects with HMI/SCADA software without writing code • However, many designers find that to complete all project requirements, they need to use scripting. • Typically, 80-90% of required functionality can be accomplished through native features. Scripting exists to fill the other 10-20%.
  • 9. Why Use Scripting? • More flexibility • Extend the logic • Do more with the product than what’s built into it • But it has to be used in the right way
  • 10. When to Use Scripting and When Not To • Use scripting when you simply can’t accomplish a requirement with built-in tools. • Don’t just use scripting for scripting’s sake. • You may want to ask other users in forums or call tech support. • Scripting can make it more difficult for another engineer to understand, so make sure it is applicable and comment your code.
  • 11. When to Use Scripting: Examples • Exporting data through scripting that wasn’t built-in to binding or component • Custom calculations
  • 12. When Not to Use Scripting: Examples • Dynamic SQL query in binding vs. scripting • Logging data (contextually) from a tag change script when you can use transaction groups
  • 13. Which Scripting Language? Best programming languages to use: • Use the scripting language that comes with your HMI, SCADA, IIoT or MES platform. • Although scripting outside the platform may be possible, it’s best to use native scripting tools because it eases maintainability and has the fullest possible integration with the platform.
  • 14. Understanding Where and When Your Script is Running • Extremely important to know exactly where and when your code is running • Requires knowledge of the software platform you are using • Avoid unnecessary code from running and performing duplicate work
  • 15. Understanding Where and When Your Script is Running • Where scripts run in Ignition: • Gateway (server) • Client • When scripts run in Ignition: • Timer • Tag change • User in client (button press) • SFC • Alarm pipeline • Etc.
  • 16. Organization and Standards • Develop a code standard and be consistent • Organize well and make sure folders, functions & variables are named appropriately • Avoid language shortcuts • Indent style (tabs or spaces) • Programming style • Comment conventions • Naming conventions
  • 17. Organization and Standards • Develop a code standard and be consistent • Organize well and make sure folders, functions & variables are named appropriately • Avoid language shortcuts • Indent style (tabs or spaces) • Programming style • Comment conventions • Naming conventions
  • 18. Organization and Standards • Avoid language shortcuts (example) 1. Example with shortcut: numbers = [1,2,3,4,5,6] even = [number for number in numbers if number%2 == 0] 2. Example without: numbers = [1,2,3,4,5,6] even = [] for number in numbers: if number%2 == 0: even.append(number)
  • 19. Organization and Standards • Develop a code standard and be consistent • Organize well and make sure folders, functions & variables are named appropriately • Avoid language shortcuts • Indent style (tabs or spaces) • Programming style • Comment conventions • Naming conventions
  • 20. Commenting Code • A comment is a programmer-readable explanation or annotation in the source code. • Added to make the source code easier for humans to understand, generally ignored by compilers and interpreters. • You need to do it! • Helps the next developers and makes code easier to understand and troubleshoot
  • 21. Commenting Code (Examples) • Individual Lines: # this is a comment print 'Hello world' # this is also a valid comment • Blocks of Lines: ''' This is a lot of text that you want to show as multiple lines of comments Script written by Professor X. Jan 5, 1990 ''' print 'Hello world'
  • 22. Commenting Code (Examples) • Use the Ctrl-/ keyboard shortcut to comment several lines of code at once. Just highlight one or more lines of code and hold the Ctrl key and press /
  • 23. Organization and Standards • Develop a code standard and be consistent • Organize well and make sure folders, functions & variables are named appropriately • Avoid language shortcuts • Indent style (tabs or spaces) • Programming style • Comment conventions • Naming conventions
  • 24. Best Practice: Variables • Use naming conventions • Define variables at the top of the script Example: name = event.source.parent.getComponent('Name').text desc = event.source.parent.getComponent('Description').text building = event.source.parent.getComponent('Building').selectedValue id = system.db.runPrepUpdate("INSERT INTO machines (machine_name, description) VALUES (?, ?)", [name, desc])
  • 25. Best Practice: Define Scripting Functions • Functions are code that can be called repeatedly from other places • Can have parameters passed into them, and may return a resulting value • Types of functions: 1. Built-in to the language, like len() 2. Part of software package, like system.gui.getMessageBox() for Ignition 3. Provided by language standard library, like math.sqrt() 4. User-defined functions
  • 26. Best Practice: Define Scripting Functions Benefits: • Keeps code organized • Easier to find and troubleshoot • Keeps windows and tags cleaner • Ability to re-use
  • 27. Best Practice: Define Scripting Functions • Default values for arguments (keyword arguments) Argument specified by position: print checkBounds(150, 0, 250) Argument specified by keyword: print checkBounds(150, range=250)
  • 28. Best Practice: Define Scripting Functions • Variable arguments (*args and **kwargs) Example: def add(firstValue, *args): finalValue = firstValue for value in args: finalValue = finalValue + value return finalValue def checkBounds(value, offset=0, range=200): if value + offset > range: return true else: return false
  • 29. Best Practice: Exception Handling • Exceptions are errors detected during execution • Not unconditionally fatal • Most exceptions aren't handled by programs • You can write programs that handle exceptions Example: try: window = system.gui.getWindow('Overview') system.gui.closeWindow(window) except: system.gui.warningBox("The Overview window isn't open")
  • 30. Best Practice: Error Console • One of the most important troubleshooting tools of any package • Shows a wealth of information about the running state of the system, system errors, and errors from custom scripts • Depending on where your script is running, there may be a different console • Clear up any known errors
  • 31. Best Practice: Error Console Tips: • Know how long your script takes (Log start, end, and duration) • Use loggers effectively to troubleshoot your code (debug vs. info vs. warn vs. error)
  • 32. Best Practice: Loops • When to use loops: - Dealing with multiple items - Iterating over finite list • When not to use loops: - To make your code wait (use a timing mechanism instead)
  • 33. Best Practice: Loops • Stay away from infinite loops (While True or long for loops) • Use breaks effectively (Don’t do unnecessary work) Example: found = False for row in result: if row[“name”] == “MyName”: found = True break
  • 34. Best Practice: Timers • Timers run at a set interval 24x7 • Understanding fixed rate vs. fixed delay: ◦ Fixed delay timer script (default) waits for given delay between each script invocation. The script's rate will be the delay plus the time it takes to execute the script. This is the safest option. ◦ Fixed rate scripts attempt to run the script at a fixed rate relative to the first execution. If script takes too long, or there is too much background process, this may not be possible.
  • 35. Best Practice: Timers • Avoid scripts that run quickly that fill up queues (such as tag writes) • Provide ability to enable/disable through a setting (such as a memory tag)
  • 36. Best Practice: Tag Change • Tag change scripts run when the value or quality of a tag changes. • Make sure to check the quality of the tag. It is possible the value didn’t change but the quality did. Don’t run code at the wrong times. • You may want to check the value, and whether the value is different from the previous value. • Decide whether you want the script to run initially (when the server reboots)
  • 37. Best Practice: Avoid Race Conditions • Race condition or race hazard: the behavior of a system where the output is dependent on the sequence or timing of other uncontrollable events • Expect one script to be completed before running the other • Becomes a bug when events do not happen in the order the programmer intended • Typically due to asynchronous problems (tags, properties)
  • 38. Best Practice: Avoid Race Conditions Examples: • A propertyChange script that refers to two properties but is only filtered on one. The second property may not have updated. Instead try to put in a single property, if possible, or run the code multiple times, looking at all props. • Writing to a tag and reading the tag on the next line
  • 39. Best Practice: Understand Threading • A lot of languages, such as Java, are multi-threaded • Two or more parts that can run concurrently, and each part can handle a different task at the same time.
  • 40. Best Practice: Understand Threading • Are scripts running in a shared or dedicated thread? • Scripts running in a shared thread will all execute in the same thread. This is usually desirable, to prevent creating unnecessary threads. However, scripts that take a long time to run will block other scripts on the shared thread.
  • 41. Best Practice: Understand Threading • Rule of thumb: quick-running tasks should run in the shared thread, and long-running tasks should get their own thread. • Understand what else could be affected if running in the same thread
  • 42. Best Practice: Understand Threading UI thread vs separate thread (asynchronous) • UI can hang • Use progress bars instead (asynchronous) • Callbacks to the UI thread invokeLater
  • 43. Other Tips: Restoring Backups on Other Machines • Scripts could be running in two places • Make sure to restore disabled or have a code check if it is a certain machine (by IP or hostname).
  • 44. Other Tips: Scripting Timesavers • Software package functions vs. libraries • Language functions vs. custom code (example: the Python CSV library)
  • 45. Recap - Things to Remember When Scripting: • Understand the basic purpose of scripting • Know when to use scripting and when not to • Understand where and when your script is running • Use organization and standards • Include comments in your code
  • 46. Recap of Scripting Best Practices: • Use variable naming conventions • Define common functions • Use exception handling • Use the error console • Avoid infinite loops • Use appropriate threads with timers • Plan tag change scripts • Avoid race conditions • Understand threading
  • 47. One Last Tip … Looking for some scripting help? Here are a few good resources: • User forum at: www.inductiveautomation.com/forum • Python language tutorial: www.python-course.eu/course.php
  • 49. Design Like a Pro Series Available at: inductiveautomation.com/resources
  • 51. Questions & Comments Jim Meisler x227 Vannessa Garcia x231 Vivian Mudge x253 Account Executives Myron Hoertling x224 Shane Miller x218 Ramin Rofagha x251 Maria Chinappi x264 Dan Domerofski x273 Lester Ares x214 800-266-7798 x247 Melanie Moniz Director of Sales: Jeff Osterback x207