Design Patterns in NI LabVIEW
Developer Days 2009
Agenda
What is a design pattern (what)
Benefits of design patterns (why)
Examples of design patterns (how)
The Need for Design Patterns
More
Onefeatures
more
feature,
.. Small
Uhh
Ilast
one
itsIbig
promise!
working
Add
Start
aHow
few
features
..think
Ithappen?
works!
no
deal
did
this
In the World of LabVIEW
How to avoid this:
What Is a Design Pattern?
Formal, solution to a problem
Widely accepted and well-known
Easily recognizable
Implementation Independent
Example: The Kitchen Sink
Benefits of Using Design Patterns
Simplify the development process
Developers can easily understand code
Do not have to reinvent the wheel
Provide preexisting solutions to common problems
Reliability
Many have been used for years they are tried and true
Refer to large development community and resources
online
Caution
You can needlessly complicate your
life if you use an unnecessarily
complex design pattern.
Do not forget the most common design
pattern of all data flow!
Basic Tools
Loops
Shift registers
Case structures
Enumerated constants
Event structures
Todays Discussion
As we look at each design pattern, we will discuss
A problem we are trying to solve
Background
How it works
Technical implementation
Demonstration
Use cases/considerations
Design Patterns
Basic
State machine
Event-driven user interface
Producer/consumer
Advanced
Object-oriented programming
10
National Instruments
Customer Education
LabVIEW
Basics I and II
State Machine
I need to execute a sequence of events, but the
order is determined programmatically.
Why Use a State Machine
Easily Extended
Can you add feature [x] to this program?
Flexible
Oops, I forgot to include a step to do [y]!
Easily Maintained
Thank goodness John used a state machine, we
can easily understand whats going on
12
Background
Static Sequence
Dynamic Sequence: Distinct states can operate in a
programmatically determined sequence
13
Vending Machine
Initialize
No Input
Wait
Change
Requested
Total <50
Change
Nickel Deposited
Quarter Deposited
Quarter
Dime Deposited
Total <50
Total <50
Nickel
Dime
Total 50
Total 50
Total >50
Vend
Soda costs 50 cents
Exit
Total = 50
14
Total 50
What is a State Machine in LabVIEW?
Case structure inside of a while loop
Each case is a single state
Current state has decision-making code that
determines next state
Use enumerated constants to pass value of next
state to shift registers
15
Defining the State Machine (1/4)
Framework
Decide which state to execute
Decide which state is next
16
Defining the State Machine (2/4)
State Code
StateCode
Code
State
Code
State
State Code
Execute code for a given state
17
Defining the State Machine (3/4)
Transition Logic
Figure out which state is next
18
Defining the State Machine (4/4)
Framework
State
State
Code
State
Code
Code
Transition
Logic
19
State Machines in LabVIEW
Framework
State
State
Code
State
Code
Code
Transition
Logic
20
State Machine
DEMO
21
Recommendations
Use Cases
Almost Always
Any program with more than a few steps
Considerations
You need to make a state diagram
LabVIEW Statechart module implements UML
statecharts
22
National Instruments
Customer Education
LabVIEW
Intermediate I
Event-Driven User Interface
I am polling for user actions, which is slowing my
application down, and sometimes I do not detect them!
Background
Procedural-driven programming
Performs a set of instructions in sequence
Requires polling to capture events
Cannot determine order of multiple events
Event-driven programming
Determines execution at run time
Waits for events to occur without consuming CPU
Remembers order of multiple events
24
How It Works
Event structure nested within loop
Blocking function until event registered or time-out
Events that can be registered:
Notify events are only for interactions with the front
panel
Dynamic events implement programmatic registration
Filter events help you to screen events before they are
processed
25
How It Works
1.
2.
3.
4.
Operating system broadcasts
system events (mouse click,
keyboard) to applications
Event structure captures
registered events and executes
appropriate case
Event structure returns
information about event to case
Event structure enqueues
events that occur while it is busy
26
How It Works: Static Binding
Browse controls
Browse events per control
Green arrow: notify
Red arrow: filter
27
Event-Driven User Interface
DEMO
28
Recommendations
Use Cases
UI: Conserve CPU usage
UI: Ensure you never miss an event
Drive slave processes
Considerations
Event structures eliminate determinism
Avoid placing two event structures in one loop
Remember to read the terminal of a latched Boolean control in its
value change event case
29
National Instruments
Customer Education
LabVIEW
Intermediate I
Producer/Consumer
I have two processes that need to execute at the same time,
and I need to make sure one cannot slow the other down.
How It Works
Thread 1
Master loop tells one or more
slave loops when they can
run
Allows for asynchronous
execution of loops
Data independence breaks
data flow and permits
multithreading
Decouples processes
Thread 2
Thread 3
31
Breaking Down the Design Pattern
Data-independent loops = multithreading
Master/slave relationship
Communication and synchronization between
loops
32
Queues
Adding Elements to the Queue
Select the data type the queue will hold
Reference to existing queue in memory
Dequeueing Elements
Dequeue will wait for data or time-out (defaults to -1)
34
Producer/Consumer
36
Producer/Consumer
DEMO
37
Recommendations
Use cases
Handling multiple processes simultaneously
Asynchronous operation of loops
Considerations
Multiple producers one consumer
One queue per consumer
If order of execution of parallel loop is critical,
use occurrences
39
National Instruments
Customer Education
LabVIEW OOP
System Design
Object-Oriented Programming
Dynamic Allocation
Inherited Functionality
Polymoprhism
Object Orientation Classes
A glorified cluster
A user-defined data type
A type of project library
41
Object Orientation Objects
An object is a specific instance of a class
Object data and methods are defined by the class
42
Object Orientation Inheritance
Each child class
inherits methods and
properties from its Printer
parent
Each child class can
also have its own
Laser Printer
unique methods
Copy Machine
Inkjet Printer
43
Object Orientation Dynamic Dispatching
Calling VI determines which version of a subVI to
use at run time. This prevents unneeded subVIs
from being loaded into memory.
Laser
Printer
Copy
Machine
Inkjet
Printer
44
Object Orientation Creating Classes
Create a class from within a project
Add VIs to the class to control methods and
properties
45
Object-Oriented Programming Logging Status Messages to a File
DEMO
46
Using Design Patterns
Lets put what we have learned to use.
Using Design Patterns
Problem: Create a responsive user interface
We need an application with a responsive user interface that
detects user inputs and reacts accordingly. This user interface
should not use excessive CPU resources. The actions we need to
take are not dependant on each other.
Solution: Event-Based Design Pattern
We should use an event-based design pattern because we need
to limit the CPU usage while waiting for events. We should not
encounter any race conditions because our actions are
independent of each other.
48
Using Design Patterns
Problem: Test and calibration system
We need to test several devices on a production line. Based on
the results of the test, we may need to calibrate the system using
one of two calibration routines, then retest the system.
Solution: State Machine
Because we do not know which of the calibration routines we
need to use, we should use a state machine to dynamically select
which of the two states we should enter.
Note: We should NOT use the object-oriented programming
factory design pattern for this because we only have two
calibration routines. Using object-oriented programming would be
needlessly complex.
49
Using Design Patterns
Problem: Data acquisition and data logging
We need to acquire data from two external instruments that
sample at different rates, filter the data, add the time of the test
and the operator who performed the test to the data, and then
write it all to a file.
Solution: Producer/consumer
We should use the producer/consumer architecture because we
have multiple tasks that run at different speeds and cannot afford
to be slowed down. Each of the external readings will be in
separate producer loops and the data processing and logging will
be in the consumer loop.
50
Using Design Patterns
Problem: Dynamically render a group of 3D objects
We need to create a series of 3D objects and display them.
These objects will be different from each other but will share some
similar properties. The number of each type that we will need to
create will not be known until the program runs.
Solution: Object-oriented programming
We should use object-oriented programming with a factory that
produces the proper number of each type of 3D object. Because
we do not know how many will be produced beforehand and they
all share some similar properties, dynamically creating these
objects from an object-oriented programming factory is the most
efficient solution.
51
Object-Oriented Programming 3D Object Field
DEMO
52
Resources
Example Finder
New>>Frameworks>>Design Patterns
ni.com/statechart
ni.com/labview/power
Training
LabVIEW Intermediate I and II
White paper on LabVIEW Queued State
Machine Architecture
Expressionflow.com
53
How to Develop
Your LabVIEW Skills
54
Fast Track to Skill Development
New User
Experienced User
Advanced User
Courses
Begin
Here
Core Courses
LabVIEW
LabVIEW
Basics II
Basics I
Certifications
Certified LabVIEW
Associate Developer Exam
LabVIEW Advanced I
LabVIEW
Intermediate I
LabVIEW
Intermediate II
Certified LabVIEW
Architect Exam
Certified LabVIEW
Developer Exam
If you are unsure take the
- Quick LabVIEW quiz
- Fundamentals exam
ni.com/training
55
Certification
56
Training Membership: The Flexible Option
Ideal for developing your skills with NI products
12 months to attend any NI regional or online
courses and take certification exams
$4,999 USD for a 12-month membership in the
USA
57
Next Steps
Visit ni.com/training
Identify your current expertise level and desired
level
Register for appropriate courses
$200 USD discount for attending LabVIEW
Developer Education Day!
58
LabVIEW Learning Paths
Advanced
LabVIEW Advanced I: Large
Application Development
LabVIEW Intermediate I and II
Intermediate
Specialty
Foundation
LabVIEW Object-Oriented
Programming System Design
LabVIEW
Real-Time
Application
Development
CompactRIO
Fundamentals
and LabVIEW
FPGA
LabVIEW
Instrument
Control
RF
Fundamentals
and RF
Application
Development
LabVIEW
Machine
Vision and
Image
Processing
LabVIEW Basics I and II
LabVIEW
DAQ and
Signal
Conditioning
Ways To Learn LabVIEW
In A Classroom Near You
Held at a local hotel or training facility
Personal Interaction with Instructor and other Attendees
On-line At Your Desk
Live and Instructor-led
No travel and reduced time away from work
At Your Company Office
Tailored course material for your companys needs
No travel required
At Your Convenience
Self-paced course kits
On-demand training modules located in the Services Resource Center
Training & Certification Membership Program
Unlimited access to all
regional and on-line
courses for one year
Unlimited access to all
certification exams for
one year
Option to retake all
courses and exams
ONE PRICE
Questions?