Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Objectives

At the end of this section, participants will be able to:


Scripting in In-Sight
• Outline how values are passed from a spreadsheet to a
Section 8
JavaScript program
• List the In-Sight models and software versions that support
scripting
• List three reasons to use scripting
• Explain the benefits of using the JavaScript Libraries and
JavaScript Template
• Outline the four sample snippets that use scripting
• Create a JavaScript program to compute the average area of a
grid of squares

NOTE: This section is not a guide to


programming in the JavaScript language

Section 8 | Page 2

This section covers Scripting in In-Sight. Scripting allows you to write programs in the JavaScript At the end of this section, participants will be able to:
language and then run those programs from the spreadsheet. Scripting is available starting in In-Sight
software version 5.1, on those camera models that support 5.1. It is also available in the In-Sight - Outline how values are passed from a spreadsheet to a JavaScript program
Explorer 5.1 emulator. - List the In-Sight models and software versions that support scripting
- List three reasons to use scripting
The emphasis of this section is on how to interface with JavaScript from the spreadsheet, i.e., how to - Explain the benefits of using the JavaScript Libraries and JavaScript Template
pass spreadsheet data to a JavaScript program and how to retrieve results from that program into the - Outline the four sample snippets that use scripting
spreadsheet. Although some JavaScript code is shown, and examined in the lab, this section does not - Create a JavaScript program to compute the average area of a grid of squares
explain details of the JavaScript language. A list of JavaScript resources is provided at the end of the
section. This section does not go into details of the JavaScript language

Section 8 | Slide 1 Section 8 | Slide 2


Scripting: Components Passing Data Between Spreadsheet and Script

Spreadsheet functions: • How to send data from spreadsheet to JavaScript program


• Script: creates and executes a JavaScript – Configure Script to refer to the data cell(s)
program
– Cells referenced can contain values or vision tools Script(A9,B12,B13,G12)
– In Palette:

D3: Script(A4:A15)
Get(D3,"avg")
• How to retrieve results from JavaScript program into spreadsheet
Get(D3,”stddev”) – Single result can be returned into the Script cell
Get(D3,“min”)
• Gets: retrieve results from a Script into Get(D3,”max”)
spreadsheet cells Script
– In Palette under Vision Data Access

– For multiple results, use one Get for each result, each referencing the Script
cell Get(D3,"avg")
Get(D3,"stddev")
Get(D3,"min")

Section 8 | Page 3 Section 8 | Page 4

To implement scripting in the spreadsheet, use the In-Sight Script function. Placing a Script function in a To send data from a spreadsheet to a JavaScript program, make references to the relevant cell(s) in the
cell launches the JavaScript editor, displaying a JavaScript template you can modify to carry out the Script function.
functionality you want.
In terms of returning results, there are two ways to set up scripting. If there is only one result, it can be
The other spreadsheet function is Get, which returns one result from the JavaScript program into the returned directly into the cell containing the Script function. In the example above, a Script is
spreadsheet. If there were four results, you would place four Gets into four cells. determining if a date is in or out of range. The Script cell ends up with a 0 if the date is out of range, or a
1 if the date is in range.
This section uses the following terminology and notation:
The other way to return values from a JavaScript program is by placing one or more Get functions into the
- Script (in bold) refers to a Script function in the spreadsheet spreadsheet. Each Get has two parameters: a reference to the Script cell, and the name of the result
- Get (in bold) refers to a Get function in the spreadsheet variable as defined in the JavaScript program. In the example above, three results are obtained from the
- “JavaScript program” refers to code written in the JavaScript language that is invoked by a Script in cell D3.
Script
- “Scripting” means the process of using a Script and a JavaScript program

The implementation of JavaScript within In-Sight Explorer follows version 5 of the open standard
approved by the European Computer Manufacturer’s Association, also known as ECMAScript 5 (ECMA5).

Section 8 | Slide 3 Section 8 | Slide 4


Passing Vision Tool Results to Script Passing Data Between Spreadsheet and Script

C40:

Script($C40)
Spreadsheet JavaScript Program

Cell Script JavaScript Code


Tool result names in JavaScript program correspond to tool function names Values
Results
in spreadsheet

Example for blobs: Get(s)

Spreadsheet function: JavaScript name must be:

GetNFound getNFound
GetArea getArea
GetWide getWide

NOTE: JavaScript names are case-sensitive

Section 8 | Page 5 Section 8 | Page 6

To send vision tool results from a spreadsheet to a JavaScript program, make a references in the Script
function to the cell containing the vision tool.

In the example above, cell C40 contains a DetectBlobs tool. The results from that tool are sent to the
JavaScript program because the Script function references cell C40.

The variable name for a tool result in the JavaScript program corresponds to the function name in the
spreadsheet. However, unlike the spreadsheet name, the variable name is case-sensitive. So if the
function in the spreadsheet is GetNFound, the corresponding name in the JavaScript program must be
arg0.getNFound. If you were to specify arg0.GetNFound or arg0.getNfound, it would not work.

Section 8 | Slide 5 Section 8 | Slide 6


Requirements for Scripting Why Use Scripting?

In-Sight models 57XX, 84XX, and successors Complex logic is difficult or impossible to implement in a
spreadsheet
- JavaScript has built-in functionality for complex logic

Spreadsheet

JavaScript

In-Sight Micro 8405

In-Sight 5705
Section 8 | Page 7 Section 8 | Page 8

Requirements for Scripting: A spreadsheet is easy to use and is fine for the vast majority of vision applications. However, applications
In-Sight model 5705, 5705C , 8405, and successors that require complex logic and manipulation of strings or dates, lend themselves well to Scripting.
In-Sight Explorer and firmware version 5.1.0 or higher
Spreadsheet mode of In-Sight Explorer

Scripting is not supported by the following:


In-Sight 51xx, 54xx, 56xx models
In-Sight 7xxx models
In-Sight Micro 1xxx models
EasyBuilder mode

Older models can not be upgraded to do scripting

Section 8 | Slide 7 Section 8 | Slide 8


Why Use Scripting? Why Use Scripting?

Complex calculations can be performed more easily and simply


• Makes it easier to read, debug, and modify complex jobs
with the JavaScript language:

• Overcomes some limitations of spreadsheet


- Array & string formulas
- Date & time handling
• Makes it easier to protect intellectual property - Analyzing data over multiple inspections
- Only need to protect one cell instead of many - Complex if-then-else
- Looping
• Can build libraries of functions that can be reused - Access to In-Sight vision tool results
- A library can be stored on a camera as a file separate from jobs - Access to In-Sight image graphics
- A library can be used by multiple jobs without having to repeat - Use of variable names
the code in every JavaScript program
- Dynamically pick a pattern from multiple patterns based on multiple criteria

Section 8 | Page 9 Section 8 | Page 10

The following slides give more details about libraries and intellectual property. Scripting uses the JavaScript language, which has functionality specifically designed for complex logic,
such as array and string handling, loops, and if-then-else constructs. When you use the Script function,
the JavaScript program has access to In-Sight’s vision tool results. For example, if a DetectBlobs tool is
referenced as an input to a Script, then the JavaScript program can access the tool results with names of
variables such as:
- xyz.getNFound
- xyz.getArea

Similarly, for an ExtractHistogram:


- abc.histContrast

xyz and abc are made up by the programmer for use in the JavaScript program. The rest of a variable
name must match the corresponding result function in the spreadsheet, with the exception that the
JavaScript result starts with a lower case letter, even though it starts with upper case in the spreadsheet.
For example: HistContrast becomes abc.histContrast

Another advantage of using JavaScript is that you can create descriptive variable names, making it easier
to understand.

Section 8 | Slide 9 Section 8 | Slide 10


Why Use Scripting? Example
Locate and mark missing blobs in a grid
Some limitations of spreadsheet are addressed by
Without Scripting With Scripting
JavaScript

- Limit on number of cells that can be used


- Limit on characters per cell
- Limit on nesting of references
- Certain string operations
- Ex: Strings with the null (“\0”) character – such as “ABC\0\0CBA”
-- cannot be handled in spreadsheet because null is the string
6 cells for logic,
terminator. including Script cell

Hundreds of spreadsheet cells needed if done with


multiple blob tools
Section 8 | Page 11 Section 8 | Page 12

Although there are limits, they are high. In this example, the goal is to locate and mark missing squares in a 13x18 array of squares, using blob
tools.
Cell limit is 10,400 cells, except for In-Sight 5000 which is 4096.
If we just put in a blob tool for each square in the grid, it would require hundreds of cells. Imagine the
There is a limit of 255 characters in a single cell. difficulty in changing that job to handle a smaller or larger grid of blobs. In addition to the work required,
we would run the risk of making an error with so many cells involved.
There is also a maximum "reference depth" of 256. This means that if you have a cell that references
another cell, which references another cell, which references another cell, etc., you can have up to 256 An equivalent spreadsheet using a Script function can be done with 6 cells of logic, one of which is the
levels of those references. Script.

Section 8 | Slide 11 Section 8 | Slide 12


JavaScript Libraries JavaScript Libraries

Example: Use a JavaScript library to determine the roots of 3. Write a JavaScript program that uses library:
function myquadtest(){}
a quadratic equation
module.exports = myquadtest;

Steps: var myquad = require('quadratic'); // import library

myquadtest.prototype.run = function(a, b, c) {
1. Write or obtain a library in JavaScript
Example: a file named quadratic.js that computes roots of a quadratic return myquad.roots(a,b,c);//put it to use
equation }

2. Copy library file to In-Sight camera (Drag & drop, FTP, etc.) 4. Set up spreadsheet with Script using the JavaScript program

Shows “Object” instead


of “Script” when retuning
multiple values
Script(B3,B4,B5) Get(A8,"root0")
JavaScript library on camera
Get A8,”root1”)
Section 8 | Page 13 Section 8 | Page 14

quadratic.js: A JavaScript library can be stored in a file of type js. For example: quadratic.js
/**
A set of functions that can be used to solve a quadratic equation. To use that library on an In-Sight camera, copy the library file to the camera. This can be done by using
*/ FTP, or by dragging the file from a PC’s desktop into the Files pane of In-Sight Explorer.
var quadratic = new Object();//here is where the parts will go
module.exports = quadratic;//tell it what to expose. In this case, anything attached to quadratic will be exposed Once the library is stored on the camera, specify the following in any JavaScript program:
/**
quadratic.discriminant = function(a,b,c) { xxx=require(‘quadratic’)
return b*b - 4*a*c;
}
Then, that JavaScript library can be used by any In-Sight spreadsheet job.
quadratic.roots = function(a,b,c) {
if(quadratic.discriminant(a,b,c) < 0) { //imaginary roots
root0 and root1 are calculated in quadratic.js
return NaN;
}

else if (quadratic.discriminant(a,b,c) === 0) { //give them an object with the only real root
return {
root: -b / (2*a)
}
}
else {
var discriminant = quadratic.discriminant(a,b,c);
//note that Math (capitol) is a built in library in javascript
return {
root0: (-b - Math.sqrt(discriminant) ) / ( 2* a ),
root1: (-b + Math.sqrt(discriminant) ) / ( 2* a )
}
}
}

Section 8 | Slide 13 Section 8 | Slide 14


JavaScript Editor JavaScript Editor

JavaScript template is built into In-Sight. Template adds 10 to total each time

• Template is run when Script function


is placed in a cell

• Double click on existing Script cell to


change program
Errors are reported at bottom
• Extensively commented
- Anything between /* and */ is comment
- Anything after // on a line is a comment
Console output Last result

• A JavaScript program referenced by a


Script is saved along with the job

Section 8 | Page 15 Section 8 | Page 16

The JavaScript editor can be entered by typing “Script” in a spreadsheet cell, or dragging the Script from The JavaScript template adds 10 to a running total each time the template is run.
the Palette. When you do this, the editor shows a built-in JavaScript template for In-Sight scripting.
Errors are displayed in the bottom two panes.
The template includes extensive comments to help you understand what needs to be done. You can type
in JavaScript code from within the editor, or copy and paste JavaScript from another application.

The Test Script button runs the JavaScript program.

Section 8 | Slide 15 Section 8 | Slide 16


JavaScript Template JavaScript Template with Comments Removed

Comments

JavaScript code.

JavaScript code.

etc.
Section 8 | Page 17 Section 8 | Page 18

The default name for the main JavaScript function is “Script.” It occurs in 6 places in the template.

If you want to use a more descriptive name for your application, you can change it to something else.
“Script” would need to be changed to the new name in the six places noted above. (You will do this in the
lab.)

NOTE: Names are case-sensitive.

Section 8 | Slide 17 Section 8 | Slide 18


Scripting Example JavaScript Snippets Included in In-Sight Explorer

B24:Script(C22:F22) Get(B24, “Total”) Get(B24,”Mean”)

• ArgumentsAndResults – demonstrates the use of a variable-length


arguments list and multi-value return statements.

• FindMissingBlobsInMatrix – detects and marks the locations of blobs


missing from a matrix of specified dimensions.

• SimulateShiftRegister – simulates a shift register.

• VerifyDateRange – determines if a date is within a specified range from


etc. current date.

Section 8 | Page 19 Section 8 | Page 20

The Snippets included in IS Explorer are:

- ArgumentsAndResults – demonstrates the use of a variable-length arguments list and multi-


value return statements.
- FindMissingBlobsInMatrix – detects and marks the locations of blobs missing from a matrix of
specified dimensions.
- SimulateShiftRegister – simulates a shift register.
- VerifyDateRange – determines if a date is within a specified period from current date.

Section 8 | Slide 19 Section 8 | Slide 20


Snippet: ArgumentsAndResults ArgumentsAndResults: JavaScript Excerpts

1. The values from the spreadsheet are 1


copied to an array named numbers(). 2

2. numbers() is then passed to the function


Via this “object” average 5
Multiple values returned by Script 3. average loops through the numbers() to
calculate their sum.

This list could have fewer or more numbers 4. average computes the average and
returns it to the main program

5. average is returned to the spreadsheet,


3
along with stddev, min, and max (which
are calculated elsewhere ).
4

Section 8 | Page 21 Section 8 | Page 22

This snippet demonstrates how to handle a variable number of inputs to a Script. Four results are This snippet demonstrates how to handle a variable number of inputs to a Script. Four results are
returned to the spreadsheet by means of four Get functions. returned to the spreadsheet by means of four Get functions.

Cells: Cells:
- A4:A15 contain 10 numbers, generated by Rand functions - A4:A15 contain 10 numbers, generated by Rand functions
- D3: Script(A4:A15) - D3: Script(A4:A15)

This invokes JavaScript code written to calculate the average, standard deviation, minimum, and This invokes JavaScript code written to calculate the average, standard deviation, minimum, and
maximum of the 10 numbers. maximum of the 10 numbers.

- D4: Get(D3, “avg”) retrieves the value calculated by user function avg - D4: Get(D3, “avg”) retrieves the value calculated by user function avg
- D5: Get(D3, “stddev”) retrieves the value calculated by user function stddev - D5: Get(D3, “stddev”) retrieves the value calculated by user function stddev
- D6: Get(D3, “min”) retrieves the value calculated by user function min - D6: Get(D3, “min”) retrieves the value calculated by user function min
- D7: Get(D3, “max”) retrieves the value calculated by user function max - D7: Get(D3, “max”) retrieves the value calculated by user function max

The number of values input into the Script can easily be changed just by changing the Script’s input from The number of values input into the Script can easily be changed just by changing the Script’s input from
A4:A15 to reference whatever the values are. A4:A15 to reference whatever the values are.

The lab for this section allows you to examine and modify this snippet. The lab for this section allows you to examine and modify this snippet.

Section 8 | Slide 21 Section 8 | Slide 22


Snippet: VerifyDateRange VerifyDateRange: JavaScript Excerpts

1. The six values from the 1


spreadsheet are input into
JavaScript. isPastDate
represents the CheckBox
value in spreadsheet, 0 or 1.

2. An if…else construct is used


to select different logic, based
A fixed string in Snippet on the value of isPastDate.
2
but could be a string isDateInRange is set to 0 if
read via OCR the date is out of range, 1 if in 2
range

3. isDateInRange is returned to 3

Script returns 0 or 1 the spreadsheet.

Section 8 | Page 23 Section 8 | Page 24

This snippet verifies that a specified date and time fall within a specified interval from the current date. A This snippet demonstrates how to handle a variable number of inputs to a Script. Four results are
CheckBox specifies whether it looks backward or forward in time. Only one value is returned to the returned to the spreadsheet by means of four Get functions.
spreadsheet, 0 or 1, which appears in the Script cell. No Get function is needed.
Cells:
Cells: - A4:A15 contain 10 numbers, generated by Rand functions
- D3: Script(A4:A15)
- D3: The date to be verified, as a string in ISO 8601 format
- C6:C9: Allowable deviation of specified date from current date and time This invokes JavaScript code written to calculate the average, standard deviation, minimum, and
- C10: CheckBox labeled “End Date is in the Past” maximum of the 10 numbers.

When the CheckBox is checked, the Script looks backwards in time. When the CheckBox is unchecked, - D4: Get(D3, “avg”) retrieves the value calculated by user function avg
the Script looks forward. - D5: Get(D3, “stddev”) retrieves the value calculated by user function stddev
- D6: Get(D3, “min”) retrieves the value calculated by user function min
D12: Script($E$5,$C$6,$C$7,$C$8,$C$9,$C$10) - D7: Get(D3, “max”) retrieves the value calculated by user function max
Returns 0 if specified date is out of range, 1 if in range
The number of values input into the Script can easily be changed just by changing the Script’s input from
Example: A4:A15 to reference whatever the values are.
Days=0, Hours=0, Minutes=20, Seconds=0, current time=10:30:00
- If E5=current date & CheckBox is checked, times of 10:10-10:30 will verify as 1 The lab for this section allows you to examine and modify this snippet.
- If E5=current date & Checkbox is unchecked, times of 10:30-10:50 will verify as 1

The lab for this section allows you examine and modify this snippet.

Section 8 | Slide 23 Section 8 | Slide 24


Snippet: SimulateShiftRegister SimulateShiftRegister: JavaScript Excerpts
This program stores data similar to a shift register; it will
return the oldest data contained in the buffer.
Script adds data to its
buffer until it is full and 1. The four values in the Script are copied into the program. value is the
then discards oldest data
to maintain history size.
current value for the shift register.
historySize is the number of values in the register.
resetEvent corresponds to the Button in the spreadsheet.
1
2. Complex logic involving
nested if’s is used to
determine the data type of
Script returns 2
value.
oldest data in
buffer.

Section 8 | Page 25 Section 8 | Page 26

This snippet simulates a shift register. This snippet demonstrates how to handle a variable number of inputs to a Script. Four results are
Cells: returned to the spreadsheet by means of four Get functions.
- C3: Rand($A$0) generates a random number every time a trigger occurs
- C6: Script($A$0,$C$3,$C$5,$D$5) Cells:
- C8: FormatOutputBuffer(0,"s8",$C$6) - A4:A15 contain 10 numbers, generated by Rand functions
- D3: Script(A4:A15)
The Script returns a list of the values in the shift register into cell C6, which is then referenced by the
FormatOutputBuffer function in cell C8. No Get function is used. This invokes JavaScript code written to calculate the average, standard deviation, minimum, and
maximum of the 10 numbers.
NOTE: This shift register can handle multiple kinds of data.
- D4: Get(D3, “avg”) retrieves the value calculated by user function avg
- D5: Get(D3, “stddev”) retrieves the value calculated by user function stddev
- D6: Get(D3, “min”) retrieves the value calculated by user function min
- D7: Get(D3, “max”) retrieves the value calculated by user function max

The number of values input into the Script can easily be changed just by changing the Script’s input from
A4:A15 to reference whatever the values are.

The lab for this section allows you to examine and modify this snippet.

Section 8 | Slide 25 Section 8 | Slide 26


Snippet: FindMissingBlobsInMatrix FindMissingBlobs: JavaScript Excerpts
1
1. The four values in the Script
are copied into the program.
Note that the first value passed
to the program is the SortBlobs
structure, called blobs in the
program. blobs.getNFound is
the number of blobs found – the
same as GetNFound in the
spreadsheet.
2
Red cells are inputs to Script in E13 2. This excerpt creates an array of
the Blobs’ structures that are
used elsewhere in the program.
Marks the search
grid and the missing
blobs
Section 8 | Page 27 Section 8 | Page 28

This snippet examines an array of squares using Blob tools. It detects any missing squares and marks This snippet demonstrates how to handle a variable number of inputs to a Script. Four results are
them in red. returned to the spreadsheet by means of four Get functions.

Cells: Cells:
- A4: DetectBlobs - A4:A15 contain 10 numbers, generated by Rand functions
- A9: SortBlobs - D3: Script(A4:A15)
- E13: Script(A9,B12,B13,G12), which returns the number of missing blobs
- Note that the four things passed to the JavaScript program are A9 (the SortBlobs structure), This invokes JavaScript code written to calculate the average, standard deviation, minimum, and
B12 (the number of rows of blobs), B13 (the number of columns of blobs), and G12 (CheckBox maximum of the 10 numbers.
for display of graphics)
- D4: Get(D3, “avg”) retrieves the value calculated by user function avg
If you tried to do the same thing using multiple blob tools in the spreadsheet (no Script), it would take - D5: Get(D3, “stddev”) retrieves the value calculated by user function stddev
hundreds of cells, and be difficult to change. - D6: Get(D3, “min”) retrieves the value calculated by user function min
- D7: Get(D3, “max”) retrieves the value calculated by user function max
The lab for this section allows you to examine and modify this snippet.
The number of values input into the Script can easily be changed just by changing the Script’s input from
A4:A15 to reference whatever the values are.

The lab for this section allows you to examine and modify this snippet.

Section 8 | Slide 27 Section 8 | Slide 28


Resources Summary of Scripting
• If you have little or no JavaScript experience:
- CodeAcademy JavaScript tutorial • Scripting allows use of JavaScript for easier
http://www.codecademy.com/en/tracks/javascript implementation of complex logic
• Other JavaScript resources: • Scripting also reduces spreadsheet clutter, making
- ‘Eloquent’ JavaScript:
http://eloquentjavascript.net/
debugging and modification easier
- Mozilla JavaScript Language Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference • There are two spreadsheet functions:
- JavaScript Quick Reference Card - Script: creates and executes script
http://www.cheat-sheets.org/saved-copy/jsquick.pdf
- Get: retrieves result
- JavaScript: The Definitive Guide, by David Flanangan (book)

• Using JavaScript on In-Sight • A JavaScript template and editor are included


- HELP in In-Sight Explorer
“Script Function JavaScript Source Code and API Reference”
“Edit Script Dialog” • Scripting is available starting with In-Sight Explorer
“Scripting” 5.1
- Sample snippets
- JavaScript template
Section 8 | Page 29 Section 8 | Page 30

In this section we covered the following topics:

- Scripting allows the use of JavaScript for easier implementation of complex logic
- Scripting also reduces spreadsheet clutter, making debugging and modification easier
- There are two spreadsheet functions:
- Script: creates and executes scripts
- Get: retrieves result
- A JavaScript template and editor are included
- Scripting is available starting with In-Sight Explorer 5.1

Section 8 | Slide 29 Section 8 | Slide 30


Lab Exercise

Section 8 | Page 31

Complete:
Lab Exercise 8.1 – Creating a JavaScript Program
Lab Exercise 8.2 – Using Snippet for Scripting
Lab Exercise 8.3 – Scripting with Multiple Gets (If Time Permits)
Lab Exercise 8.4 – Look at Additional Examples of Scripting (If Time Permits)

Section 8 | Slide 31

You might also like