SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Downloaden Sie, um offline zu lesen
ni.com
Foundational Design Patterns for
Multi-Purpose Applications
Ching-Hwa Yu
Software Group Leader | Certified LabVIEW Architect
Solution Sources Programming, Inc.
2ni.com
Topics
• Creating scalable applications
• Coupling
• Cohesion
• Moving beyond one loop
• Design patterns
• Communication mechanisms
• Functional global variables [DEMO]
• Queued message handlers [DEMO]
3ni.com
When Most
Consider Advanced
Architectures
When You Should Consider Advanced
Architectures
DefiningAdvancedApplications & LabVIEWAbility
Ability
3-Icon
Apps
State
Machines
Multi-Process
Apps
Multi-Target
Apps
LearningEffort
4ni.com
Master Key Design Patterns…
…and Understand Their Limitations
Ability
3-Icon
Apps
State
Machines
Multi-Process
Apps
Multi-Target
Apps
LearningEffort
Master the FGV
and the QMH
5ni.com
While Loop
Acquire Analyze Log Present
10ms 50ms 250ms 20ms
Doing Everything in One Loop Can Cause Problems
• One cycle takes at least 330 ms
• User interface can only be updated every 330 ms
• If the acquisition reads from a buffer, it may fill up
6ni.com
While Loop
Acquire Analyze
Log
Present10ms 50ms
250ms
20ms
Doing Everything in One Loop Can Cause Problems
• One cycle still takes at least 310 ms
• These are examples of high coupling
7ni.com
User Interface Event Handler
DAQ Acquisition
DAQ
Execution: The user interface cannot respond to other input while acquiring data
Development: Modifying one process requires modifying the other
Extensibility: How do you add a data logging process?
Maintenance: Can you test one piece of an application without testing its entirety?
Why is Coupling Bad?
8ni.com
Coupling is OftenAccidental: Case Study
Initial Scope
• Demonstrate:
• Data Acquisition
• CAN Synchronization
• Selected Architecture:
• State Machine
Final [Expanded] Scope
• Demonstrate:
• Data Acquisition
• CAN Synchronization
• IMAQ Acquisition
• TDMS Streaming
• DIAdem Post-processing
• Selected Architecture:
• Band-Aids and Duct Tape
NIWeek 2011 Hummer Demo
9ni.com
Coupling is OftenAccidental: Case Study
Final Demo Code
• Once
• Once you start…you can’t stop
• You can’t test independent actions
• There are 7 shift registers:
• State
• DAQ Settings
• TDMS Settings
• Errors
• DIAdem References
• IMAQ Settings
• CAN Settings
• Whether used or not, every shift
register goes across every case
10ni.com
While Loop
Cohesion: Limiting Process Scope
• Often, shift register
defines scope of process
• Processes should be very
cohesive
• Independent processes
should be separate loops
» DAQ »
» TDMS »
» User Interface »
» State Information »
Multiple shift registers for one process
indicate over-coupling
X
X
X
11ni.com
The Rewritten Hummer Demo
Using a Queued Message Handler Architecture
•O
n
c
e
•Once
12ni.com
DAQ Application
Event-Driven Loop
How to De-Couple Independent Processes
Best Practices
1. Identify data scope
2. Delegate actions to appropriate
process
3. Avoid polling or using timeouts*
*except for code that communicates with hardware
Considerations
1. How do you send commands?
2. How do you send data?
3. Which processes can communicate
with each other?
4. How do you update the UI?
?
13ni.com
Inter-Process Communication
ensures tasks run asynchronously
and efficiently
Goals
• Loops are running independently
• User interface can be updated
every 20 ms
• Acquisition runs every 10ms,
helping to not overflow the buffer
• All while loops run entirely
parallel with each other
While Loop
Acquire
While Loop
Analyze
While Loop
Present
While Loop
Log
10ms
50ms
250ms
20ms
…How?
14ni.com
Many Data Communication Options Exist in LabVIEW
1. TCP and UDP
2. Network Streams
3. Shared Variables
4. DMAs
5. Web Services
6. Peer-to-Peer Streaming
7. Queues
8. Dynamic Events
9. Functional Global Variables
10. RT FIFOs
11. Datasocket
12. Local Variables
13. Programmatic Front Panel
Interface
14. Target-scoped FIFOs
15. Notifiers
16. Simple TCP/IP Messaging
17. AMC
18. HTTP
19. FTP
20. Global variables
… just to name a few!
In no particular order…
15ni.com
“Don’t Re-invent
the Wheel…
…or Worse,
a Flat Tire.”
-Head First Design Patterns
16ni.com
What is a design pattern and why use one?
• Definition:
• A general reusable approach to a commonly occurring problem
• Well-established, proven techniques
• A formalized best practice
• Not a finished design
• Design patterns:
• Save time
• Improve code readability
• Simplify code maintenance
17ni.com
What is the difference between a design pattern and a
framework?
Design Pattern
• Focuses on a specific
problem
• Geared toward solo
developers
• More foundational
Framework
• Focuses on larger
applications
• Geared toward team
development
• Often involve an architect
18ni.com
Design Patterns are not Specific to LabVIEW
• Design Patterns: Elements of Reusable Object-Oriented
Software, 1994
• Includes examples in C++, Smalltalk
• The LabVIEW community has
adopted and extended several design
patterns for use with LabVIEW
• Examples:
o Producer / Consumer
o State Machine
o Queued Message Handler
o Factory Pattern
o Singleton Pattern
19ni.com
RisksAssociated with a “Flat Tire”
(Poor Application Design)
• Nothing happens when you press “Stop”
• Poor error handling
• No consistent style
• Complicated maintenance and debugging
• Difficulty scaling application
• Tight coupling, poor cohesion
20ni.com
Inter-Process Communication
• Store Data
• Stream Data
• Send
Message
Many more variations,
permutations, and design
considerations
Typically straightforward
use cases with limited
implementation options
21ni.com
Functional Global Variables
• What is a functional global variable (FGV)?
• Does the FGV prevent race conditions?
22ni.com
De-Facto Communication Choice: Locals / Globals
• Local and Global variables are simple and obvious
• Text-based mindset isn’t used to parallel programs,
multithreading
• Problem: Locals / Globals are pure data storage and
could cause race conditions
“The traditional, text-based programmer’s first instinct is
always to use local variables.”
– Brian Powell
23ni.com
What is a Functional Global Variable?
• The general form of a functional global variable includes
an uninitialized shift register (1) with a single iteration
While Loop
1.
Functional Global
Variable Code
24ni.com
What is a Functional Global Variable?
• A functional global variable usually has an action input
parameter that specifies which task the VI performs
• The uninitialized shift register in a loop holds the result of
the operation
25ni.com
Sidebar: Reentrant vs. Non-Reentrant
• Non-reentrancy is required for FGVs
• Reentrancy allows one subVI to be called simultaneously
from different places
• To allow a subVI to be called in parallel
• To allow a subVI instance to maintain its own state
Data
Space
Data
Space
Data
Space
State (or the data that
resides in the uninitialized
shift register) is maintained
between all instances of
the FGV
26ni.com
Various Inter-process Communication Methods Exist
• FGVs are one tool of many in the toolbox:
Same target
Same application instance
Same target, different application instances /
Different targets on network
Storing -
Current Value
• Single-process shared variables
• Local and global variables
• FGV, SEQ, DVR
• CVT
• Notifiers (Get Notifier)
• Network-published shared variables
(single-element)
• CCC
Sending
Message
• Queues (N:1)
• User events (N:N)
• Notifiers (1:N)
• User Events
• TCP, UDP
• Network Streams (1:1)
• AMC (N:1)
• STM (1:1)
Streaming
• Queues • Network Streams
• TCP
27ni.com
What Else Do I Need to Know?
• Store Data
• Stream Data
• Send
Message
Many more variations,
permutations, and design
considerations
Typically straightforward
use cases with limited
implementation options
28ni.com
Queued Message Handlers
• What are Queues?
• What is the Queued Message Handler (QMH)?
• Basic modifications to the QMH template
29ni.com
Adding Elements to the Queue
Dequeueing Elements
Reference to existing queue in memory
Select the data type the queue will hold
Dequeue will wait for data or time-out
(defaults to -1)
Queues 101: Inter-Process Communication
30ni.com
Producer Consumer Generalization
Thread 1
Thread 2
Thread 3
Best Practices
1. One consumer per queue
2. Keep at least one reference to a
named queue available at any time
3. Consumers can be their own
producers
4. Do not use variables
Considerations
1. How do you stop all loops?
2. What data should the queue send?
QUEUE
QUEUE
31ni.com
Anatomy of a “Producer” Process
Process
Stop
Condition
Met?
Send
InformationData
Information
Action or Event
Sends message to other process, program, or target
32ni.com
Anatomy of a Message Producer Process
Process
Stop
Condition
Met?
Inter-Process
CommunicationData
Command
Action or Event
Sends message to other process, program, or target
Message comprised of a
command and optional data
33ni.com
Constructing a Message
Examples:
Data
Variant allows data-type
to vary. Different
messages may require
different data.
Command
Enumerated constants
(or strings) list all of
the options.
Command Data
Initialize UI Cluster containing configuration
data
Populate Menu Array of strings to display in menu
Resize Display Array of integers [Width, Height]
Load Subpanel Reference of VI to Load
Insert Header String
Stop -
34ni.com
Sidebar: Enums versus Strings for Commands?
Enumerated Constant
• Safer to use – prevents
misspellings
• Compiler checks for
message validity
• Requires a copy for each
API (e.g. “Initialize”)
• “Add case for every value”
String
• Misspellings could lead to
runtime errors
• Onus is on the developer to
get messages correct
• Streamlines usage across
multiple APIs
• Universal data type
35ni.com
?
Next
Steps
FIRST STATE
Case structure has a case for every
command
Next steps could enqueue new action
for any other loop, including this one
Data cluster for all
states
After command is executed,
data cluster may be updated
Queue
Reference
Command
Execution
State
Specific
Data-type
Definition
Variant To Data
Dequeue
Action &
Data
Queued Message Handler “Consumer” Process
Defines the scope
of operations this
consumer can
handle Stop
Condition
Met?
36ni.com
Queued Message Handler
Template
37ni.com
Queued Message Handler
UI event capture loop
Message handling loop
Queue
setup
Template
38ni.com
Queued Message Handler
UI event capture loop
Message handling loop
Create queue for message communication and user
event to stop event loop
Template
39ni.com
Queued Message Handler
Message handling loop
Queue
setup
Event structure
in its own loop
String messages
added to a queue
Template
40ni.com
QMH Extends Producer/Consumer
SubVI Encapsulation
Exit
Strategy
Standard
Cases
Basic Controls
Included
41ni.com
QMH Features
Local Data
Receive Communication
Command: String
Data: Variant
Event
Handler
Update local
data?
Next steps
Stop
condition
met?
42ni.com
General Modifications to the QMH Template
• Add Interrupt
• What if a process needs to disrupt the flow of tasks (e.g.
Emergency stop)?
• Add Additional Message Handlers
• Add Error Handler
• Add Timeout to Dequeue Messages
• May want to timeout for regular Update Display execution
• …etc.
42
43ni.com
Application-Specific Modifications to the QMH
• Official Login Process
• Operator login and documentation
• Customized or Interactive Displays
• Different ways of displaying different types of data
• Standardized Logging
• Company or application specific file formatting and structure
• …etc.
43
44ni.com
Summary and Next Steps
• FGVs are an effective data storage mechanism
• Action engines prevent race conditions
• The QMH is really a starting point
• It will get you really far, but…
• It is frequently customized
• It is frequently one component in a larger framework
• Next Steps:
• Advanced Architectures in LabVIEW CustEd Course
• History Probe for keeping track of actions:
https://decibel.ni.com/content/docs/DOC-1106
45ni.com
Solution Sources Programming, Inc.
Company History
• Est. 1990
• Headquartered in San Jose, CA
• Support Requirements Worldwide
Expertise
• Turnkey Engineering & Production Test
Systems
• LabVIEW, TestStand, LabWindowsCVI
Industries
• Aerospace & Defense
• Consumer Electronics
• Green Technologies
• Medical and Life Sciences
• RF and Wireless
• Semiconductor
Contact us
www.ssprog.com
sales@ssprog.com
408-487-0270

Weitere ähnliche Inhalte

Was ist angesagt?

Como uso el formato de pruebas
Como uso el formato de pruebasComo uso el formato de pruebas
Como uso el formato de pruebas
Yesika Rodriguez
 
Metodología rmm resumido
Metodología rmm resumidoMetodología rmm resumido
Metodología rmm resumido
Angel Morinigo
 
tipos de pruebas.
tipos de pruebas.tipos de pruebas.
tipos de pruebas.
Juan Ravi
 

Was ist angesagt? (20)

Como uso el formato de pruebas
Como uso el formato de pruebasComo uso el formato de pruebas
Como uso el formato de pruebas
 
Eleven step of software testing process
Eleven step of software testing processEleven step of software testing process
Eleven step of software testing process
 
Manual open roberta
Manual open robertaManual open roberta
Manual open roberta
 
Plan curso de programación java SE
Plan curso de programación java SEPlan curso de programación java SE
Plan curso de programación java SE
 
Types of software testing
Types of software testingTypes of software testing
Types of software testing
 
Plan de pruebas_inces
Plan de pruebas_incesPlan de pruebas_inces
Plan de pruebas_inces
 
Unidad 1 Ingenieria de software
Unidad 1 Ingenieria de softwareUnidad 1 Ingenieria de software
Unidad 1 Ingenieria de software
 
Act 4.3 pruebas de software
Act 4.3 pruebas de softwareAct 4.3 pruebas de software
Act 4.3 pruebas de software
 
Gestión de la Calidad en Proyectos de Software
Gestión de la Calidad en Proyectos de SoftwareGestión de la Calidad en Proyectos de Software
Gestión de la Calidad en Proyectos de Software
 
Agile testing
Agile testingAgile testing
Agile testing
 
Pairing and mobbing
Pairing and mobbingPairing and mobbing
Pairing and mobbing
 
Metodología rmm resumido
Metodología rmm resumidoMetodología rmm resumido
Metodología rmm resumido
 
Plan de Pruebas
Plan de PruebasPlan de Pruebas
Plan de Pruebas
 
Principios básicos de usabilidad y accesibilidad
Principios básicos de usabilidad y accesibilidadPrincipios básicos de usabilidad y accesibilidad
Principios básicos de usabilidad y accesibilidad
 
Hands-On Mobile App Testing
Hands-On Mobile App TestingHands-On Mobile App Testing
Hands-On Mobile App Testing
 
Test Case Design and Technique
Test Case Design and TechniqueTest Case Design and Technique
Test Case Design and Technique
 
Building a testing team
Building a testing teamBuilding a testing team
Building a testing team
 
tipos de pruebas.
tipos de pruebas.tipos de pruebas.
tipos de pruebas.
 
Proceso de software
Proceso de softwareProceso de software
Proceso de software
 
Plan de pruebas
Plan de pruebasPlan de pruebas
Plan de pruebas
 

Andere mochten auch

Beyond State Machines: Building Modular Applications in LabVIEW Using Public ...
Beyond State Machines: Building Modular Applications in LabVIEW Using Public ...Beyond State Machines: Building Modular Applications in LabVIEW Using Public ...
Beyond State Machines: Building Modular Applications in LabVIEW Using Public ...
JKI
 
NIWeek 2011: Five Clever Debugging Techniques for Every LabVIEW Developer
NIWeek 2011: Five Clever Debugging Techniques for Every LabVIEW DeveloperNIWeek 2011: Five Clever Debugging Techniques for Every LabVIEW Developer
NIWeek 2011: Five Clever Debugging Techniques for Every LabVIEW Developer
JKI
 
LV Dev Efficiency NIDays 2015
LV Dev Efficiency NIDays 2015LV Dev Efficiency NIDays 2015
LV Dev Efficiency NIDays 2015
Jeffrey Habets
 
Real time Vital Signs Monitorong Using NI LabVIEW
Real time Vital Signs Monitorong Using NI LabVIEWReal time Vital Signs Monitorong Using NI LabVIEW
Real time Vital Signs Monitorong Using NI LabVIEW
Talha Patel
 

Andere mochten auch (15)

NIWeek 2011: Beyond State Machines / Building Modular Applications in LabVIEW...
NIWeek 2011: Beyond State Machines / Building Modular Applications in LabVIEW...NIWeek 2011: Beyond State Machines / Building Modular Applications in LabVIEW...
NIWeek 2011: Beyond State Machines / Building Modular Applications in LabVIEW...
 
Beyond State Machines: Building Modular Applications in LabVIEW Using Public ...
Beyond State Machines: Building Modular Applications in LabVIEW Using Public ...Beyond State Machines: Building Modular Applications in LabVIEW Using Public ...
Beyond State Machines: Building Modular Applications in LabVIEW Using Public ...
 
CLA Summit 2013: Connecting LabVIEW to Everything Else
CLA Summit 2013: Connecting LabVIEW to Everything ElseCLA Summit 2013: Connecting LabVIEW to Everything Else
CLA Summit 2013: Connecting LabVIEW to Everything Else
 
NIWeek 2011: Five Clever Debugging Techniques for Every LabVIEW Developer
NIWeek 2011: Five Clever Debugging Techniques for Every LabVIEW DeveloperNIWeek 2011: Five Clever Debugging Techniques for Every LabVIEW Developer
NIWeek 2011: Five Clever Debugging Techniques for Every LabVIEW Developer
 
Jki Introduction 2010
Jki   Introduction   2010Jki   Introduction   2010
Jki Introduction 2010
 
NIWeek 2011: Put the LabVIEW Community to Work for You
NIWeek 2011: Put the LabVIEW Community to Work for YouNIWeek 2011: Put the LabVIEW Community to Work for You
NIWeek 2011: Put the LabVIEW Community to Work for You
 
LV Dev Efficiency NIDays 2015
LV Dev Efficiency NIDays 2015LV Dev Efficiency NIDays 2015
LV Dev Efficiency NIDays 2015
 
NIWeek 2012: Secret Sauce / Tools to Make You a Better LabVIEW Developer
NIWeek 2012: Secret Sauce / Tools to Make You a Better LabVIEW DeveloperNIWeek 2012: Secret Sauce / Tools to Make You a Better LabVIEW Developer
NIWeek 2012: Secret Sauce / Tools to Make You a Better LabVIEW Developer
 
Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to Akka
 
LabView Workshop
LabView WorkshopLabView Workshop
LabView Workshop
 
REAL TIME VITAL SIGN MONITORING USING NI LABVIEW
REAL TIME VITAL SIGN MONITORING USING NI LABVIEWREAL TIME VITAL SIGN MONITORING USING NI LABVIEW
REAL TIME VITAL SIGN MONITORING USING NI LABVIEW
 
Model Predictive Control Implementation with LabVIEW
Model Predictive Control Implementation with LabVIEWModel Predictive Control Implementation with LabVIEW
Model Predictive Control Implementation with LabVIEW
 
SIMULATION OF TEMPERATURE SENSOR USING LABVIEW
SIMULATION OF TEMPERATURE SENSOR USING LABVIEWSIMULATION OF TEMPERATURE SENSOR USING LABVIEW
SIMULATION OF TEMPERATURE SENSOR USING LABVIEW
 
Real time Vital Signs Monitorong Using NI LabVIEW
Real time Vital Signs Monitorong Using NI LabVIEWReal time Vital Signs Monitorong Using NI LabVIEW
Real time Vital Signs Monitorong Using NI LabVIEW
 
PPT - Powerful Presentation Techniques
PPT - Powerful Presentation TechniquesPPT - Powerful Presentation Techniques
PPT - Powerful Presentation Techniques
 

Ähnlich wie Foundational Design Patterns for Multi-Purpose Applications

Overcoming software development challenges by using an integrated software fr...
Overcoming software development challenges by using an integrated software fr...Overcoming software development challenges by using an integrated software fr...
Overcoming software development challenges by using an integrated software fr...
Design World
 
MSF: Sync your Data On-Premises And To The Cloud - dotNetwork Gathering, Oct ...
MSF: Sync your Data On-Premises And To The Cloud - dotNetwork Gathering, Oct ...MSF: Sync your Data On-Premises And To The Cloud - dotNetwork Gathering, Oct ...
MSF: Sync your Data On-Premises And To The Cloud - dotNetwork Gathering, Oct ...
sameh samir
 
Choosing the right parallel compute architecture
Choosing the right parallel compute architecture Choosing the right parallel compute architecture
Choosing the right parallel compute architecture
corehard_by
 
Multi Layer Monitoring V1
Multi Layer Monitoring V1Multi Layer Monitoring V1
Multi Layer Monitoring V1
Lahav Savir
 
TechTalk_Cloud Performance Testing_0.6
TechTalk_Cloud Performance Testing_0.6TechTalk_Cloud Performance Testing_0.6
TechTalk_Cloud Performance Testing_0.6
Sravanthi N
 

Ähnlich wie Foundational Design Patterns for Multi-Purpose Applications (20)

Microservices.pdf
Microservices.pdfMicroservices.pdf
Microservices.pdf
 
Introduction
IntroductionIntroduction
Introduction
 
Microservices: Yes or not?
Microservices: Yes or not?Microservices: Yes or not?
Microservices: Yes or not?
 
Adding Real-time Features to PHP Applications
Adding Real-time Features to PHP ApplicationsAdding Real-time Features to PHP Applications
Adding Real-time Features to PHP Applications
 
Overcoming software development challenges by using an integrated software fr...
Overcoming software development challenges by using an integrated software fr...Overcoming software development challenges by using an integrated software fr...
Overcoming software development challenges by using an integrated software fr...
 
Architectural Decisions: Smoothly and Consistently
Architectural Decisions: Smoothly and ConsistentlyArchitectural Decisions: Smoothly and Consistently
Architectural Decisions: Smoothly and Consistently
 
Architectural Decisions: Smoothly and Consistently
Architectural Decisions: Smoothly and ConsistentlyArchitectural Decisions: Smoothly and Consistently
Architectural Decisions: Smoothly and Consistently
 
MSF: Sync your Data On-Premises And To The Cloud - dotNetwork Gathering, Oct ...
MSF: Sync your Data On-Premises And To The Cloud - dotNetwork Gathering, Oct ...MSF: Sync your Data On-Premises And To The Cloud - dotNetwork Gathering, Oct ...
MSF: Sync your Data On-Premises And To The Cloud - dotNetwork Gathering, Oct ...
 
Deploying at will - SEI
 Deploying at will - SEI Deploying at will - SEI
Deploying at will - SEI
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Choosing the right parallel compute architecture
Choosing the right parallel compute architecture Choosing the right parallel compute architecture
Choosing the right parallel compute architecture
 
Multi Layer Monitoring V1
Multi Layer Monitoring V1Multi Layer Monitoring V1
Multi Layer Monitoring V1
 
12 Factor App Methodology
12 Factor App Methodology12 Factor App Methodology
12 Factor App Methodology
 
oneM2M - Release 1 Primer
oneM2M - Release 1 PrimeroneM2M - Release 1 Primer
oneM2M - Release 1 Primer
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
IBM Blockchain Platform - Architectural Good Practices v1.0
IBM Blockchain Platform - Architectural Good Practices v1.0IBM Blockchain Platform - Architectural Good Practices v1.0
IBM Blockchain Platform - Architectural Good Practices v1.0
 
TechTalk_Cloud Performance Testing_0.6
TechTalk_Cloud Performance Testing_0.6TechTalk_Cloud Performance Testing_0.6
TechTalk_Cloud Performance Testing_0.6
 
Design Like a Pro: Planning Enterprise Solutions
Design Like a Pro: Planning Enterprise SolutionsDesign Like a Pro: Planning Enterprise Solutions
Design Like a Pro: Planning Enterprise Solutions
 
Design Like a Pro: Planning Enterprise Solutions
Design Like a Pro: Planning Enterprise SolutionsDesign Like a Pro: Planning Enterprise Solutions
Design Like a Pro: Planning Enterprise Solutions
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Foundational Design Patterns for Multi-Purpose Applications

  • 1. ni.com Foundational Design Patterns for Multi-Purpose Applications Ching-Hwa Yu Software Group Leader | Certified LabVIEW Architect Solution Sources Programming, Inc.
  • 2. 2ni.com Topics • Creating scalable applications • Coupling • Cohesion • Moving beyond one loop • Design patterns • Communication mechanisms • Functional global variables [DEMO] • Queued message handlers [DEMO]
  • 3. 3ni.com When Most Consider Advanced Architectures When You Should Consider Advanced Architectures DefiningAdvancedApplications & LabVIEWAbility Ability 3-Icon Apps State Machines Multi-Process Apps Multi-Target Apps LearningEffort
  • 4. 4ni.com Master Key Design Patterns… …and Understand Their Limitations Ability 3-Icon Apps State Machines Multi-Process Apps Multi-Target Apps LearningEffort Master the FGV and the QMH
  • 5. 5ni.com While Loop Acquire Analyze Log Present 10ms 50ms 250ms 20ms Doing Everything in One Loop Can Cause Problems • One cycle takes at least 330 ms • User interface can only be updated every 330 ms • If the acquisition reads from a buffer, it may fill up
  • 6. 6ni.com While Loop Acquire Analyze Log Present10ms 50ms 250ms 20ms Doing Everything in One Loop Can Cause Problems • One cycle still takes at least 310 ms • These are examples of high coupling
  • 7. 7ni.com User Interface Event Handler DAQ Acquisition DAQ Execution: The user interface cannot respond to other input while acquiring data Development: Modifying one process requires modifying the other Extensibility: How do you add a data logging process? Maintenance: Can you test one piece of an application without testing its entirety? Why is Coupling Bad?
  • 8. 8ni.com Coupling is OftenAccidental: Case Study Initial Scope • Demonstrate: • Data Acquisition • CAN Synchronization • Selected Architecture: • State Machine Final [Expanded] Scope • Demonstrate: • Data Acquisition • CAN Synchronization • IMAQ Acquisition • TDMS Streaming • DIAdem Post-processing • Selected Architecture: • Band-Aids and Duct Tape NIWeek 2011 Hummer Demo
  • 9. 9ni.com Coupling is OftenAccidental: Case Study Final Demo Code • Once • Once you start…you can’t stop • You can’t test independent actions • There are 7 shift registers: • State • DAQ Settings • TDMS Settings • Errors • DIAdem References • IMAQ Settings • CAN Settings • Whether used or not, every shift register goes across every case
  • 10. 10ni.com While Loop Cohesion: Limiting Process Scope • Often, shift register defines scope of process • Processes should be very cohesive • Independent processes should be separate loops » DAQ » » TDMS » » User Interface » » State Information » Multiple shift registers for one process indicate over-coupling X X X
  • 11. 11ni.com The Rewritten Hummer Demo Using a Queued Message Handler Architecture •O n c e •Once
  • 12. 12ni.com DAQ Application Event-Driven Loop How to De-Couple Independent Processes Best Practices 1. Identify data scope 2. Delegate actions to appropriate process 3. Avoid polling or using timeouts* *except for code that communicates with hardware Considerations 1. How do you send commands? 2. How do you send data? 3. Which processes can communicate with each other? 4. How do you update the UI? ?
  • 13. 13ni.com Inter-Process Communication ensures tasks run asynchronously and efficiently Goals • Loops are running independently • User interface can be updated every 20 ms • Acquisition runs every 10ms, helping to not overflow the buffer • All while loops run entirely parallel with each other While Loop Acquire While Loop Analyze While Loop Present While Loop Log 10ms 50ms 250ms 20ms …How?
  • 14. 14ni.com Many Data Communication Options Exist in LabVIEW 1. TCP and UDP 2. Network Streams 3. Shared Variables 4. DMAs 5. Web Services 6. Peer-to-Peer Streaming 7. Queues 8. Dynamic Events 9. Functional Global Variables 10. RT FIFOs 11. Datasocket 12. Local Variables 13. Programmatic Front Panel Interface 14. Target-scoped FIFOs 15. Notifiers 16. Simple TCP/IP Messaging 17. AMC 18. HTTP 19. FTP 20. Global variables … just to name a few! In no particular order…
  • 15. 15ni.com “Don’t Re-invent the Wheel… …or Worse, a Flat Tire.” -Head First Design Patterns
  • 16. 16ni.com What is a design pattern and why use one? • Definition: • A general reusable approach to a commonly occurring problem • Well-established, proven techniques • A formalized best practice • Not a finished design • Design patterns: • Save time • Improve code readability • Simplify code maintenance
  • 17. 17ni.com What is the difference between a design pattern and a framework? Design Pattern • Focuses on a specific problem • Geared toward solo developers • More foundational Framework • Focuses on larger applications • Geared toward team development • Often involve an architect
  • 18. 18ni.com Design Patterns are not Specific to LabVIEW • Design Patterns: Elements of Reusable Object-Oriented Software, 1994 • Includes examples in C++, Smalltalk • The LabVIEW community has adopted and extended several design patterns for use with LabVIEW • Examples: o Producer / Consumer o State Machine o Queued Message Handler o Factory Pattern o Singleton Pattern
  • 19. 19ni.com RisksAssociated with a “Flat Tire” (Poor Application Design) • Nothing happens when you press “Stop” • Poor error handling • No consistent style • Complicated maintenance and debugging • Difficulty scaling application • Tight coupling, poor cohesion
  • 20. 20ni.com Inter-Process Communication • Store Data • Stream Data • Send Message Many more variations, permutations, and design considerations Typically straightforward use cases with limited implementation options
  • 21. 21ni.com Functional Global Variables • What is a functional global variable (FGV)? • Does the FGV prevent race conditions?
  • 22. 22ni.com De-Facto Communication Choice: Locals / Globals • Local and Global variables are simple and obvious • Text-based mindset isn’t used to parallel programs, multithreading • Problem: Locals / Globals are pure data storage and could cause race conditions “The traditional, text-based programmer’s first instinct is always to use local variables.” – Brian Powell
  • 23. 23ni.com What is a Functional Global Variable? • The general form of a functional global variable includes an uninitialized shift register (1) with a single iteration While Loop 1. Functional Global Variable Code
  • 24. 24ni.com What is a Functional Global Variable? • A functional global variable usually has an action input parameter that specifies which task the VI performs • The uninitialized shift register in a loop holds the result of the operation
  • 25. 25ni.com Sidebar: Reentrant vs. Non-Reentrant • Non-reentrancy is required for FGVs • Reentrancy allows one subVI to be called simultaneously from different places • To allow a subVI to be called in parallel • To allow a subVI instance to maintain its own state Data Space Data Space Data Space State (or the data that resides in the uninitialized shift register) is maintained between all instances of the FGV
  • 26. 26ni.com Various Inter-process Communication Methods Exist • FGVs are one tool of many in the toolbox: Same target Same application instance Same target, different application instances / Different targets on network Storing - Current Value • Single-process shared variables • Local and global variables • FGV, SEQ, DVR • CVT • Notifiers (Get Notifier) • Network-published shared variables (single-element) • CCC Sending Message • Queues (N:1) • User events (N:N) • Notifiers (1:N) • User Events • TCP, UDP • Network Streams (1:1) • AMC (N:1) • STM (1:1) Streaming • Queues • Network Streams • TCP
  • 27. 27ni.com What Else Do I Need to Know? • Store Data • Stream Data • Send Message Many more variations, permutations, and design considerations Typically straightforward use cases with limited implementation options
  • 28. 28ni.com Queued Message Handlers • What are Queues? • What is the Queued Message Handler (QMH)? • Basic modifications to the QMH template
  • 29. 29ni.com Adding Elements to the Queue Dequeueing Elements Reference to existing queue in memory Select the data type the queue will hold Dequeue will wait for data or time-out (defaults to -1) Queues 101: Inter-Process Communication
  • 30. 30ni.com Producer Consumer Generalization Thread 1 Thread 2 Thread 3 Best Practices 1. One consumer per queue 2. Keep at least one reference to a named queue available at any time 3. Consumers can be their own producers 4. Do not use variables Considerations 1. How do you stop all loops? 2. What data should the queue send? QUEUE QUEUE
  • 31. 31ni.com Anatomy of a “Producer” Process Process Stop Condition Met? Send InformationData Information Action or Event Sends message to other process, program, or target
  • 32. 32ni.com Anatomy of a Message Producer Process Process Stop Condition Met? Inter-Process CommunicationData Command Action or Event Sends message to other process, program, or target Message comprised of a command and optional data
  • 33. 33ni.com Constructing a Message Examples: Data Variant allows data-type to vary. Different messages may require different data. Command Enumerated constants (or strings) list all of the options. Command Data Initialize UI Cluster containing configuration data Populate Menu Array of strings to display in menu Resize Display Array of integers [Width, Height] Load Subpanel Reference of VI to Load Insert Header String Stop -
  • 34. 34ni.com Sidebar: Enums versus Strings for Commands? Enumerated Constant • Safer to use – prevents misspellings • Compiler checks for message validity • Requires a copy for each API (e.g. “Initialize”) • “Add case for every value” String • Misspellings could lead to runtime errors • Onus is on the developer to get messages correct • Streamlines usage across multiple APIs • Universal data type
  • 35. 35ni.com ? Next Steps FIRST STATE Case structure has a case for every command Next steps could enqueue new action for any other loop, including this one Data cluster for all states After command is executed, data cluster may be updated Queue Reference Command Execution State Specific Data-type Definition Variant To Data Dequeue Action & Data Queued Message Handler “Consumer” Process Defines the scope of operations this consumer can handle Stop Condition Met?
  • 37. 37ni.com Queued Message Handler UI event capture loop Message handling loop Queue setup Template
  • 38. 38ni.com Queued Message Handler UI event capture loop Message handling loop Create queue for message communication and user event to stop event loop Template
  • 39. 39ni.com Queued Message Handler Message handling loop Queue setup Event structure in its own loop String messages added to a queue Template
  • 40. 40ni.com QMH Extends Producer/Consumer SubVI Encapsulation Exit Strategy Standard Cases Basic Controls Included
  • 41. 41ni.com QMH Features Local Data Receive Communication Command: String Data: Variant Event Handler Update local data? Next steps Stop condition met?
  • 42. 42ni.com General Modifications to the QMH Template • Add Interrupt • What if a process needs to disrupt the flow of tasks (e.g. Emergency stop)? • Add Additional Message Handlers • Add Error Handler • Add Timeout to Dequeue Messages • May want to timeout for regular Update Display execution • …etc. 42
  • 43. 43ni.com Application-Specific Modifications to the QMH • Official Login Process • Operator login and documentation • Customized or Interactive Displays • Different ways of displaying different types of data • Standardized Logging • Company or application specific file formatting and structure • …etc. 43
  • 44. 44ni.com Summary and Next Steps • FGVs are an effective data storage mechanism • Action engines prevent race conditions • The QMH is really a starting point • It will get you really far, but… • It is frequently customized • It is frequently one component in a larger framework • Next Steps: • Advanced Architectures in LabVIEW CustEd Course • History Probe for keeping track of actions: https://decibel.ni.com/content/docs/DOC-1106
  • 45. 45ni.com Solution Sources Programming, Inc. Company History • Est. 1990 • Headquartered in San Jose, CA • Support Requirements Worldwide Expertise • Turnkey Engineering & Production Test Systems • LabVIEW, TestStand, LabWindowsCVI Industries • Aerospace & Defense • Consumer Electronics • Green Technologies • Medical and Life Sciences • RF and Wireless • Semiconductor Contact us www.ssprog.com sales@ssprog.com 408-487-0270