design like a pro: scripting best practices

52

Upload: inductive-automation

Post on 23-Jan-2018

283 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Design Like a Pro: Scripting Best Practices
Page 2: Design Like a Pro: Scripting Best Practices

Moderator

Don Pearson

Chief Strategy Officer

Inductive Automation

Page 3: Design Like a Pro: Scripting Best Practices

Today’s Agenda

• Introduction to Ignition

• Things to Remember When Scripting

• Scripting Best Practices

• Q&A

Page 4: Design Like a Pro: Scripting Best Practices

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

Page 5: Design Like a Pro: Scripting Best Practices

Used By Industries Worldwide

Page 6: Design Like a Pro: Scripting Best Practices

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

Page 7: Design Like a Pro: Scripting Best Practices

Presenter

Kevin McClusky

Co-Director of Sales Engineering,

Inductive Automation

Page 8: Design Like a Pro: Scripting Best Practices

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%.

Page 9: Design Like a Pro: Scripting Best Practices

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

Page 10: Design Like a Pro: Scripting Best Practices

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.

Page 11: Design Like a Pro: Scripting Best Practices

When to Use Scripting: Examples

• Exporting data through scripting that wasn’t built-in to binding or

component

• Custom calculations

Page 12: Design Like a Pro: Scripting Best Practices

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

Page 13: Design Like a Pro: Scripting Best Practices

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.

Page 14: Design Like a Pro: Scripting Best Practices

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

Page 15: Design Like a Pro: Scripting Best Practices

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.

Page 16: Design Like a Pro: Scripting Best Practices

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

Page 17: Design Like a Pro: Scripting Best Practices

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

Page 18: Design Like a Pro: Scripting Best Practices

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)

Page 19: Design Like a Pro: Scripting Best Practices

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

Page 20: Design Like a Pro: Scripting Best Practices

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

Page 21: Design Like a Pro: Scripting Best Practices

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'

Page 22: Design Like a Pro: Scripting Best Practices

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 /

Page 23: Design Like a Pro: Scripting Best Practices

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

Page 24: Design Like a Pro: Scripting Best Practices

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])

Page 25: Design Like a Pro: Scripting Best Practices

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

Page 26: Design Like a Pro: Scripting Best Practices

Best Practice: Define Scripting Functions

Benefits:

• Keeps code organized

• Easier to find and troubleshoot

• Keeps windows and tags cleaner

• Ability to re-use

Page 27: Design Like a Pro: Scripting Best Practices

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)

Page 28: Design Like a Pro: Scripting Best Practices

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

Page 29: Design Like a Pro: Scripting Best Practices

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")

Page 30: Design Like a Pro: Scripting Best Practices

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

Page 31: Design Like a Pro: Scripting Best Practices

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)

Page 32: Design Like a Pro: Scripting Best Practices

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)

Page 33: Design Like a Pro: Scripting Best Practices

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

Page 34: Design Like a Pro: Scripting Best Practices

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.

Page 35: Design Like a Pro: Scripting Best Practices

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)

Page 36: Design Like a Pro: Scripting Best Practices

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)

Page 37: Design Like a Pro: Scripting Best Practices

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)

Page 38: Design Like a Pro: Scripting Best Practices

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

Page 39: Design Like a Pro: Scripting Best Practices

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.

Page 40: Design Like a Pro: Scripting Best Practices

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.

Page 41: Design Like a Pro: Scripting Best Practices

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

Page 42: Design Like a Pro: Scripting Best Practices

Best Practice: Understand Threading

UI thread vs separate thread (asynchronous)

• UI can hang

• Use progress bars instead (asynchronous)

• Callbacks to the UI thread invokeLater

Page 43: Design Like a Pro: Scripting Best Practices

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).

Page 44: Design Like a Pro: Scripting Best Practices

Other Tips: Scripting Timesavers

• Software package functions vs. libraries

• Language functions vs. custom code (example: the Python

CSV library)

Page 45: Design Like a Pro: Scripting Best Practices

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

Page 46: Design Like a Pro: Scripting Best Practices

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

Page 47: Design Like a Pro: Scripting Best Practices

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

Page 48: Design Like a Pro: Scripting Best Practices
Page 49: Design Like a Pro: Scripting Best Practices

Design Like a Pro Series

Available at: inductiveautomation.com/resources

Page 50: Design Like a Pro: Scripting Best Practices
Page 51: 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

Page 52: Design Like a Pro: Scripting Best Practices