Design Like a Pro: Scripting Best Practices

InductiveAutomation 1,513 views 52 slides Nov 28, 2018
Slide 1
Slide 1 of 52
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52

About This Presentation

Scripting experts from Inductive Automation cover general best practices that will help you add flexibility and customization to HMI, SCADA, IIoT, and other industrial applications. Some specific tips about using scripting in the Ignition platform will be included as well.

In this webinar, learn m...


Slide Content

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 Series Available at: inductiveautomation.com/resources

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