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 Industries 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
Design Like a Pro: Planning Enterprise Solutions
Inductive Automation
 
PPTX
Design Like a Pro: Basics of Building Mobile-Responsive HMIs
Inductive Automation
 
PPTX
Fixing SCADA: How Ignition Saves Time
Inductive Automation
 
PPTX
The New Ignition v7.9 - See, Maintain, and Manage Your Enterprise With Ease
Inductive Automation
 
PPTX
How to Quickly Create Effective Plant-Floor Screens
Inductive Automation
 
PPTX
Fixing SCADA: How Ignition Saves Money
Inductive Automation
 
PPTX
Top 10 Design & Security Tips to Elevate Your SCADA System
Inductive Automation
 
PPTX
Design Like a Pro: Building Better HMI Navigation Schemes
Inductive Automation
 
PPTX
Design Like a Pro - Best Practices For IIoT
Inductive Automation
 
PPTX
Leveraging Operational Data in the Cloud
Inductive Automation
 
PPTX
July webinar slides industry 4.0 view from the front lines
Inductive Automation
 
PPTX
Design Like a Pro: How to Pick the Right System Architecture
Inductive Automation
 
PPTX
10 Steps to Architecting a Sustainable SCADA System
Inductive Automation
 
PPTX
Common Project Mistakes: Visualization, Alarms, and Security
Inductive Automation
 
PPTX
Real Tools for Digital Transformation
Inductive Automation
 
PPTX
Bringing Digital Transformation Into Focus
Inductive Automation
 
PPTX
Fixing SCADA: How Ignition Reduces Frustration
Inductive Automation
 
PPTX
Mobility Meets Manufacturing
Inductive Automation
 
PPTX
6 Simple Steps to Enterprise Digital Transformation
Inductive Automation
 
PPS
ENPAQ Brochure
Vinod Kumar
 
Design Like a Pro: Planning Enterprise Solutions
Inductive Automation
 
Design Like a Pro: Basics of Building Mobile-Responsive HMIs
Inductive Automation
 
Fixing SCADA: How Ignition Saves Time
Inductive Automation
 
The New Ignition v7.9 - See, Maintain, and Manage Your Enterprise With Ease
Inductive Automation
 
How to Quickly Create Effective Plant-Floor Screens
Inductive Automation
 
Fixing SCADA: How Ignition Saves Money
Inductive Automation
 
Top 10 Design & Security Tips to Elevate Your SCADA System
Inductive Automation
 
Design Like a Pro: Building Better HMI Navigation Schemes
Inductive Automation
 
Design Like a Pro - Best Practices For IIoT
Inductive Automation
 
Leveraging Operational Data in the Cloud
Inductive Automation
 
July webinar slides industry 4.0 view from the front lines
Inductive Automation
 
Design Like a Pro: How to Pick the Right System Architecture
Inductive Automation
 
10 Steps to Architecting a Sustainable SCADA System
Inductive Automation
 
Common Project Mistakes: Visualization, Alarms, and Security
Inductive Automation
 
Real Tools for Digital Transformation
Inductive Automation
 
Bringing Digital Transformation Into Focus
Inductive Automation
 
Fixing SCADA: How Ignition Reduces Frustration
Inductive Automation
 
Mobility Meets Manufacturing
Inductive Automation
 
6 Simple Steps to Enterprise Digital Transformation
Inductive Automation
 
ENPAQ Brochure
Vinod Kumar
 

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

PDF
Scripting Recipes for Testers
Adam Goucher
 
PPTX
Javascript Programming according to Industry Standards.pptx
MukundSonaiya1
 
PDF
Software maintenance PyConPL 2016
Cesar Cardenas Desales
 
PDF
Guidelines to clean coding
Janak Porwal
 
PPTX
7a Good Programming Practice.pptx
DylanTilbury1
 
ODP
Path dependent-development (PyCon India)
ncoghlan_dev
 
PDF
Systems se
Franco Bressan
 
PPTX
Austin Python Learners Meetup - Everything you need to know about programming...
Danny Mulligan
 
PDF
Research Software Engineering A Guide To The Open Source Ecosystem Matthias B...
kleksramble
 
ODP
Path Dependent Development (PyCon AU)
ncoghlan_dev
 
PPTX
sat_presentation
Mookambika A
 
PPTX
Programming style guildelines
Rich Nguyen
 
DOCX
Unix commands
saywhatyousee
 
PDF
Crafting high quality code
Allan Mangune
 
PDF
Ohio Valley Oracle Application User Group
Kyle Goodfriend
 
PDF
Linux Commands, C, C++, Java and Python Exercises For Beginners
Manjunath.R -
 
PPTX
Building a Strong Foundation for Python Development
SynapseIndia
 
PDF
Getting It Done
Wez Furlong
 
PPTX
Writing clean scientific software Murphy cleancoding
saber tabatabaee
 
PPTX
The Challenges & Pitfalls of Database Continuous Delivery
Perforce
 
Scripting Recipes for Testers
Adam Goucher
 
Javascript Programming according to Industry Standards.pptx
MukundSonaiya1
 
Software maintenance PyConPL 2016
Cesar Cardenas Desales
 
Guidelines to clean coding
Janak Porwal
 
7a Good Programming Practice.pptx
DylanTilbury1
 
Path dependent-development (PyCon India)
ncoghlan_dev
 
Systems se
Franco Bressan
 
Austin Python Learners Meetup - Everything you need to know about programming...
Danny Mulligan
 
Research Software Engineering A Guide To The Open Source Ecosystem Matthias B...
kleksramble
 
Path Dependent Development (PyCon AU)
ncoghlan_dev
 
sat_presentation
Mookambika A
 
Programming style guildelines
Rich Nguyen
 
Unix commands
saywhatyousee
 
Crafting high quality code
Allan Mangune
 
Ohio Valley Oracle Application User Group
Kyle Goodfriend
 
Linux Commands, C, C++, Java and Python Exercises For Beginners
Manjunath.R -
 
Building a Strong Foundation for Python Development
SynapseIndia
 
Getting It Done
Wez Furlong
 
Writing clean scientific software Murphy cleancoding
saber tabatabaee
 
The Challenges & Pitfalls of Database Continuous Delivery
Perforce
 
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
Integrators Explore the Road Ahead
Inductive Automation
 
PPTX
The Art of Displaying Industrial Data
Inductive Automation
 
PPTX
Common Project Mistakes (And How to Avoid Them)
Inductive Automation
 
PPTX
First Steps to DevOps
Inductive Automation
 
PPTX
Choosing a SCADA System for the IIoT Era
Inductive Automation
 
PPTX
The Evolution of Industrial Visualization
Inductive Automation
 
PPTX
Historic Opportunities: Discover the Power of Ignition's Historian
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
 
PPTX
Ignition Community Live with Carl Gould & Colby Clegg
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
 
Integrators Explore the Road Ahead
Inductive Automation
 
The Art of Displaying Industrial Data
Inductive Automation
 
Common Project Mistakes (And How to Avoid Them)
Inductive Automation
 
First Steps to DevOps
Inductive Automation
 
Choosing a SCADA System for the IIoT Era
Inductive Automation
 
The Evolution of Industrial Visualization
Inductive Automation
 
Historic Opportunities: Discover the Power of Ignition's Historian
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
 
Ignition Community Live with Carl Gould & Colby Clegg
Inductive Automation
 
Ad

Recently uploaded (20)

PDF
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PPTX
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
PDF
Next level data operations using Power Automate magic
Andries den Haan
 
PDF
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PDF
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PDF
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
Next level data operations using Power Automate magic
Andries den Haan
 
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
Why aren't you using FME Flow's CPU Time?
Safe Software
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 

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 Industries 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