Download LabVIEW Intermediate II (Connectivity Course Manual).pdf...
TM
LabVIEW Intermediate II Connectivity Course Manual
Course Software Version 8.0 October 2005 Edition Part Number 323758B-01 LabVIEW Intermediate II Course Manual Copyright © 2004–2005 National Instruments Corporation. All rights reserved. Under the copyright laws, this publication may not be reproduced or transmitted in any form, electronic or mechanical, including photocopying, recording, storing in an information retrieval system, or translating, in whole or in part, without the prior written consent of National Instruments Corporation. In regards to components used in USI (Xerces C++, ICU, and HDF5), the following copyrights apply. For a listing of the conditions and disclaimers, refer to the USICopyrights.chm. This product includes software developed by the Apache Software Foundation (http:/www.apache.org/). Copyright © 1999 The Apache Software Foundation. All rights reserved. Copyright © 1995–2003 International Business Machines Corporation and others. All rights reserved. NCSA HDF5 (Hierarchical Data Format 5) Software Library and Utilities Copyright 1998, 1999, 2000, 2001, 2003 by the Board of Trustees of the University of Illinois. All rights reserved. Trademarks National Instruments, NI, ni.com, and LabVIEW are trademarks of National Instruments Corporation. Refer to the Terms of Use section on ni.com/legal for more information about National Instruments trademarks. Other product and company names mentioned herein are trademarks or trade names of their respective companies. Members of the National Instruments Alliance Partner Program are business entities independent from National Instruments and have no agency, partnership, or joint-venture relationship with National Instruments. Patents For patents covering National Instruments products, refer to the appropriate location: Help»Patents in your software, the patents.txt file on your CD, or ni.com/legal/patents.
Worldwide Technical Support and Product Information ni.com National Instruments Corporate Headquarters 11500 North Mopac Expressway Austin, Texas 78759-3504
USA Tel: 512 683 0100
Worldwide Offices Australia 1800 300 800, Austria 43 0 662 45 79 90 0, Belgium 32 0 2 757 00 20, Brazil 55 11 3262 3599, Canada 800 433 3488, China 86 21 6555 7838, Czech Republic 420 224 235 774, Denmark 45 45 76 26 00, Finland 385 0 9 725 725 11, France 33 0 1 48 14 24 24, Germany 49 0 89 741 31 30, India 91 80 51190000, Israel 972 0 3 6393737, Italy 39 02 413091, Japan 81 3 5472 2970, Korea 82 02 3451 3400, Lebanon 961 0 1 33 28 28, Malaysia 1800 887710, Mexico 01 800 010 0793, Netherlands 31 0 348 433 466, New Zealand 0800 553 322, Norway 47 0 66 90 76 60, Poland 48 22 3390150, Portugal 351 210 311 210, Russia 7 095 783 68 51, Singapore 1800 226 5886, Slovenia 386 3 425 4200, South Africa 27 0 11 805 8197, Spain 34 91 640 0085, Sweden 46 0 8 587 895 00, Switzerland 41 56 200 51 51, Taiwan 886 02 2377 2222, Thailand 662 278 6777, United Kingdom 44 0 1635 523545 For further support information, refer to the Additional Information and Resources appendix. To comment on National Instruments documentation, refer to the National Instruments Web site at ni.com/info and enter the info code feedback.
Contents Student Guide A. B. C. D. E. F.
NI Certification .....................................................................................................v Course Description ...............................................................................................vi What You Need to Get Started .............................................................................vi Installing the Course Software..............................................................................vii Course Goals.........................................................................................................vii Course Conventions ..............................................................................................viii
Lesson 1 Calling Shared Libraries in LabVIEW A. Shared Library Overview......................................................................................1-2 B. Calling Shared Libraries .......................................................................................1-2 Exercise 1-1 Computer Name................................................................................1-12 Summary .....................................................................................................................1-27
Lesson 2 VI Server A. What is VI Server?................................................................................................2-2 B. VI Server Programming Model ............................................................................2-4 C. VI Server Functions ..............................................................................................2-5 Exercise 2-1 Concept: VI Server Options .............................................................2-13 Exercise 2-2 VI Statistics ......................................................................................2-15 D. Remote Communication .......................................................................................2-23 Exercise 2-3 Concept: Remote Run VI .................................................................2-25 E. Dynamically Calling and Loading VIs .................................................................2-29 Exercise 2-4 Dynamically Calling VIs..................................................................2-34 Summary .....................................................................................................................2-38
Lesson 3 Calling Objects in LabVIEW A. Calling Objects in LabVIEW Using ActiveX.......................................................3-2 B. Using LabVIEW as an ActiveX Client.................................................................3-3 Exercise 3-1 Browse to URL.................................................................................3-7 Exercise 3-2 VI Statistics Report...........................................................................3-12 C. Using LabVIEW as an ActiveX Server ................................................................3-15 Exercise 3-3 Frequency Response VI....................................................................3-17 D. ActiveX Events .....................................................................................................3-19
© National Instruments Corporation
iii
LabVIEW Intermediate II Course Manual
Contents
E. Calling Objects in LabVIEW Using .NET ...........................................................3-21 F. Implementing .NET ..............................................................................................3-23 Exercise 3-4 Font Dialog.......................................................................................3-26 Exercise 3-5 Word Processor ................................................................................3-32 G. Registering .NET Events ......................................................................................3-53 Exercise 3-6 Auto Save .........................................................................................3-55 Summary .....................................................................................................................3-63
Lesson 4 Broadcasting Data A. Broadcasting Data Overview ................................................................................4-2 B. Implementing Broadcast Models ..........................................................................4-5 Exercise 4-1 VI Statistics Broadcast .....................................................................4-7 Summary .....................................................................................................................4-13
Lesson 5 Serving Data to a Client Using TCP/IP A. TCP/IP Overview..................................................................................................5-2 Exercise 5-1 Concept: Simple Data Client VI and Simple Data Server VI ..........5-6 B. Implementing the Client/Server Model ................................................................5-10 Exercise 5-2 TCP File Transfer .............................................................................5-13 Summary .....................................................................................................................5-24
Lesson 6 Publishing Data to a Subscriber A. Publisher/Subscriber Communication Model Overview ......................................6-2 B. Implementing the Publisher/Subscriber Communication Model..........................6-9 Exercise 6-1 Publisher and Subscriber ..................................................................6-15 Summary .....................................................................................................................6-22
Appendix A Additional Information and Resources Index Course Evaluation
LabVIEW Intermediate II Course Manual
iv
ni.com
Student Guide Thank you for purchasing the LabVIEW Intermediate II: Connectivity course kit. This course manual and the accompanying software are used in the two-day, hands-on LabVIEW Intermediate II: Connectivity course. You can apply the full purchase of this course kit toward the corresponding course registration fee if you register within 90 days of purchasing the kit. Visit ni.com/training for online course schedules, syllabi, training centers, and class registration. Note
A. NI Certification The LabVIEW Intermediate II: Connectivity course is part of a series of courses designed to build your proficiency with LabVIEW and help you prepare for exams to become an NI Certified LabVIEW Developer and NI Certified LabVIEW Architect. The following illustration shows the courses that are part of the LabVIEW training series. Refer to ni.com/ training for more information about NI Certification. Courses
Begin Here
New User
Experienced User
Advanced User
LabVIEW Basics I* LabVIEW Basics II*
LabVIEW Intermediate I*
LabVIEW Advanced Application Development
Skills learned: • LabVIEW environment navigation • Basic application creation using LabVIEW
LabVIEW Intermediate II* Skills learned: • Modular application development • Structured design and development practices • Memory management and VI performance improvement
Skills learned: • Large application design • Code reuse maximization • Object-oriented programming in LabVIEW
Certifications Certified LabVIEW Developer Exam
Certified LabVIEW Associate Developer Exam Skills tested: • LabVIEW environment knowledge
Skills tested: • LabVIEW application development expertise
Certified LabVIEW Architect Exam Skills tested: • LabVIEW application development mastery
Hardware-Based Courses: • Data Acquisition and Signal Conditioning • Modular Instruments • Instrument Control • Machine Vision • Motion Control • LabVIEW Real-Time *Core courses are strongly recommended to realize maximum productivity gains when using LabVIEW.
© National Instruments Corporation
v
LabVIEW Intermediate II Course Manual
Student Guide
B. Course Description This course manual teaches you how to use advanced connectivity in VIs. This course manual assumes that you are familiar with Windows, that you have experience writing algorithms in the form of flowcharts or block diagrams, and that you have taken the LabVIEW Basics I: Introduction and LabVIEW Basics II: Development courses or you have familiarity with all the concepts contained therein. This course also assumes that you have one year or more of LabVIEW development experience. The course manual is divided into lessons, each covering a topic or set of topics. Each lesson consists of the following: •
An introduction that describes the lesson’s purpose and topics
•
A discussion of the topics
•
A set of exercises to reinforce the topics presented in the discussion Several lessons in this manual include optional and challenge exercise sections.
•
A summary that outlines the important concepts and skills in the lesson
C. What You Need to Get Started Before you use this course manual, make sure you have the following items: ❑ Computer running Windows 2000 or later; This course manual is optimized for Windows XP ❑ LabVIEW Professional Development System 8.0 or later ❑ Spreadsheet application such as Microsoft Excel ❑ LabVIEW Intermediate II: Connectivity course CD, containing the following folders Directory
Description
Exercises
Folder containing all the VIs and support files needed to complete the exercises in this course
Solutions
Folder containing the completed versions of the VIs you build in the exercises for this course
LabVIEW Intermediate II Course Manual
vi
ni.com
Student Guide
D. Installing the Course Software Complete the following steps to install the course software. 1. Insert the course CD in your computer. The LabVIEW Intermediate Course Material Setup dialog box appears. 2. Click the Next button. 3. Choose Typical setup type and click the Install button to begin the installation. 4. Click the Finish button to exit the Setup Wizard. 5. The installer places the Exercises and Solutions folders at the top level of the C:\ directory.
Repairing or Removing Course Material You can repair or remove the course material using the Add or Remove Programs feature on the Windows Control Panel. Repair the course material to overwrite existing course material with the original, unedited versions of the files. Remove the course material if you no longer need the files on your machine.
E. Course Goals This course presents the following topics: •
•
Networking technologies –
External procedure call model
–
Broadcast model
–
Client/server model
–
Publish/subscribe model
Implementing the external procedure call model –
Calling shared libraries from LabVIEW
–
Programmatically controlling VIs using the VI Server •
–
–
Calling objects in LabVIEW using ActiveX •
Using LabVIEW as an ActiveX client
•
Using LabVIEW as an ActiveX server
•
ActiveX events
Calling Objects in LabVIEW using .NET •
© National Instruments Corporation
Using the VI Server functions to programmatically load and operate VIs and LabVIEW itself
Using LabVIEW as a .NET client
vii
LabVIEW Intermediate II Course Manual
Student Guide
• •
Implementing the broadcast model –
•
Using the UDP VI and functions to create a UDP multicast session
Implementing the client/server model –
•
.NET events
Using the TCP/IP VI and functions to communicate with other applications locally and over a network
Implementing the publish/subscribe model –
Using the Shared Variable node to read, write, and share data among VIs and other applications locally and over a network
This course does not present any of the following topics: •
Basic principles of LabVIEW covered in the LabVIEW Basics I: Introduction and LabVIEW Basics II: Development courses
•
Every built-in VI, function, or object; refer to the LabVIEW Help for more information about LabVIEW features not described in this course
•
Developing a complete VI for any student in the class; refer to the NI Example Finder, available by selecting Help»Find Examples, for example VIs you can use and incorporate into VIs you create
F. Course Conventions The following conventions are used in this course manual: »
The » symbol leads you through nested menu items and dialog box options to a final action. The sequence File»Page Setup»Options directs you to pull down the File menu, select the Page Setup item, and select Options from the last dialog box. This icon denotes a tip, which alerts you to advisory information. This icon denotes a note, which alerts you to important information. This icon denotes a caution, which advises you of precautions to take to avoid injury, data loss, or a system crash.
bold
Bold text denotes items that you must select or click in the software, such as menu items and dialog box options. Bold text also denotes parameter names, controls and buttons on the front panel, dialog boxes, sections of dialog boxes, menu names, and palette names.
italic
Italic text denotes variables, emphasis, a cross reference, or an introduction to a key concept. Italic text also denotes text that is a placeholder for a word or value that you must supply.
LabVIEW Intermediate II Course Manual
viii
ni.com
Student Guide
monospace
Text in this font denotes text or characters that you enter from the keyboard, sections of code, programming examples, and syntax examples. This font also is used for the proper names of disk drives, paths, directories, programs, subprograms, subroutines, device names, functions, operations, variables, filenames, and extensions.
monospace bold
Bold text in this font denotes the messages and responses that the computer automatically prints to the screen. This font also emphasizes lines of code that are different from the other examples.
platform
Text in this font denotes a specific platform and indicates that the text following it applies only to that platform.
© National Instruments Corporation
ix
LabVIEW Intermediate II Course Manual
Calling Shared Libraries in LabVIEW
1
You can use LabVIEW to call code written in other languages in the following ways: •
Using platform-specific protocols.
•
Using the Call Library Function Node to call the following types of shared libraries: –
Dynamic Link Libraries (DLL) on Windows
–
Frameworks on Mac OS
–
Shared Libraries on Linux
The scope of this course covers using the Call Library Function Node to call Dynamic Link Libraries (shared libraries) on Windows. Refer to the LabVIEW Help for information about other ways to use LabVIEW to call code written in other languages.
Topics A. Shared Library Overview B. Calling Shared Libraries
© National Instruments Corporation
1-1
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
A. Shared Library Overview On Windows, a shared library is called a DLL. A shared library is a library of executable functions or data that can be used by a Windows application. Typically, a shared library provides one or more particular functions that a program can access by creating a static or dynamic link to the shared library. A static link remains constant during program execution and a dynamic link is created by the program as needed. The library is stored as a binary file. You can use any language to write DLLs as long as the DLLs can be called using one of the calling conventions LabVIEW supports, either stdcall or C. Examples and troubleshooting information help you build and use DLLs and to successfully configure the Call Library Function Node in LabVIEW. The general methods described here for DLLs also apply to other types of shared libraries. Refer to the labview\examples\dll directory for examples of using shared libraries.
B. Calling Shared Libraries This section describes the process of using a DLL in LabVIEW.
Describing and Defining Shared Libraries You can call most standard shared libraries with the Call Library Function Node. On Windows, these shared libraries are DLLs, on Mac OS, they are Frameworks, and on Linux, they are Shared Libraries. The Call Library Function Node includes a large number of data types and calling conventions. You can use the Call Library Function Node to call functions from most standard and custom-made libraries.
Functions, Advantages, and Limitations of DLLs DLLs have the following advantages: •
You can change the DLL without changing any of the VIs that link to the DLL, provided you do not modify the function prototypes.
•
Practically all modern development environments provide support for creating DLLs.
The Call Library Function Node is most appropriate when you have existing code you want to call, or if you are familiar with the process of creating standard shared libraries. Because a library uses a format standard among several development environments, you can use almost any development environment to create a library that LabVIEW can call. Refer to the documentation for your compiler to determine whether you can create standard shared libraries.
LabVIEW Intermediate II Course Manual
1-2
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
The LabVIEW compiler can generate code fast enough for most programming tasks. Call shared libraries from LabVIEW to accomplish tasks a text-based language can accomplish more easily, such as timecritical tasks. Also use shared libraries for tasks you cannot perform directly from the block diagram, such as calling system routines for which no corresponding LabVIEW functions exist. Shared libraries also can link existing code to LabVIEW, although you might need to modify the code so it uses the correct LabVIEW data types. Shared libraries execute synchronously, so LabVIEW cannot use the execution thread used by these objects for any other tasks. When a VI runs, LabVIEW monitors the user interface, including the menus and keyboard. In multithreaded applications, LabVIEW uses a separate thread for user interface tasks. In single-threaded applications, LabVIEW switches between user interface tasks and running VIs. When shared library object code executes, it takes control of its execution thread. If an application has only a single thread of control, the application waits until the object code returns. In single-threaded operating systems such as Mac OS, shared libraries even prevent other applications from running. LabVIEW cannot interrupt object code that is running, so you cannot reset a VI that is running a shared library until execution completes. If you want to write a shared library that performs a long task, be aware that LabVIEW cannot perform other tasks in the same thread while these objects execute.
Method for Calling Shared Libraries Use the Call Library Function Node to directly call a 32-bit Windows DLL, a Mac OS Framework, or a Linux Shared Library function. With this node, you can create an interface in LabVIEW to call existing libraries or new libraries specifically written for use with LabVIEW. National Instruments recommends using the Call Library Function Node to create an interface to external code. Be aware when using the Call Library Function Node or writing code that is called by the Call Library Function Node that LabVIEW reserves Windows messages WM_USER through WM_USER+99 for internal use only. Note
Right-click the Call Library Function Node and select Configure from the shortcut menu to open the Call Library Function dialog box, shown in the following figure. Use the Call Library Function dialog box to specify the library, function, parameters, return value for the object, and calling conventions on Windows. When you click OK in the Call Library Function dialog box, LabVIEW updates the Call Library Function Node
© National Instruments Corporation
1-3
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
according to your settings, displaying the correct number of terminals and setting the terminals to the correct data types.
As you configure parameters, the Function Prototype text box displays the C prototype for the function you are building. This text box is a read-only display.
Setting the Calling Convention Use the Calling Conventions pull-down menu in the Call Library Function dialog box to select the calling convention for the function. The default calling convention is C. (Windows) You also can use the standard Windows calling convention, stdcall.
Refer to the documentation for the DLL you want to call for the appropriate calling conventions.
Configuring Parameters Initially, the Call Library Function Node has no parameters and has a return type of Void. The return type for the Call Library Function Node returns to the right terminal of the top pair of terminals. If the return type is Void, the top pair of terminals is unused. Each additional pair of terminals corresponds to a parameter in the Parameter list of the Call Library
LabVIEW Intermediate II Course Manual
1-4
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
Function Node. To pass a value to the Call Library Function Node, wire to the left terminal of a terminal pair. To read the value of a parameter after the Call Library Function Node call, wire from the right terminal of a terminal pair. The following figure shows a Call Library Function Node that has a return type of Void, a string parameter, and a numeric parameter.
Return Type For return type, you can set Type to Void, Numeric, or String. Void is only available for return type and is not available for parameters. Use Void for the return type if your function does not return any values. Even if the function you call returns a value, you can use Void for the return type. When the function returns a value and you select Void as the return type, the value returned by the function is ignored. If the function you are calling returns a data type not listed, choose a return data type the same data size as the one returned by the function. For example, if the function returns a char data type, use an 8-bit unsigned integer. A call to a function in a DLL cannot return a pointer because there are no pointer types in LabVIEW. However, you can specify the return type as an integer that is the same size as the pointer. LabVIEW then treats the address as a simple integer, and you can pass it to future DLL calls. Note
Adding and Deleting Parameters To add parameters to the Call Library Function Node, click the Add a Parameter Before button or the Add a Parameter After button. To remove a parameter, click the Delete this Parameter button. Editing Parameters Use the Parameter pull-down menu to select the return value or a parameter for editing. When selected, you can edit the Parameter name to something more descriptive, which makes it easier to switch between parameters. The Parameter name does not affect the call, but it is propagated to output wires. Also, you can edit all fields in the Parameter section for the selected parameter.
© National Instruments Corporation
1-5
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
Selecting the Parameter Type Use the Type pull-down menu to indicate the type of each parameter. You can select from the following parameter types: •
Numeric
•
Array
•
String
•
Waveform
•
Digital Waveform
•
Digital Data
•
ActiveX
•
Adapt to Type
After you select an item from the Type pull-down menu, you see more items you can use to indicate details about the parameter and about how to pass the data to the library function. The Call Library Function Node has a number of different items for parameter types because of the variety of data types required by different libraries. Refer to the documentation for the library you call to determine which parameter types to use. The following sections discuss the different parameter types available from the Type pull-down menu. (Windows) Refer to the labview\examples\dll\data passing\Call Native Code.llb for an example of using data types in shared libraries. Numeric
For numeric data types, you must indicate the exact numeric type by using the Data Type pull-down menu. You can choose from the following data types: •
8-, 16-, 32-, and 64-bit signed and unsigned integers
•
4-byte, single-precision numbers
•
8-byte, double-precision numbers
Extended-precision numbers and complex numbers can be passed by selecting Adapt to Type from the Type pull-down menu. However, standard libraries generally do not use extended-precision numbers and complex numbers. Note
Use the Pass pull-down menu to indicate whether you want to pass the value or a pointer to the value.
LabVIEW Intermediate II Course Manual
1-6
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
Array
Use the Data Type pull-down menu to indicate the data type of the array. You can choose from the same data types available for numeric parameters. Specify the dimensions of the array in Dimension. Use the Array Format pull-down menu to make one of the following choices: •
Array Data Pointer passes a one-dimensional pointer to the array data.
•
Array Handle passes a pointer to a pointer that points to a four-byte value for each dimension, followed by the data.
•
Array Handle Pointer passes a pointer to an array handle.
Note Do not attempt to resize an array with system functions, such as realloc. Doing so might crash your system. Instead, use one of the Code Interface Node (CIN) manager functions, such as NumericArrayResize. String
Use the String Format pull-down menu to indicate the string format. You can choose from the following string formats: •
C String Pointer—a string followed by a null character
•
Pascal String Pointer—a string preceded by a length byte
•
String Handle—a pointer to a pointer to four bytes for length information, followed by string data
•
String Handle Pointer
Select a string format that the library function expects. Most standard libraries expect either a C string or a Pascal string. If the library function you are calling is written for LabVIEW, you might want to use the string handle format. Do not attempt to resize a string with system functions, such as realloc, because your system might crash.
Note
String Options LabVIEW stores strings as arrays, that is, structures pointed to by handles. The Call Library Function Node works with C and Pascal-style string pointers or LabVIEW string handles. The following illustration shows an example of a LabVIEW string handle.
© National Instruments Corporation
1-7
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
String Data
\00
\00
\00
\04
t
e
x
t
String Length
Think of a string as an array of characters. Assembling the characters in order forms a string. LabVIEW stores a string in a special format in which the first four bytes of the array of characters form a 32-bit signed integer that stores how many characters appear in the string. Thus, a string with n characters requires n + 4 bytes to store in memory. For example, the string text contains four characters. When LabVIEW stores the string, the first four bytes contain the value 4 as a 32-bit signed number, and each of the following four bytes contains a character of the string. The advantage of this type of string storage is that NULL characters are allowed in the string. Strings are virtually unlimited in length, up to 231 characters. The Pascal string format is nearly identical to the LabVIEW string format, but instead of storing the length of the string as a 32-bit signed integer, it is stored as an 8-bit unsigned integer. This limits the length of a Pascal-style string to 255 characters. A graphical representation of a Pascal string appears in the following illustration. A Pascal string that is n characters long requires n + 1 bytes of memory to store. String Length \04
t
e
x
t
String Data
C strings are probably the type of strings you deal with most often. The similarities between the C-style string and normal numeric arrays in C becomes much clearer when you notice that C strings are declared as char *. C strings do not contain any information that directly indicate the length of the string, as do the LabVIEW and Pascal strings. Instead, C strings use a special character, called the NULL character, to indicate the end of the string, as shown in the following illustration. NULL has a value of zero in the ASCII character set. Notice that this is the number zero and not the character 0.
LabVIEW Intermediate II Course Manual
1-8
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
NULL Character
t
e
x
t
\00
String Data
Thus, in C, a string containing n characters requires n + 1 bytes of memory to store, n bytes for the characters in the string and one additional byte for the NULL termination character. The advantage of C-style strings is that they are limited in size only by available memory. However, if you are acquiring data from an instrument that returns numeric data as a binary string, as is common with serial or GPIB instruments, values of zero in the string are possible. For binary data where NULLs might be present, you should use an array of 8-bit unsigned integers. If you treat the string as a Cstyle string, the program assumes incorrectly that the end of the string has been reached, when in fact the instrument is returning a numeric value of zero. Waveform
When you call a shared library that includes a waveform data type, you do not have to specify a numeric value from the Data Type pull-down menu; the default is 8-byte double. However, you must specify a Dimension. If the Parameter is a single waveform, specify a Dimension of 0. If the Parameter is an array of waveforms, specify a Dimension of 1. LabVIEW does not support an array of waveforms greater than 1D. Digital Waveform
Specify a Dimension of 0 if the Parameter is a single digital waveform. Specify a Dimension of 1 if the Parameter is an array of digital waveforms. LabVIEW does not support an array of digital waveforms greater than 1D. Digital Table
Specify a Dimension of 1 if the Parameter is an array of digital data. Otherwise, specify a Dimension of 0. LabVIEW does not support an array of digital data greater than 1D. Note You can pass waveforms, digital waveforms, and digital data through shared libraries, but accessing the data inside the shared libraries is not supported at this time.
© National Instruments Corporation
1-9
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
ActiveX
Select one of the following items from the Data Type pull-down menu: •
ActiveX Variant Pointer passes a pointer to ActiveX data.
•
IDispatch* Pointer passes a pointer to the IDispatch interface of an ActiveX Automation server.
•
IUnknown Pointer passes a pointer to the IUnknown interface of an ActiveX Automation server.
Adapt to Type
Use Adapt to Type to pass arbitrary LabVIEW data types to DLLs. The arbitrary LabVIEW data types are passed to DLLs in the following ways: •
Scalars are passed by reference. A pointer to the scalar is passed to the library.
•
Arrays and strings are passed according to the Data Format setting. You can choose from the following Data Format settings: –
Handles by Value passes the handle to the library. The handle is not NULL.
–
Pointers to Handles passes a pointer to the handle to the library. If the handle is NULL, treat the handle as an empty string or array. To set a value when the handle is NULL, you must allocate a new handle.
•
Clusters are passed by reference.
•
Scalar elements in arrays or clusters are in line. For example, a cluster containing a numeric is passed as a pointer to a structure containing a numeric.
•
Clusters within arrays are in line.
•
Strings and arrays within clusters are referenced by a handle.
When one or more of the parameters of the function you want to call in a DLL are of types that do not exist in LabVIEW, ensure that each parameter is passed to the function in a way that allows the DLL to correctly interpret the data. Create a skeleton .c file from the current configuration of the Call Library Function Node. By viewing the .c file, you can determine whether LabVIEW passes the data in a manner compatible with the DLL function. You then can make any necessary adjustments. Note
Working with Unusual Data Types You might encounter a function that expects data in a form that the Call Library Function Node cannot pass. Specifically, the Call Library Function Node does not support structures or arrays containing a pointer to other data or structures containing flat arrays that can be variably sized. You can call a function that expects an unsupported data type in the following ways:
LabVIEW Intermediate II Course Manual
1-10
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
•
If the data contains no pointers, you might be able to use the Flatten to String function to create a string containing the binary image of the data required and pass this string as a C string pointer. You will probably want to use the byte order input to Flatten to String to specify that the data be flattened in native byte order.
•
Write a library function that accepts the data in the form used by LabVIEW and builds the data structure expected by the other library. This function can then call the other library and retrieve any returned values before returning. Your function will probably accept the data from the diagram as adapt to type, so that any diagram data type can be passed.
Thread-Safe and Thread-Unsafe DLLs In a multithreaded operating system, you can make multiple calls to a DLL or shared library simultaneously. By default, all call library objects run in the user interface thread. The control below the Browse button in the Call Library Function dialog box reflects your selection of Run in UI Thread or Reentrant. Before you configure a Call Library Function Node to be reentrant, make sure that multiple threads can call the function simultaneously. The following characteristics are the basic characteristics of thread safe code in a shared library: •
The code is thread safe when it does not store any global data, such as global variables, files on disk, and so on.
•
The code is thread safe when it does not access any hardware. In other words, the code does not contain register-level programming.
•
The code is thread safe when it does not make any calls to any functions, shared libraries, or drivers that are not thread safe.
•
The code is thread safe when it uses semaphores or mutexes to protect access to global resources.
•
The code is thread safe when it is called by only one non-reentrant VI.
Refer to the Execution Properties Page topic of the LabVIEW Help for more information about reentrancy. Refer to the Benefits of Multithreaded Applications topic of the LabVIEW Help for more information about multithreading in LabVIEW.
© National Instruments Corporation
1-11
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
Exercise 1-1
Computer Name
Goal Call a DLL function from the Windows API.
Scenario Programmatically determining the Windows computer name is necessary in a number of situations. For example, if you have several computers logging data to a central server, you should identify the computer name for each set of data in order to track the data. The computer name is also helpful for storing or retrieving data over a Windows File Share and is a useful piece of information to include when generating reports. There is not a native function within LabVIEW to retrieve the computer name. However, the Windows operating system provides an API, in the form of DLLs, which allows you to interface with the operating system. One common use of this API is retrieving useful information about the operating system or computer, such as the computer name. Call a Windows API DLL function to determine the name of the computer. You should also handle any errors returned by the function in an appropriate manner. The Windows computer name is different from the network address of a computer. You can determine a computer’s network address in LabVIEW by using the String to IP and IP to String functions located on the TCP/IP palette. Note
Design Inputs and Outputs Table 1-1. Computer Name Inputs and Outputs
Type
Name
Properties
Default Values
Numeric Control
Buffer Size
32-bit Unsigned Integer
256
String Indicator
Computer Name
—
Empty
Program Structure When you call a DLL in LabVIEW, any error handling must be performed manually. Therefore Call Library Function nodes do not have error cluster inputs and outputs. Because you cannot wire error clusters to enforce dataflow between nodes, you must use other data wires or structures to
LabVIEW Intermediate II Course Manual
1-12
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
control the execution order of your program. The best structure for controlling execution order is a state machine, as it allows you better decision making and error handling strategies than a Sequence structure.
State Machine Design For this program you utilize a state machine with three states: Get Computer Name, Handle Error and Stop. The first state gets the computer name. If the state succeeds, the program moves to the Stop state and finishes. If the DLL call to get the computer name fails, the program enters the Handle Error state, where it accesses an error code and translates the error code into an error message. Get Computer Name Case The Windows API provides a function called GetComputerName in Kernel32.dll. In order to call this function in LabVIEW, you need to allocate a string buffer large enough to hold the computer name. Use the byte array method described in the String Options section of this lesson to allocate the buffer. If the buffer is too small to store the computer name, or if another error occurs, this function returns a value of zero. Use the return value from this function to control the transition logic of the state machine. Handle Errors Case In order to provide a meaningful error message for Windows API calls, you need to perform two steps. First, you must call the Windows API function GetLastError. This function returns a numeric value that represents any error encountered during the last function call, in this case, GetComputerName. In order to translate the numeric code into a meaningful message, you must call the FormatMessage Windows API function. You can use this function many different ways. Control the behavior of the function by setting one or more flags in a parameter called dwFlags. In order to return a message for a system error, set the FORMAT_MESSAGE_FROM_SYSTEM flag. Also set the FORMAT_MESSAGE_IGNORE_INSERTS flag because you do not need to include any additional parameters in your message. Setting this parameter also allows you to ignore the arguments parameter of the function, thereby simplifying the function call. For more information on setting flags, refer to the Background: Windows API Reference section. All of the functions called in this exercise are in kernel32.dll. However, Windows API functions are found in many other DLLs. Refer to the Windows API Reference to determine in which DLL a given function is located.
Tip
Stop Case The stop case simply finishes the state machine, thereby ending the While Loop and the program.
© National Instruments Corporation
1-13
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
Additional Information The following sections describe some issues particular to Windows API calls that you must address in order to implement a solution. Background: Windows API Reference You can find the Windows API definitions for each of the functions used in this exercise in the C:\Exercises\LabVIEW Intermediate II\ Computer Name directory. Open each of the PDF files in this directory and browse the reference material in them. As you proceed through the exercise, refer to the references periodically to identify the meaning of each parameter you pass to the functions. The function information in these PDF files is from the Windows API Reference in the MSDN library. You can access the full Windows API Reference at: Note
http://msdn.microsoft.com/library/en-us/winprog/winprog/ windows_api_reference.asp.
Bit Masked Flags Some functions in the API contain a flags parameter that allows you to enable one or more options by masking the bits in an integer. The dwFlags parameter of the FormatMessage function is an example of this technique. In order to set a flag in LabVIEW, pass an integer constant with the appropriate size and value to the Call Library Function node. Remember that you can change the way a numeric constant is represented to make it easier to enter the flag value. For example, the specification for the FormatMessage function gives the flags in hexadecimal format, you can set the format of your numeric constant to hexadecimal and then enter the value directly. If you need to set multiple flags in a flags parameter, you can use a Bitwise Or to combine multiple flags. In LabVIEW, the Or function is a polymorphic function which automatically becomes a Bitwise Or if you wire two integers to it. Data Types Windows API and other DLL function specifications often refer to many data types which have different names in LabVIEW. The following table lists LabVIEW types for some of the Windows data types used in this exercise. For a more complete list, the Call DLL example in the NI Example Finder provides a complete data type conversion list, as well as examples for each data type. The Windows Data Type reference is also a useful reference, it can be found at: http://msdn.microsoft.com/library/en-us/ winprog/winprog/windows_data_types.asp.
LabVIEW Intermediate II Course Manual
1-14
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
Table 1-2. Data Type Conversion
Windows Data Type
LabVIEW Data Type
LPTSTR
String (Pass as C String Pointer)
DWORD
U32
LPDWORD
U32 (Pass by pointer)
BOOL
I32
va_list*
Varies (Use Adapt to Type)
LPCVOID
Varies (Use Adapt to Type)
String Types Many Windows API functions support two methods for representing strings. The first method is ASCII, in which each character in a string is represented by a single character. Traditional ASCII has a 128 character set, which contains all of the upper and lowercase letters, as well as other common symbols and a set of control characters. LabVIEW typically uses ASCII to represent strings. The second method uses “wide” strings, which is another term for Unicode string representation (UTF-16 encoding). Unicode requires two bytes for each character, and allows for a much larger character set than traditional ASCII. Unicode is not natively supported in LabVIEW, but it is possible to use Unicode through add on libraries or calls to external functions. Windows API functions which deal with strings often have two versions present in the DLL, marked with an “A” for ASCII and a “W” for wide. For example, there are two GetComputerName functions in kernel32.dll, GetComputerNameA and GetComputerNameW. In most cases, you should use the “A” version of the function in LabVIEW.
Implementation 1. Create the front panel shown in Figure 1-1.
Figure 1-1. Computer Name Front Panel
© National Instruments Corporation
1-15
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
❑ Create a blank VI and save the VI as Computer Name.vi in the C:\Exercises\LabVIEW Intermediate II\Computer Name directory.
❑ Create the Buffer Size control as described in Table 1-1. ❑ Create the Computer Name indicator as described in Table 1-1. 2. Create a type defined enumerated type control to control the state machine. ❑ Place an enum control on the front panel. ❑ Label the enum Computer Name. ❑ Right-click the Computer Name control and select Advanced» Customize from the shortcut menu to open the Control Editor. ❑ Right-click the control and select Edit Items from the shortcut menu. ❑ Enter the items as shown in Figure 1-2 and click the OK button.
Figure 1-2.
❑ Select Type Def. from the Type Def. Status pull-down menu.
LabVIEW Intermediate II Course Manual
1-16
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
❑ Save the control as Computer Name.ctl in the C:\Exercises\ LabVIEW Intermediate II\Computer Name directory. ❑ Close the Control Editor and click Yes when prompted to replace the original with the customized control. ❑ From the block diagram, right-click the Computer Name control and select Change to Constant from the shortcut menu. ❑ Set the value of the Computer Name constant to Get Computer Name. 3. Build a state machine to control the program as shown in Figure 1-3.
Figure 1-3. State Machine
❑ Place a While Loop on the block diagram. ❑ Place a Case structure inside the While Loop. ❑ Wire the Computer Name constant to the case selector terminal through a shift register on the While Loop. ❑ Right-click the Case structure and select Add Case for Every Value from the shortcut menu to add a case for every value in the Computer Name control. ❑ Wire the Buffer Size control to the state machine as shown in Figure 1-3.
© National Instruments Corporation
1-17
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
4. Call the GetComputerName function. ❑ Open the GetComputerName function reference from C:\Exercises\LabVIEW Intermediate II\ Computer Name\getcomputername.pdf and identify the
prototype and parameters for the function. ❑ Place a Call Library Function Node in the Get Computer Name case of the Case structure. ❑ Double-click the Call Library Function Node to open the Call Library Function dialog box. ❑ Click the Browse button and navigate to C:\WINDOWS\ system32\kernel32.dll. ❑ Select GetComputerNameA from the Function Name pull-down menu. ❑ Select Reentrant from the Run in UI Thread pull-down menu. Note Because the Windows API functions are reentrant (multi-threaded), calling GetComputerName in UI thread functions correctly, except the error is not stored in the proper memory location for GetLastError to access it.
❑ Select stdcall (WINAPI) from the Calling Conventions pull-down menu. ❑ Leave parameter set to return type. ❑ Select Numeric from the Type pull-down menu. ❑ Click the Add a Parameter After button. ❑ Enter lpBuffer in the Parameter text box. ❑ Select String from the Type pull-down menu. ❑ Click the Add a Parameter After button. ❑ Enter lpnSize in the Parameter text box. ❑ Select Numeric from the Type pull-down menu. ❑ Select Unsigned 32-bit Integer from the Data Type pull-down menu. ❑ Select Pointer to Value from the Pass pull-down menu.
LabVIEW Intermediate II Course Manual
1-18
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
❑ Confirm that the function prototype matches Figure 1-4. ❑ Click the OK button.
Figure 1-4. GetComputerName Call Library Function
5. Create the Get Computer Name case as shown in Figure 1-5.
Figure 1-5. Get Computer Name Case
❑ Place a numeric constant with a representation of U8 in the Get Computer Name case. Label the constant Byte. ❑ Place an Initialize Array function in the Case structure. ❑ Place a Byte Array To String function in the Case structure. ❑ Place an Equal To 0? function in the Case structure.
© National Instruments Corporation
1-19
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
❑ Place a Select function in the Case structure. ❑ Place the Computer Name indicator inside the Case structure. ❑ Create two constants from the enum terminal on the right side of the Case structure. Set one value to Stop and the other to Handle Error. ❑ Place a False constant inside the Case structure. ❑ Wire the case as shown in Figure 1-5. 6. Call the GetLastError function ❑ Open the GetLastError function reference from C:\Exercises\LabVIEW Intermediate II\ Computer Name\getlasterror.pdf and identify the
prototype and parameters for the function. ❑ Place a Call Library Function Node in the Handle Error case. ❑ Double-click the Call Library Function Node to open the Call Library Function dialog box. ❑ Click the Browse button and select C:\WINDOWS\system32\ kernel32.dll. ❑ Select GetLastError from the Function Name pull-down menu. ❑ Select Reentrant from the Run in UI Thread pull-down menu. ❑ Select stdcall (WINAPI) from the Calling Conventions pull-down menu. ❑ Select Numeric from the Type pull-down menu. ❑ Select Unsigned 32-bit Integer from the Type pull-down menu. ❑ Confirm that the function prototype matches Figure 1-6. ❑ Click the OK button.
LabVIEW Intermediate II Course Manual
1-20
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
Figure 1-6. GetLastError Call Library Function
7. Call the FormatMessage function. ❑ Open the FormatMessage function reference from C:\Exercises\LabVIEW Intermediate II\ Computer Name\formatmessage.pdf and identify the
prototype and parameters for the function. ❑ Place a Call Library Function Node in the Handle Error case. ❑ Double-click the Call Library Function Node to open the Call Library Function dialog box. ❑ Click the Browse button and select C:\WINDOWS\system32\ kernel32.dll. ❑ Select FormatMessageA from the Function Name pull-down menu. ❑ Select Reentrant from the Run in UI Thread pull-down menu. ❑ Select stdcall (WINAPI) from the Calling Conventions pull-down menu. ❑ Select Numeric from the Type pull-down menu. ❑ Select Unsigned 32-bit Integer from the Type pull-down menu. ❑ Click the Add a Parameter After button.
© National Instruments Corporation
1-21
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
❑ Enter dwFlags in the Parameter text box. ❑ Select Unsigned 32-bit Integer from the Type pull-down menu. ❑ Click the Add a Parameter After button. ❑ Enter lpSource in the Parameter text box. ❑ Select Adapt to Type from the Type pull-down menu. ❑ Select Pointers to Handles from the Data Format pull-down menu. ❑ Click the Add a Parameter After button. ❑ Enter dwMessageId in the Parameter text box. ❑ Select Unsigned 32-bit Integer from the Type pull-down menu. ❑ Click the Add a Parameter After button. ❑ Enter dwLanguageId in the Parameter text box. ❑ Select Unsigned 32-bit Integer from the Type pull-down menu. ❑ Click the Add a Parameter After button. ❑ Enter lpBuffer in the Parameter text box. ❑ Select String from the Type pull-down menu. ❑ Click the Add a Parameter After button. ❑ Enter nSize in the Parameter text box. ❑ Select Unsigned 32-bit Integer from the Type pull-down menu. ❑ Click the Add a Parameter After button. ❑ Enter Arguments in the Parameter text box. ❑ Select Adapt to Type from the Type pull-down menu. ❑ Select Pointers to Handles from the Data Format pull-down menu. ❑ Confirm that the function prototype matches Figure 1-7. ❑ Click the OK button.
LabVIEW Intermediate II Course Manual
1-22
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
Figure 1-7. FormatMessage Call Library Function Note The terminals corresponding to the arguments with type Void are blank until wired because void parameters accept any type of data
8. Create the Handle Error case shown in Figure 1-8.
Figure 1-8. Handle Error Case
❑ Place a numeric constant with a representation of U8 in the Handle Error case. Label the constant Byte. ❑ Place a numeric constant with a representation of I32 in the Case structure. Label the constant String Size. ❑ Set the value of the String Size constant to 1000.
© National Instruments Corporation
1-23
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
❑ Place an Initialize Array function in the Case structure. ❑ Place a Byte Array To String function in the Case structure. ❑ Place a numeric constant with a representation of U32 in the Case structure. Label the constant Null Value. ❑ Place an Or function in the Case structure. ❑ Create a constant from the enum terminal on the right side of the Case structure and set the value to Stop. ❑ Place a False constant inside the Case structure. ❑ Place a numeric constant with a representation of U32 in the Case structure. ❑ Right-click the numeric constant and select Format and Precision from the shortcut menu. ❑ Configure the constant as shown in Figure 1-9.
Figure 1-9. Numeric Constant Properties
❑ Set the value of the constant to 00000200. ❑ Label the constant Ignore Arguments.
LabVIEW Intermediate II Course Manual
1-24
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
❑ Create a copy of the Ignore Arguments constant. ❑ Change the label of the new constant to System Message. ❑ Set the value of the System Message constant to 00001000. ❑ Place a One Button Dialog function in the Case structure. ❑ Wire the case as shown in Figure 1-8. 9. Create the Stop case as shown in Figure 1-10.
Figure 1-10. Stop Case
❑ Select the Stop case of the Case structure. ❑ Create a constant from the enum tunnel on the right side of the Case structure and set the value to Stop. ❑ Create a constant from the stop tunnel on the right side of the Case structure and set the value to True. 10. Save the VI.
Testing 1. Test the VI with an appropriate buffer size. ❑ Switch to the front panel of the VI. ❑ Run the VI with the default Buffer Size (256). ❑ The name of your computer should display in the Computer Name indicator.
© National Instruments Corporation
1-25
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
2. Verify that the correct computer name displays. ❑ Locate My Computer on the desktop of your computer or in Windows Explorer. ❑ Right-click My Computer and select Properties from the shortcut menu. ❑ Select the Computer Name tab and verify that the Full Computer Name matches the value the VI returns. Note
The case of the names does not need to match. 3. Test the error handling in the VI. ❑ Set the Buffer Size control to 1 and run the VI. ❑ Verify that the VI displays The file name is too long. as an error message.
The error message that displays for this VI is the description for the Windows error message ERROR_BUFFER_OVERFLOW (System Error 111). Refer to Tip
http://msdn.microsoft.com/library/en-us/debug/base/ system_error_codes.asp for more information about system error codes and their
descriptions.
End of Exercise 1-1
LabVIEW Intermediate II Course Manual
1-26
ni.com
Lesson 1
Calling Shared Libraries in LabVIEW
Summary •
Dynamic linking is a mechanism that links applications to libraries at run time.
•
The Call Library Function Node offers easy access to DLLs.
•
To call a function in a DLL, you need to know the following:
© National Instruments Corporation
–
The calling convention used.
–
The data type returned by the function.
–
The parameters to be sent to the function, their types, and the order in which they must be passed.
–
The location of the DLL on the computer.
–
Whether the function can be called safely by multiple threads simultaneously.
1-27
LabVIEW Intermediate II Course Manual
Lesson 1
Calling Shared Libraries in LabVIEW
Notes
LabVIEW Intermediate II Course Manual
1-28
ni.com
2
VI Server
You can access the VI Server through block diagrams, ActiveX technology, and the TCP protocol to communicate with VIs and other application instances so you can programmatically control VIs and LabVIEW. You can perform VI Server operations on a local computer or remotely across a network.
Topics A. What is VI Server? B. VI Server Programming Model C. VI Server Functions D. Remote Communication E. Dynamically Calling and Loading VIs
© National Instruments Corporation
2-1
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
A. What is VI Server? The VI Server is an object-oriented, platform-independent technology that provides programmatic access to LabVIEW and LabVIEW applications. Use the VI Server to perform the following programmatic operations: •
Call a VI remotely.
•
Configure a LabVIEW application instance to be a server that exports VIs you can call from other instances of LabVIEW on the Web. For example, if you have a data acquisition application that acquires and logs data at a remote site, you can sample that data occasionally from your local computer. By changing your LabVIEW preferences, you can make some VIs accessible on the Web so that transferring the latest data is as easy as a subVI call. The VI Server handles the networking details. The VI Server also works across platforms, so the client and the server can run on different platforms.
•
Edit the properties of a VI and LabVIEW. For example, you can dynamically determine the location of a VI window or scroll a front panel so that a part of it is visible. You also can programmatically save any changes to disk.
•
Update the properties of multiple VIs rather than manually using the File»VI Properties dialog box for each VI.
•
Retrieve information about an application instance, such as the version number and edition. You also can retrieve environment information, such as the platform on which LabVIEW is running.
•
Dynamically load VIs into memory when another VI needs to call them, rather than loading all subVIs when you open a VI.
•
Create a plug-in architecture for the application to add functionality to the application after you distribute it to customers. For example, you might have a set of data filtering VIs, all of which take the same parameters. By designing the application to dynamically load these VIs from a plug-in directory, you can ship the application with a partial set of these VIs and make more filtering options available to users by placing the new filtering VIs in the plug-in directory.
•
Control front panel objects.
VI Server Clients The VI Server has a set of methods and properties that are accessible through the different clients, as shown in Figure 2-1. The different client interfaces are ActiveX Automation client, TCP/IP client, and LabVIEW functions that allow LabVIEW VIs to access the VI Server.
LabVIEW Intermediate II Course Manual
2-2
ni.com
Lesson 2
VI Server
VI Server
ActiveX Interface
Block Diagram Functions
TCP/IP
ActiveX Automation Client
LabVIEW
TCP/IP Client
Figure 2-1. VI Server Clients
•
Block Diagram Access—LabVIEW includes a set of built-in functions located on the Application Control palette you can use to access the VI Server on a local or remote computer.
•
Network Access—If you are using the VI Server on a remote computer, LabVIEW uses the TCP/IP protocol as the means of communication.
•
ActiveX Interface—ActiveX clients such as Visual Basic, Visual C++, and Excel applications can use the VI Server to run LabVIEW applications.
Application and VI Objects You access VI Server functionality through references to two main classes of objects—the Application object and the VI object. After you create a reference to one of these objects, you can pass the reference to a VI or function that performs an operation on the object. An Application refnum refers to a local or remote application instance. You can use Application properties and methods to change LabVIEW preferences and return system information. A VI refnum refers to a VI in an application instance. With a refnum to an application instance, you can retrieve information about the LabVIEW environment, such as the platform on which LabVIEW is running, the version number, or a list of all VIs currently in memory. You also can set information, such as the list of VIs exported to other application instances. When you create a refnum to a VI, LabVIEW loads the VI into memory. The VI stays in memory until you close the refnum, and the VI meets the following conditions: •
There are no other references to the VI.
•
The front panel of the VI is not open.
•
The VI is not a subVI of another VI in memory.
© National Instruments Corporation
2-3
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
With a refnum to a VI, you can update all the properties of the VI available in the File»VI Properties dialog box as well as dynamic properties, such as the position of the owning pane. You also can programmatically print the VI documentation, save the VI to another location, and export and import its strings to translate into another language.
B. VI Server Programming Model The programming model for VI Server applications is based on refnums. Refnums also are used in file I/O, network connections, and other objects in LabVIEW. Typically, you open a refnum to an application instance or to a VI. You then use the refnum as a parameter to other VIs. The VIs get (read) or set (write) properties, execute methods, or dynamically load a referenced VI. Finally, you close the refnum, which releases the referenced VI from memory. Figure 2-2 illustrates the VI Server programming model.
Create Reference to Object
Operate on Properties or Methods
Close Reference to Object
Check for Errors
Figure 2-2. VI Server Programming Model
Use the following general procedure to create a VI Server application. 1. (Optional) Configure the VI Server. 2. Use the Open VI Reference function to open a reference to a VI on the local or remote computer that already exists in memory for the application instance, or to dynamically load a VI from disk. Use the Open Application Reference function to open a reference to the local or remote application you are accessing through the server or to access a remote application instance. 3. Use the Property Node to get or set properties or the Invoke Node to get or set methods. You also can use a Call By Reference Node to call a dynamically loaded VI.
LabVIEW Intermediate II Course Manual
2-4
ni.com
Lesson 2
VI Server
4. Use the Close Reference function to close any open references. 5. Check for errors.
C. VI Server Functions Use the following Application Control functions and nodes to build VI Server applications: •
Open Application Reference—Opens a reference to a local or remote application instance.
•
Open VI Reference—Opens a reference to a VI on the local or remote computer or dynamically loads a VI from disk.
•
Property Node—Gets and sets VI, object, or application properties.
•
Invoke Node—Invokes methods on a VI, object, or application.
•
Call By Reference Node—Calls a dynamically loaded VI.
•
Close Reference—Closes open references to the VI, object, or application you accessed using the VI Server.
Open Application Reference Function The Open Application Reference function returns a reference to a VI Server application running on the specified computer. If you specify an empty string for machine name, it returns a reference to the local LabVIEW application in which this function is running. If you do specify a machine name, it attempts to establish a TCP connection with a remote VI Server on that machine on the specified port. You can use this function to get references to global VIs and custom controls. machine name can be in dotted decimal notation, such as 123.23.45.100, or domain name notation, such as remotemachine.ni.com. The port number input allows you to specify multiple servers on a single computer. You use the application reference output as an input to Property Nodes and Invoke Nodes to get or set properties and invoke methods on the LabVIEW application. You also use application reference as the input to the Open VI Reference function to get references to VIs that are running in the LabVIEW application.
Open VI Reference Function The Open VI Reference function returns a reference to a VI, control, or global variable specified by a name string or path to the location of the VI on disk.
© National Instruments Corporation
2-5
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
You can get references to VIs in another LabVIEW application by wiring an application reference, obtained from the Open Application Reference function, to this function. If you leave the application reference input unwired, the Open VI Reference function refers to the local installation of LabVIEW.
Property Nodes Use the Property Node to get and set various properties on an application or VI. Select properties from the node by using the Operating tool to click the property terminal or by right-clicking the white area of the node and selecting Properties from the shortcut menu. You can read or write multiple properties using a single node. However, some properties are not readable and some are not writable. Use the Positioning tool to resize the Property Node to add new terminals. A small direction arrow to the right of the property indicates a property you read. A small direction arrow to the left of the property indicates a property you write. Right-click the property and select Change to Read or Change to Write from the shortcut menu to change the operation of the property. The node executes from top to bottom. The Property Node does not execute if an error occurs before it executes, so always check for the possibility of errors. If an error occurs in a property, LabVIEW ignores the remaining properties and returns an error. The error out cluster contains information about which property caused the error.
Invoke Nodes Use the Invoke Node to perform actions, or methods, on an application or VI. Unlike the Property Node, a single Invoke Node executes only a single method on an application or VI. Select a method by using the Operating tool to click the method terminal or by right-clicking the white area of the node and selecting Methods from the shortcut menu. You also can create an Invoke Node by right-clicking the object, selecting Create»Invoke Node, and selecting a method from the shortcut menu.
Close Reference Function The Close Reference function releases the application or VI reference. If you close a reference to a specified VI and there are no other references to that VI, LabVIEW can unload the VI from memory. This function does not prompt you to save changes to the VI. By design, VI Server actions should avoid causing user interaction. You must use the Save:Instrument method to save the VI programmatically.
LabVIEW Intermediate II Course Manual
2-6
ni.com
Lesson 2
VI Server
If you do not close the application or VI reference with this function, the reference closes automatically when the top-level VI associated with this function finishes execution. However, it is a good programming practice to conserve the resources involved in maintaining the connection by closing the reference when you finish using it. Note
Properties of the Application or VI Classes Property Nodes are used to modify properties of the LabVIEW application or VI Object defined with the Open Application Reference or Open VI Reference function. There are different properties available in the Application Class and the VI Class.
Application Class Properties Most Application Class properties are read only. They allow you to check a whole range of parameters, such as what VIs are loaded into memory, the operating system, and so on. The properties that can be written are for the printing options, which allow you to customize what prints and what does not print. The following block diagram opens an application session to the local installation of LabVIEW and reads four properties of the LabVIEW application: •
The display properties of all the display monitors
•
The name of the operating system, such as Windows 2000, Windows XP, and so on
•
The version of the operating system
•
Whether the LabVIEW Web Server is active
You can use this information to ensure that the computer running LabVIEW is configured correctly and prompt the user to reconfigure the computer if necessary.
© National Instruments Corporation
2-7
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
VI Object Properties Many of the properties of the VI that are exposed correspond to the properties available in the VI Properties dialog box. You can access the VI Properties dialog box by selecting File»VI Properties. Most of the properties are read and write. Properties such as name, path, type, metrics, and so on are read only. Some properties are transient, such as window position, title, and so on. After you select a property, you can get help information about it by right-clicking the property and selecting Help for Property Name from the shortcut menu, where Property Name is the name of the property.
Tip
Methods of the Application or VI Classes Invoke Nodes are used to perform functions on the LabVIEW application or VI Object defined with the Open Application Reference or Open VI Reference function. There are different methods available in the Application Class and the VI Class.
Application Class Methods When you place the Invoke Node on the block diagram you can access the Application class methods. You do not have to wire an Application reference to the Invoke Node to access the Application class methods because the node defaults to the current Application if reference is unwired. Some of the important methods available are Mass Compile, Get VI Version, Bring To Front, and so on. The Mass Compile method loads and compiles all the VIs in a directory and all its subdirectories. The Get VI Version method gets the version of LabVIEW in which the VI was last saved. The Bring To Front method brings the application windows to the front.
VI Object Methods When you wire the VI reference to the Invoke Node, you can access the VI class methods. Some of the important methods exported by the VI Server are Export VI Strings, Set Lock State, Run VI, Save Instrument, and so on. The Export VI Strings method exports strings pertaining to VI and front panel objects to a tagged text file. The Set Lock State method sets the lock state of a VI. The Run VI method starts VI execution. The Save:Instrument method saves a VI.
LabVIEW Intermediate II Course Manual
2-8
ni.com
Lesson 2
VI Server
After you select a method, you can get help information about it by right-clicking the method and selecting Help for Method Name from the shortcut menu, where Method Name is the name of the method.
Tip
VI Server Configuration To configure the VI Server, select Tools»Options on the server computer and select VI Server: Configuration from the Category list to display the VI Server: Configuration page. If a target in a LabVIEW project supports the VI Server, you also can right-click the target, such as My Computer, select Properties from the shortcut menu, and select VI Server: Configuration from the Category list to display this page. If you are using a project, display this page from the Options dialog box to configure the VI Server for the main application instance. To configure the VI Server for a target, display this page from the Properties dialog box for the target. The default VI Server settings are ActiveX enabled and TCP/IP disabled. This page includes the following components. •
Protocols—Sets the protocols for the VI Server. –
TCP/IP—Enables VI server support for TCP/IP. If you allow remote applications to connect using TCP/IP, you also should specify which machine addresses can access the VI Server on the VI Server: Machine Access page of the Options dialog box. This checkbox is unchecked by default. •
Port—Sets the TCP/IP port at which the VI server listens for requests. By default, this port number is 3363, which is a registered port number reserved for use by LabVIEW. You need to change this number if you want to run multiple application instances on the machine, each with its own VI Server running. In that case, each application instance must have a unique VI Server port number. You also can use the Server:Port property to set the LabVIEW VI Server port programmatically.
•
Service name—Sets the service name for the VI Server TCP Instance. If you display this page from the Options dialog box, this service name is Main Application Instance by default. If you display this page from the Properties dialog box for a target, the service name is target name/VI Server by default. If Use default is checked, you cannot edit this field. –
© National Instruments Corporation
Use default—Sets Service name to its default value of Main Application Instance. This checkbox is checked by default. To edit Service name, remove the checkmark from the checkbox.
2-9
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
– •
ActiveX—(Windows) Enables VI server support for ActiveX Automation. This checkbox is checked by default.
Accessible Server Resources—Indicates the tasks that remote applications can accomplish. –
VI calls—Allows remote applications to call VIs exported through the VI Server. If you allow remote applications access to VIs, specify which VIs can be exported. This checkbox is checked by default.
–
VI properties and methods—Allows remote applications to read and set the properties of VIs through the VI Server. If you allow remote applications access to VIs, specify which VIs can be exported. This checkbox is checked by default.
–
Application methods and properties—Allows remote applications to read and set the properties of the VI Server. This checkbox is checked by default.
–
Control methods and properties—Allows remote applications to read and set the properties of controls in exported VIs. You also can call methods that are usable with controls. This checkbox is checked by default.
Machine Access Configuration When you allow remote applications to access the VI Server using the TCP/IP protocol, you should specify which Internet hosts have access to the server. To configure the TCP/IP access permissions select Tools»Options on the server computer and select VI Server: Machine Access from the Category list to display the VI Server: Machine Access page. Use this page to control machine access to VIs through the VI Server. If you are using a project, display this page from the Options dialog box to control machine access for the main application instance. To control machine access for a target, display this page from the Properties dialog box for the target. When a remote LabVIEW application attempts to open a connection to the VI Server, the VI Server compares the IP address to the entries in the Machine access list to determine whether it should grant access. If an entry in the Machine access list matches the IP address, the VI Server permits or denies access based on how you set up the entry. If no entry matches the IP address, the VI Server denies access. When you add new Machine access list entries, edit existing entries, or remove entries, use the correct syntax, order, and wildcards in the entries. An Internet (IP) address, such as 130.164.15.138, might have more than one domain name associated with it. The conversion from a domain name
LabVIEW Intermediate II Course Manual
2-10
ni.com
Lesson 2
VI Server
to its corresponding IP address is called name resolution. The conversion from an IP address to its domain name is called name lookup. A name lookup or a resolution can fail when the system does not have access to a DNS (Domain Name System) server or when the address or name is not valid. The VI Server: Machine Access page includes the following components: •
Machine access list—Lists machines that do and do not have access to the VI Server. You also can use the Server:TCP/IP Access List property to list programmatically the TCP/IP addresses of machines that may access the VI server.
•
Machine name/address—Enter the name or IP address of the machine you want to add to the Machine access list.
•
Allow Access—Allows access to the machine(s) selected in Machine access list.
•
Deny Access—Denies access to the machine(s) selected in Machine access list.
•
Add—Adds a new entry to the Machine access list. The new entry appears below the selected entry in the Machine access list.
•
Remove—Removes the selected entry from the Machine access list.
Exported VIs Configuration When you allow remote applications to access VIs through the VI Server, you should specify which VIs these applications can access. To configure the exported VIs, select Tools»Options on the server computer and select VI Server: Exported VIs from the Category list to display the VI Server: Exported VIs page. Configure the exported VIs using the following components of the page: •
Exported VIs—Lists the VIs that can be exported.
•
Exported VI—Enter a VI to list in Exported VIs.
•
Allow Access—Allows access to the VI(s) selected in Exported VIs. This option is selected by default.
•
Deny Access—Denies access to the VI(s) selected in Exported VIs.
•
Add—Adds a new entry to Exported VIs.
•
Remove—Removes the selected entry from Exported VIs.
If an entry is allowed access to VIs, a checkmark appears next to the entry. If an entry is denied access to VIs, an X appears next to the entry. If no symbol appears next to the entry, the syntax of the entry is incorrect. Each entry in the Exported VIs list describes a VI name or a VI path and can contain wildcard characters. When a remote client tries to access a VI,
© National Instruments Corporation
2-11
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
the VI Server examines the Exported VIs list to determine whether to grant access to the requested VI. If an entry in the list matches the requested VI, the server allows or denies access to that VI based on how you set up that entry. If a subsequent entry also matches the VI, its access permission is used in place of the previous permission. If there is not a VI in the list that matches the requested VI, access to the VI is denied. You can use the ?, *, and ** characters as wildcard characters. The ? and * wildcards do not include the path separator. ** includes the path separator.
LabVIEW Intermediate II Course Manual
2-12
ni.com
Lesson 2
Exercise 2-1
VI Server
Concept: VI Server Options
Goal Observe and set the VI server configuration options.
Description VI Server presents a potential security risk because other programs and/or computers can use it to call VIs, which can in turn be used to do almost anything with a computer. To protect your computer, VI server contains security options which allow you to select who can use VI server, which VIs users can access, how the VIs can be used, and what communication mechanisms can be used. This exercise demonstrates the VI Server configuration options and sets them to a configuration you can use to run the remaining exercises in the course. The security configuration set in this exercise is very light. Therefore, if you are completing these exercises on a development machine or any other important machine, increase the security level by only allowing certain machines to access VI Server or return the settings to the default values when you finish the course.
Implementation 1. Configure VI Server. ❑ Select Tools»Options and select VI Server: Configuration from the Category list. ❑ Make sure a checkmark appears in the ActiveX checkbox. ❑ Make sure that checkmarks appear in all the checkboxes under the Accessible Server Resources frame. ❑ Place a checkmark in the TCP/IP Configuration checkbox. Notice the Port number. 2. Configure Machine Access. ❑ Select VI Server: Machine Access from the Category list. ❑ Enter * in the Machine name/address field. Entering * in the Machine name/address field opens up VI Server Access to all computers. For security reasons, you should generally not do this on a production computer. Instead, add the machine name or IP address of each computer that needs access to VI server on this computer. Tip
© National Instruments Corporation
2-13
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
3. Configure Exported VIs. ❑ Select VI Server: Exported VIs from the Category list. ❑ Ensure * is entered in the Exported VIs list. ❑ Click the OK button to exit the options dialog.
End of Exercise 2-1
LabVIEW Intermediate II Course Manual
2-14
ni.com
Lesson 2
Exercise 2-2
VI Server
VI Statistics
Goal Open and use VI server references to Application and VI objects to gather information about all open VIs.
Scenario The Application VI Server object allows you to retrieve a list of all VIs in memory. Using this list, you can determine information about the VIs in memory. This information is useful for writing tools which track information about the VIs on your system. In this exercise you track VI usage statistics to identify the number of VIs running and the number of VIs in memory at any given time. Because VI Server has the ability to access application instances on remote machines, you can use this program to track the VI usage on any computer which allows you VI Server access.
Design Inputs and Outputs Table 2-1. VI Statistics Inputs and Outputs
Type
Name
Properties
Default Value
String Control
Machine Name
String
Empty (defaults to local machine)
Numeric Indicator
VIs Open
32-bit Integer
0
Numeric Indicator
VIs Running
32-bit Integer
0
Table
VI Report
Table, Column headers visible
Empty (Column headers only)
Program Flow 1. Acquire a reference to the LabVIEW Application object by using the Open Application Reference function. 2. Use this reference to access the ExportedVIs property, which gives you a list of each VI in memory. 3. Use a For Loop and the Open VI Reference function to get a reference to each VI in the list. 4. Using the VI reference, access the desired properties, in this case, Name, VIType and Exec.State. 5. Close each VI reference.
© National Instruments Corporation
2-15
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
6. Gather and display the data. 7. Close the application reference.
Property Descriptions Use the following properties in this program: ExportedVIs (Application Object)—This property returns an array of strings, which represent the name of all VIs in memory, if run on the local machine, or a list of all exported VIs in memory, if run on a remote machine. You must use this property instead of the AllVIs property to run the program on a remote machine. Notice that the strings contain only the names of the VIs, and not their paths. However, because the VIs are already guaranteed to be in memory, you only need the VI name to open a VI reference. Name (VI Object)—This property accesses the Name of the VI. You could use the names from the ExportedVIs property in place of this property, however using the property provides a consistent technique for accessing the VI data and also simplifies wiring. VIType (VI Object)—This property returns an enumeration containing the type of the VI. This property is useful because not all VIs are standard, executable VIs. Examples of other types of VIs include global variables, type definitions and custom controls. In this program, this property provides information for the VI report. Certain VI properties are valid for only some VI types, and therefore, it may be necessary to check the value of this property before accessing it. For example, if the program made use of any properties from the Execution group except for Exec.State, you would need to check this property before accessing the properties to ensure that the current VI reference is not a control or a global variable. Exec.State (VI Object)—This property returns an enumeration containing the execution state of the VI. In this program, you increment the number of running VIs if this property is equal to Run Top Level or Running.
LabVIEW Intermediate II Course Manual
2-16
ni.com
Lesson 2
VI Server
Implementation 1. Create the front panel as shown in Figure 2-3.
Figure 2-3. VI Statistics Front Panel
❑ Create a blank VI and save the VI as VI Statistics.vi in the C:\Exercises\LabVIEW Intermediate II\ VI Statistics directory.
❑ Create the Machine Name control as described in Table 2-1. ❑ Create the VIs Open indicator as described in Table 2-1. ❑ Create the VIs Running indicator as described in Table 2-1. ❑ Place a Table control on the front panel and label it VI Report. ❑ Right-click the VI Report table and select Change to Indicator from the shortcut menu. ❑ Right-click the VI Report table and select Visible Items»Column Headers from the shortcut menu. ❑ Enter VI Name, VI Type, and VI State as the first three column headers. ❑ Arrange the front panel as shown in Figure 2-3. © National Instruments Corporation
2-17
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
2. Access Application properties.
Figure 2-4. Application Properties
❑ Open the block diagram. ❑ Place an Open Application Reference function on the block diagram. ❑ Right-click the application reference output of the Open Application Reference function and select Create»Property» Application»Exported VIs in Memory from the shortcut menu to create an ExportedVIs Property Node. ❑ Place a Close Reference function on the block diagram. Make sure to leave plenty of space between the Property Node and the Close Reference function because you insert more code between them.
Tip
❑ Wire the block diagram as shown in Figure 2-4.
LabVIEW Intermediate II Course Manual
2-18
ni.com
Lesson 2
VI Server
3. Access VI properties.
Figure 2-5. VI Properties
❑ Place an Open VI Reference function on the block diagram. ❑ Right-click the vi reference output of the Open VI Reference function and select Create»Property»VI Name from the shortcut menu to create the VI Name Property Node. ❑ Expand the VI Name Property Node so that three items are available. ❑ Click the second item in the Property Node and select VI Type from the list. ❑ Click the third item in the Property Node and select Execution» State from the list. ❑ Place a Close Reference function on the block diagram. ❑ Wire the application reference output of the Open Application Reference function to the Open VI Reference function. ❑ Wire the vi reference output of the Open VI Reference function to the VI Property Node and the Close Reference function. ❑ Wire the error clusters through each of the nodes. ❑ Surround the code for the VI object with a For Loop as shown in Figure 2-6. ❑ Delete the wire from the Application Property Node to the Close Reference function and re-wire it through the border of the For Loop.
© National Instruments Corporation
2-19
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
Wiring the nodes before adding the For Loop allows the For Loop to identify which wires it needs and prevents having to delete and re-wire most of the wires. However, the For Loop does not automatically create a tunnel for application reference because it is not modified inside the For Loop.
Tip
❑ Replace the application reference and error tunnels on the For Loop with Shift Registers. Note When you pass references to a For Loop, always use shift registers instead of tunnels. If the For Loop executes 0 times, a tunnel returns an empty reference, which causes a memory leak and an error when you try to close the reference. You should always use shift registers to pass error wires through loops because tunnels discard errors which occur before the last iteration of the loop.
❑ Wire the output from the ExportedVIs Property Node to the vi path input of the Open VI Reference function. Leave indexing enabled on the For Loop tunnel. 4. Gather and display VI statistics.
Figure 2-6. VI Statistics Block Diagram
❑ Place a numeric constant with an I32 representation to the left side of the For Loop. Label the constant Number Running. ❑ Place an Increment function in the For Loop. ❑ Wire the value from the numeric constant through the increment function and the loop borders to the VIs Running indicator. Use shift registers to wire through the For Loop. ❑ Place a Case structure around the Increment function.
LabVIEW Intermediate II Course Manual
2-20
ni.com
Lesson 2
VI Server
❑ Wire the output of the Exec.State property to the case selector terminal. ❑ Right-click the Case structure and select Add Case After from the shortcut menu. ❑ Verify that the Run Top Level case of the Case structure is visible. Right-click the Case structure and select Swap Diagram With Case»Idle from the shortcut menu. ❑ Wire the numeric data through the Idle and Bad cases of the Case structure. ❑ Switch to the Run Top Level case, which should have the increment function in it, then right-click the Case structure and select Duplicate Case from the shortcut menu. This creates a Running case which contains an increment function. The Case structure increments the number in the VIs Running indicator if the VI is in the Run Top Level or the Running state. ❑ Place an Increment function to the right of the For Loop. ❑ Wire the iteration terminal of the For Loop to the Increment function through the border of the For Loop. Disable indexing on the tunnel. ❑ Place two Format Into String functions inside the For Loop. The Format Into String function determines the string representation of an enumerated value.
Tip
❑ Place a Build Array function inside the For Loop. ❑ Wire the remaining nodes as shown in Figure 2-6. 5. Handle errors. ❑ Place a Simple Error Handler VI on the block diagram. ❑ Wire the error clusters as shown in Figure 2-6. 6. Save the VI.
Testing 1. Run the VI. ❑ Switch to the front panel of the VI.
© National Instruments Corporation
2-21
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
❑ Close all other open VIs. ❑ Run the VI. 2. Run the VI with multiple VIs in memory. ❑ Open the solution to the LabVIEW Intermediate I project from C:\Solutions\LabVIEW Intermediate I\Completed Application\TLC Main.vi.
If you do not have the LabVIEW Intermediate I solution, you can use any other complex application. The solution to the Word Processor project in the C:\Solutions\ LabVIEW Intermediate II\Ex 3-5 directory is sufficient. Note
❑ Run the VI. ❑ Observe the results in the VI Report. 3. Test the VI on a remote system. ❑ Determine the network address of a target computer near you and enter it in the Machine Name control. In most cases, you can use the Computer Name, which you found in Exercise 1-1, as a network address. If this name does not work, find the IP address of the computer by using the String to IP and IP to String functions.
Tip
❑ Ensure that the VI Server settings on the target computer are configured as described in Exercise 2-1. ❑ Open one or more VIs on the target computer. ❑ Run the VI. All exported VIs in memory on the target computer should display.
Challenge Add statistical information for the VI priority, VI execution system, and/or state of the front panel to your table. Remember that not all properties are valid for all types of VIs. Use the context help to identify which types of VIs a property applies to and the VIType property to determine which VIs have the property, otherwise you receive an error.
End of Exercise 2-2
LabVIEW Intermediate II Course Manual
2-22
ni.com
Lesson 2
VI Server
D. Remote Communication An important aspect of both Application and VI refnums is their network transparency. This means you can open refnums to objects on remote computers in the same way you open refnums to those objects on your computer. After you open a refnum to a remote object, you can treat it in exactly the same way as a local object, with a few restrictions. For operations on a remote object, the VI Server sends the information about the operation across the network and sends the results back. The application looks almost identical regardless of whether the operation is remote or local. To open an application reference to a remote version of LabVIEW, you must specify the machine name input of the Open Application Reference function. Then LabVIEW attempts to establish a TCP connection with a remote VI Server on that computer on the specified port.
Example—Accessing a Remote VI Property Figure 2-7 shows how to access the properties of a VI object on a remote computer. The Open Application Reference function opens a connection to a remote computer. The Open VI Reference function opens a VI on the specified remote computer. The Property Node opens the front panel of the specified VI. The Invoke Node runs the specified VI and waits for execution to complete before exiting the function. Because the Auto Dispose Ref is set to False, a Close Reference function must be used to release the reference and the parallel data space.
Figure 2-7. Accessing a Remote VI Property
Open VI Reference Inputs VI path accepts a string containing the name of the VI you are referencing or a path containing the complete path to the VI you are referencing. The function loads the specified VI into memory, if it is not already open, and returns a reference to this VI. If you wire a name string, the VI must already be in memory. If you wire a path and a VI of the same name is already in memory, the function returns a reference to the open VI, regardless of
© National Instruments Corporation
2-23
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
whether its path is the same as the input. If the VI is not in memory, the VI must be at the specified path for this function to succeed. application reference is a reference to a LabVIEW application. The default is a reference to an application on the local instance of LabVIEW. If wired and the reference is to a remote instance of LabVIEW, the remote instance of LabVIEW is queried to return the VI reference. Refer to the LabVIEW Help for more information about using the Open VI Reference function.
LabVIEW Intermediate II Course Manual
2-24
ni.com
Lesson 2
Exercise 2-3
VI Server
Concept: Remote Run VI
Goal Build a VI that programmatically opens and runs another VI on a remote computer.
Description You have seen how the Application refnum runs transparently over a network. In this exercise, use VI Server to run a VI remotely. The techniques in this exercise show how to use VI Server to open and run a VI on a remote machine. VI Server operates the same whether it is on a network or a local machine.
Implementation 1. Open the Remote Run VI located in the C:\Exercises\LabVIEW Intermediate II\Remote Run directory. The front panel is already built.
Figure 2-8. Remote Run VI Front Panel Tip To allow selection of .llb files, right-click the file browser icon, select Browse Options from the shortcut menu and place a checkmark in the Treat LLBs as folders checkbox.
© National Instruments Corporation
2-25
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
2. Build the following block diagram.
Figure 2-9. Remote Run VI Block Diagram
❑ Place the Open Application Reference function on the block diagram. ❑ Wire the Machine Name string control to the machine name input. You can leave the string control empty if you are running the exercise on a local computer. If you want to call a VI on a remote computer you need to supply an IP address or the domain name for the remote computer. If you do not call a remote VI, you do not need to use this function. ❑ Place the Open VI Reference function on the block diagram. ❑ Wire the VI to execute path control, which determines the VI to execute, to the vi path input of the Open VI Reference function. ❑ Place the Close Reference function on the block diagram. This function closes the VI reference to the VI you are calling. ❑ Place a Property Node on the block diagram. ❑ Wire the Open VI Reference function to the Property Node. ❑ Click the property terminal and select Front Panel Window»Open from the list. ❑ Right-click the Property Node and select Change All to Write from the shortcut menu. ❑ Wire a True Boolean constant to the Front Panel Window Open property terminal.
LabVIEW Intermediate II Course Manual
2-26
ni.com
Lesson 2
VI Server
❑ Place an Invoke Node on the block diagram. ❑ Wire the VI reference to the Invoke Node. ❑ Click the method terminal and select Run VI from the list. ❑ Wire the True Boolean constant to the Wait Until Done property terminal and a False Boolean constant to the Auto Dispose Ref property terminal. ❑ Place a Simple Error Handler VI on the block diagram. ❑ Place a Case structure on the block diagram. Use the Case structure to select whether the front panel of the called VI remains open when the VI completes execution. The True case contains a Property Node that has a False Boolean constant wired to the Front Panel Window Open property terminal. This closes the front panel of the called VI if it is selected. ❑ Leave the False case empty and wire the VI refnum and the error cluster through the case. 3. Save the VI.
Testing 1. Run the VI on the local computer. This VI opens a reference to the Frequency Response VI located in the C:\Exercises\LabVIEW Intermediate II\Remote Run directory. The front panel of the VI is opened by accessing the Front Panel Open property of the VI. Then, the Run method runs the VI. Because the Wait Until Done property is True, this VI waits for the Frequency Response VI to complete execution. After exiting the Frequency Response VI, the front panel remains open or closes depending on the position of the front panel switch. Finally, the Close Reference function closes the VI reference, freeing the resources. 2. If time permits, complete the following optional and challenge steps, otherwise close the VI.
Optional If your computer is connected through TCP/IP to another computer that has LabVIEW and each computer has a unique IP address, you can run the Remote Run VI on one computer and have it call the Frequency Response VI on the other computer.
© National Instruments Corporation
2-27
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
1. Find a partner and exchange IP addresses. Decide which computer is the server. Complete the following steps on the server computer to set up the VI Server. ❑ Select Tools»Options and select VI Server: Configuration from the Category list to display the VI Server: Configuration page. Confirm that a checkmark appears in the TCP/IP Configuration checkbox and that a port number is entered. ❑ Select VI Server: TCP/IP Access from the Category list to display the VI Server: TCP/IP page. Enter the IP address of the client computer. Select the Allow Access option and click the Add button. ❑ Select VI Server: Exported VIs from the Category list to display the VI Server: Exported VIs page. Confirm that a wildcard (*) is allowed access. This allows the client computer, or any computer allowed access in the VI Server: TCP/IP Access section, to access any VIs on your computer. Click the OK button. 2. On the client computer, verify the path to the Frequency Response VI on the server computer. Enter the IP address of the server computer in the Machine Name control. 3. Run the Remote Run VI on the client computer. Does the VI behave as expected? Repeat steps 1 and 2, but reverse situations with your partner.
Challenge 1. Break into groups of three. Write a VI on the first computer that calls the Remote Run VI on the second computer, which then calls the Frequency Response VI on the third computer.
End of Exercise 2-3
LabVIEW Intermediate II Course Manual
2-28
ni.com
Lesson 2
VI Server
E. Dynamically Calling and Loading VIs You can dynamically load VIs instead of using statically linked subVI calls. A statically linked subVI is one you place directly on the block diagram of a caller VI. It loads at the same time the caller VI loads. Unlike statically linked subVIs, dynamically loaded VIs do not load until the caller VI loads them with the Open VI Reference. If you have a large caller VI, you can save load time and memory by dynamically loading the VI because the VI does not load until the caller VI needs it, and you can release it from memory after the operation completes. You also can use the VI Call Configuration dialog box to configure when to load the subVI. You use two types of VI refnums to dynamically load and call VIs in LabVIEW—strictly typed VI references and weakly typed VI references.
Using Strictly Typed VI Refnums •
Weakly Typed VI Reference—Includes a path to the VI. The type of the VI reference is not specified. If you create an indicator from the vi reference output of the Open VI Reference function, it looks like the control shown at left if it is weakly typed. Use a weakly typed VI references to pass a VI reference from an Open VI Reference function or an Application Reference function to a Property Node or an Invoke Node. Create a weakly typed VI reference by not specifying the type specifier VI Refnum input.
•
Strictly Typed VI Reference—Includes the connector pane information of the VI to be called. An indicator created from the vi reference output of the Open VI Reference function looks similar to the control shown at left if it is strictly typed. Use a strictly typed VI reference to dynamically call or load a VI. Create a strictly typed VI reference by specifying the type of the VI refnum. Wire a strictly typed VI refnum to the type specifier input of the Open VI Reference function to use. Strictly typed means that the connector terminals of a called VI and the data type they can accept are fixed. When you use the Open VI Reference function, it checks to see if the VI has the same connectors and data types as defined in the type specifier vi refnum input. If it does not, an error is generated.
The VI you specify for strictly typed refnums provides only the connector pane information. That is, no permanent association is made between the refnum and the VI. In particular, avoid confusing selecting the VI connector pane with getting a refnum to the selected VI. You specify a particular VI using the vi path input on the Open VI Reference function. Note
© National Instruments Corporation
2-29
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
Use the Call By Reference Node to dynamically call VIs. The Call By Reference Node requires a strictly typed VI refnum. The strictly typed VI refnum identifies the connector pane of the VI you are calling. It does not create a permanent association to the VI or contain other VI information, such as the name and location. You can wire the Call By Reference Node inputs and outputs just like you wire any other VI. Strictly typed VI refnums allow you to save load time and memory because the subVI does not load until the caller VI needs it and you can release the subVI from memory after the operation completes. The following block diagram shows how to use the Call By Reference Node to dynamically call the Frequency Response VI. The Call By Reference Node requires the use of the Open VI Reference and Close Reference functions, similar to the functions you use for the Property Node and the Invoke Node.
Programming Model Complete the following steps to call a VI dynamically using the VI Server. 1. Use the Open VI Reference function to specify the VI you want to call. The Open VI Reference function needs a strictly typed refnum in order to call the VI dynamically. To create a strictly typed refnum, select Controls»All Controls»Refnum and place a VI refnum on the front panel. Right-click the refnum and select Select VI Server Class»Browse from the shortcut menu. The Choose the VI to Open dialog box prompts you to select a VI. Select the VI that you want to replicate. Wire the strictly typed VI refnum to the type specifier VI Refnum input of the Open VI Reference function, as shown in the following figure.
LabVIEW Intermediate II Course Manual
2-30
ni.com
Lesson 2
VI Server
You also can create a strictly typed refnum by dragging and dropping a VI icon onto the refnum.
Tip
2. Use the Call by Reference Node to dynamically call the VI, as shown in the following figure. The Call By Reference Node works in the same way as calling a subVI. The only difference is that normally LabVIEW loads subVIs into memory when the application first opens, whereas with a Call by Reference Node, LabVIEW loads a VI into memory when the Open VI Reference function generates a reference to it.
A strictly typed refnum stores the connector pane information of the VI to which it is strictly typed. The type specifier displays its connector pane. Notice that you are opening a reference to a VI that has a connector pane of the type you have just selected. It does not store any link to the VI you select. 3. Use the Close Reference function to close the reference to the VI and add a Simple Error Handler VI, as shown in the following figure.
© National Instruments Corporation
2-31
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
Using Weakly Typed VI References You can use methods in LabVIEW to modify the values of controls in a VI and read the values of indicators using a weakly typed VI refnum, as shown in Figure 2-10.
Figure 2-10. Use Methods to Modify and Read Values
Using a Call by Reference Node and a strictly typed VI refnum instead, as show in Figure 2-11, you can write or read data to a VI in a much simpler manner.
Figure 2-11. Use Call By Reference Node to Write or Read Data
Behavior of Strictly Typed VI References When you open a strictly typed reference, the referenced VI is reserved for running and cannot be edited. For example, you can open a VI reference to a target VI and edit the VI. While this reference is open, you can open another reference—such as a
LabVIEW Intermediate II Course Manual
2-32
ni.com
Lesson 2
VI Server
strictly typed reference—and call the target VI as a subVI through the Call By Reference Node. However, until you close the strictly typed reference, editing operations through the Property and Invoke Nodes fail because the VI to which they refer is reserved for running by the strictly typed reference. Because opening a strictly typed VI reference puts the referenced VI in the reserved for running state, it means that the VI has been checked to make sure it is not corrupted, that it is not currently running as a top-level VI, that it has been compiled (if necessary), and a few other checks. A VI referenced by a strictly typed VI reference can be called using the Call By Reference Node at any moment without having to check all these conditions again. Thus, in the reserved for running state you cannot edit the VI or do anything to it that would change the way it would execute.
© National Instruments Corporation
2-33
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
Exercise 2-4
Dynamically Calling VIs
Goal Observe two different methods for calling VIs dynamically and learn the difference between strictly and weakly typed refnums.
Description This exercise demonstrates two ways to dynamically call a VI. The first method is to use a Weakly Typed VI Refnum. This technique is advantageous because it can be used to call any VI, regardless of the VI’s connector pane. However, passing data to the VI using a Weakly Typed VI Refnum is difficult. The second method uses a Strictly Typed VI Refnum. The Strictly Typed Refnum specifies the connector pane for the called VI, and allows you to use a Call By Reference node, which simplifies the passing of data to the dynamically called VI. However, a Strictly Typed VI Refnum only allows you to call VIs with a matching connector pane, therefore it is not as flexible as the Weakly Typed VI Refnum.
Instructions 1. Complete the VI front panel. ❑ Open the Dynamically Calling VIs VI located in the C:\Exercises\LabVIEW Intermediate II\ Dynamically Calling VIs directory.
❑ Place a VI Refnum to the left of the Boolean switch. Label the refnum Weakly Typed. ❑ Right-click the Weakly Typed VI refnum and check that the VI Server Class is VI in the shortcut menu. ❑ Place a VI Refnum to the right of the Boolean switch. Label the refnum Strictly Typed. ❑ Right-click the Strictly Typed VI refnum and select Select VI Server Class»Browse from the shortcut menu. ❑ Navigate to the Pop up VI in the C:\Exercises\LabVIEW Intermediate II\Dynamically Calling VIs directory and click the OK button. The refnum adapts to the connector pane of the Pop up VI.
LabVIEW Intermediate II Course Manual
2-34
ni.com
Lesson 2
VI Server
Figure 2-12. Weakly VS Strictly Typed Ref VI Front Panel
2. Complete the False case on the block diagram. ❑ Open the block diagram. ❑ Wire the Weakly Typed VI refnum to the Type Specifier input of the Open VI Reference function in the False case as shown in Figure 2-13.
Figure 2-13. Weakly VS Strictly Typed Ref VI Block Diagram False Case
The False case contains a VI reference to the Pop up VI. This VI reference opens the front panel of the VI using the Front Panel Window:Open property. The Set Control Value method passes values to the Numeric and String controls of the Pop up VI. The Run method runs the VI and waits until it completes execution. The Get All Control Values method returns the values of the front panel indicators of the Pop up VI. These values display on the front panel of
© National Instruments Corporation
2-35
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
this VI. Finally, the Close VI Reference function closes the front panel of the Pop up VI and releases the VI Reference. 3. Complete the True case on the block diagram. ❑ Wire the Strictly Typed VI refnum to the Type Specifier input of the Open VI Reference function. ❑ Place a Call By Reference Node on the block diagram. ❑ Wire the vi reference output of the Open VI Reference function to the reference input of the Call By Reference Node. The node adopts the connector pane of the Pop up VI, as shown at left. 4. Wire the remainder of the case as shown in Figure 2-14.
Figure 2-14. Block Diagram Code Inside the True Case
The True case uses a strictly typed reference. When you wire the strictly typed VI refnum for the Pop up VI to the Open VI Reference function, a strictly typed VI reference is generated that you can wire to the Call By Reference Node. 5. Save the VI.
Testing 1. Run the VI. ❑ Display the front panel and run the VI. ❑ Select the strictly typed reference and click the GO! button. The Pop up VI appears. It returns the value it receives or allows you to change the data. When you finish with the Pop up VI and click the DONE button, the values of the indicators from the Pop up VI display on the front panel. ❑ Run the VI again and select the weakly typed reference. Notice that the behavior is the same as the behavior of the strictly typed reference.
LabVIEW Intermediate II Course Manual
2-36
ni.com
Lesson 2
VI Server
Although both calling methods produce the same result, the Run method provides more flexibility and allows you to call a VI asynchronously. If you call a VI asynchronously by passing a false value to the Wait Until Done parameter of the Run method, the dynamically called VI executes independently of the calling VI. The calling VI continues its dataflow progression without waiting for the called VI to complete. The Call By Reference Node simplifies calling a VI dynamically, particularly when passing data to the subVI. The Call By Reference function requires a strictly typed reference that eliminates the possibility of a run-time type mismatch error. If you do not need the additional flexibility of the Run method, use the Call By Reference Node to reduce the complexity of your code.
End of Exercise 2-4
© National Instruments Corporation
2-37
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
Summary •
The VI Server allows you to programmatically access and control VIs or LabVIEW itself.
•
You can perform VI Server operations locally or on a remote computer.
•
For operations on a remote object, the VI Server is responsible for sending information across the network and returning results.
•
To configure the VI Server, you must select communication protocols, a list of exported VIs, and a list of clients that have access to the server.
•
A strictly typed VI refnum is a data type that contains the connector pane information of a VI.
•
Strictly typed VI refnums call VIs dynamically, saving load time and memory.
•
When you open a strictly typed reference, the referenced VI is reserved for running and cannot be edited.
LabVIEW Intermediate II Course Manual
2-38
ni.com
Lesson 2
VI Server
Notes
© National Instruments Corporation
2-39
LabVIEW Intermediate II Course Manual
Lesson 2
VI Server
Notes
LabVIEW Intermediate II Course Manual
2-40
ni.com
Calling Objects in LabVIEW
3
LabVIEW provides access to other Windows applications using .NET or ActiveX technologies. .NET refers to Microsoft's .NET technology. The .NET framework is the programming basis of the .NET environment you use to build, deploy, and run Web-based applications, smart client applications, and XML Web services. You must install the .NET framework. Refer to the MSDN Web site for more information about .NET and installing the framework. Creating and communicating with .NET objects requires the .NET Framework 1.1 Service Pack 1 or later. National Instruments also strongly recommends that you use .NET objects only in LabVIEW projects. Note
ActiveX refers to Microsoft's ActiveX technology and OLE technology. With ActiveX Automation, a Windows application, such as LabVIEW, provides a public set of objects, commands, and functions that other Windows applications can access. Refer to the Microsoft Developer's Network documentation, Inside OLE, by Kraig Brockschmidt, second edition, and Essential COM, by Don Box, for more information about ActiveX.
Topics A. Calling Objects in LabVIEW Using ActiveX B. Using LabVIEW as an ActiveX Client C. Using LabVIEW as an ActiveX Server D. ActiveX Events E. Calling Objects in LabVIEW Using .NET F. Implementing .NET G. Registering .NET Events
© National Instruments Corporation
3-1
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
A. Calling Objects in LabVIEW Using ActiveX You can use LabVIEW as an ActiveX client to access the objects, properties, methods, and events associated with other ActiveX-enabled applications. LabVIEW also can act as an ActiveX server, so other applications can access LabVIEW objects, properties, and methods.
ActiveX Objects, Properties, Methods, and Events ActiveX-enabled applications include objects that have exposed properties and methods that other applications can access. Objects can be visible to the users, such as buttons, windows, pictures, documents, and dialog boxes, or invisible to the user, such as application objects. You access an application by accessing an object associated with that application and setting a property or invoking a method of that object. Events are the actions taken on an object, such as clicking a mouse, pressing a key, or receiving notifications about things such as running out of memory or tasks completing. Whenever these actions occur to the object, the object sends an event to alert the ActiveX container along with the event-specific data. The ActiveX object defines the events available for an object.
ActiveX VIs, Functions, Controls, and Indicators Use the following VIs, functions, controls, and indicators to access the objects, properties, methods, and events associated with other ActiveXenabled applications: •
Use the automation refnum control to create a reference to an ActiveX object. Right-click this control on the front panel to select an object from the type library you want to access.
•
Use the Automation Open function to open an ActiveX object.
•
Use the ActiveX container to access and display an ActiveX object on the front panel. Right-click the container, select Insert ActiveX Object from the shortcut menu, and select the object you want to access.
•
Use the Property Node to get (read) and set (write) the properties associated with an ActiveX object.
•
Use the Invoke Node to invoke the methods associated with an ActiveX object.
•
Use the Register Event Callback function to handle events that occur on an ActiveX object.
•
Use the variant control and indicator to pass data to or from ActiveX controls.
Select Tools».NET & ActiveX»Add ActiveX Controls to Palette to add custom control files to the ActiveX Controls palette.
Tip
LabVIEW Intermediate II Course Manual
3-2
ni.com
Lesson 3
Calling Objects in LabVIEW
B. Using LabVIEW as an ActiveX Client When LabVIEW accesses the objects associated with another ActiveXenabled application, it is acting as an ActiveX client. You can use LabVIEW as an ActiveX client in the following ways: •
Open an application, such as Microsoft Excel, create a document, and add data to that document.
•
Embed a document, such as a Microsoft Word document or an Excel spreadsheet, on the front panel in a container.
•
Place a button or other object from another application, such as a Help button that calls the other application help file, on the front panel.
•
Link to an ActiveX control you built with another application.
LabVIEW accesses an ActiveX object with the automation refnum control or the ActiveX container, both of which are front panel objects. Use the automation refnum control to select an ActiveX object. Use the ActiveX container to select a displayable ActiveX object, such as a button or document and place it on the front panel. Both objects appear as automation refnum controls on the block diagram. Figure 3-1 shows how LabVIEW, acting as an ActiveX client, interacts with server applications.
Client Application: LabVIEW Possible Actions: Creates Object Instance Gets an Existing Object Gets or Sets Properties Invokes Methods Dispatches Action
LabVIEW also can act as the ActiveX server
Gets Properties
Maps Names to Interface
Sets Properties Automation Server
Type Library (.TLB)
Defines and Exposes Automation Objects
Describes Programmable Objects (Can be Part of DLL or Stand-Alone)
Figure 3-1. LabVIEW as an ActiveX Automation Client
LabVIEW accesses the server type library to obtain information about its objects, methods, and properties. LabVIEW can perform actions such as invoking methods, getting or setting properties, and so on.
© National Instruments Corporation
3-3
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
Accessing an ActiveX-Enabled Application To access an ActiveX-enabled application, use the automation refnum control on the block diagram to create a reference to an application. Wire the control to the Automation Open function, which opens the calling application. Use the Property Node to select and access the properties associated with the object. Use the Invoke Node to select and access the methods associated with the object. Close the reference to the object using the Close Reference function. Closing the reference removes the object from memory. For example, you can build a VI that opens Microsoft Excel so it appears on the user's screen, creates a workbook, creates a spreadsheet, creates a table in LabVIEW, and writes that table to the Excel spreadsheet. Refer to the Write Table To XL VI in the labview\examples\comm\ ExcelExamples.llb for an example of using LabVIEW as an Excel client.
Inserting an ActiveX Object on the Front Panel To insert an ActiveX object on the front panel, right-click the ActiveX container, select Insert ActiveX Object from the shortcut menu, and select the ActiveX control or document you want to insert. You can set the properties for an ActiveX object using the ActiveX Property Browser or property pages, or you can set the properties programmatically using the Property Node. Use the Invoke Node to invoke the methods associated with the object. For example, you can display a Web page on the front panel by using an ActiveX container to access the Microsoft Web Browser control, selecting the Navigate class of methods, selecting the URL method, and specifying the URL. If you use the ActiveX container, you do not have to wire the automation refnum control on the block diagram to the Automation Open function or close the reference to the object using the Close Reference function. You can wire directly to the Invoke Node or Property Node because the ActiveX container embeds the calling application in LabVIEW. However, if the ActiveX container includes properties or methods that return other automation refnums, you must close these additional references.
Design Mode for ActiveX Objects Right-click an ActiveX container and select Advanced»Design Mode from the shortcut menu to display the container in design mode while you edit the VI. In design mode, events are not generated and event procedures do not
LabVIEW Intermediate II Course Manual
3-4
ni.com
Lesson 3
Calling Objects in LabVIEW
run. The default mode is run mode, where you interact with the object as a user would.
Setting ActiveX Properties After you open an ActiveX server or insert an ActiveX control or document, you can set the properties associated with that control or document using the ActiveX Property Browser, property pages, and the Property Node. ActiveX Property Browser Use the ActiveX Property Browser to view and set all the properties associated with an ActiveX control or document in an ActiveX container. To access the ActiveX Property Browser, right-click the control or document in the container on the front panel and select Property Browser from the shortcut menu. You also can select Tools».NET & ActiveX»Browse ActiveX Properties. The ActiveX Property Browser is an easy way to set the properties of an ActiveX object interactively, but you cannot use the browser to set properties programmatically, and you can use the ActiveX Property Browser only with ActiveX objects in a container. The ActiveX Property Browser is not available in run mode or while a VI runs. ActiveX Property Pages Many ActiveX objects include property pages, which organize the properties associated with the object on separate tabs. To access ActiveX property pages, right-click the object in the container on the front panel and select the name of the object from the shortcut menu. Like the ActiveX Property Browser, ActiveX property pages are an easy way to set the properties of an ActiveX object interactively, but you cannot use them to set properties programmatically, and you can use property pages only with ActiveX objects in a container. Property pages are not available for all ActiveX objects. Property pages also are not available in run mode or when the VI is running. Property Nodes Use the Property Node to set ActiveX properties programmatically. For example, if you use an ActiveX object to warn a user when a temperature exceeds a limit, use the Property Node to set the Value property of the object to specify the limit. The following block diagram shows an example that changes the Value property of the CWButton ActiveX control, which is part of the National Instruments Measurement Studio User Interface ActiveX Library, when the temperature reaches 85 degrees Fahrenheit or higher.
© National Instruments Corporation
3-5
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
In this case, the CWButton control acts as an LED, changes colors, and displays Warning when the temperature reaches the limit, which is the on state of the CWButton control. Note In this example, you could use the ActiveX Property Browser or property pages to set the OffText, OffColor, OnText, and OnColor properties for the CWButton control because you do not need to set those properties programmatically.
LabVIEW Intermediate II Course Manual
3-6
ni.com
Lesson 3
Exercise 3-1
Calling Objects in LabVIEW
Browse to URL
Goal Use ActiveX automation to control Internet Explorer.
Scenario Displaying a web page or HTML report is a common task for measurement and test applications. Develop a reusable component which allows you to create a web browser and navigate to a specified address.
Design Inputs and Outputs Table 3-1. Browse to URL Inputs and Outputs
Type
Name
Properties
Default Value
String Control
URL
—
Empty
Cluster Control
Error In
Error Cluster
No Error
Cluster Indicator
Error Out
Error Cluster
No Error
Microsoft provides two ActiveX interfaces for interacting with Internet Explorer. Internet Explorer can be embedded within another application as an ActiveX control or Internet Explorer can be accessed as a separate entity through an automation server. Embedding Internet Explorer within a LabVIEW front panel is a powerful tool that allows your user to view web pages or other documents without changing programs. However, an embedded control requires an ActiveX container on the front panel, which is less re-usable than a call to the automation server. To create a reusable web browser component, write a subVI that does the following: 1. Opens a reference to the Internet Explorer automation server. 2. Shows an Internet Explorer window. 3. Navigates to a web site specified by the URL control. 4. Closes the ActiveX reference.
IWebBrowser2 Interface Description To open a reference to the Internet Explorer automation server, create an InternetExplorer.IWebBrowser2 object from the Microsoft Internet Controls Type Library. The Microsoft Internet Controls Type Library contains more than one IWebBrowser2 object, so be certain to select the
© National Instruments Corporation
3-7
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
object in the InternetExplorer folder. In this exercise, you use the following properties and methods of the IWebBrowser2 object: Visible property—When you open an Internet Explorer automation reference, the Internet Explorer window is hidden by default. Set the Visible property to True to display the Internet Explorer window. Navigate method—The Navigate method instructs Internet Explorer to open a document or URL. Use the URL control to pass a string to this function. Notice that the IWebBrowser2 object also contains a Navigate2 method. In addition to standard URLs, the second method allows you to browse to nonstandard folders such as the Printers folder or the Recycle bin. Although the Navigate2 method also works for this exercise, use the Navigate method because you do not need the extra functionality. The LabVIEW context help provides descriptions of many ActiveX properties and methods.
Tip
Implementation 1. Create the front panel as shown in Figure 3-2.
Figure 3-2. Browse to URL Front Panel
❑ Create a blank VI and save the VI as Browse to URL.vi in the C:\Exercises\LabVIEW Intermediate II\Browse to URL
directory. ❑ Create the URL control as described in Table 3-1. ❑ Create the Error In control as described in Table 3-1. ❑ Create the Error Out indicator as described in Table 3-1. ❑ Arrange the front panel as shown in Figure 3-2. 2. Open the automation reference.
LabVIEW Intermediate II Course Manual
3-8
ni.com
Lesson 3
Calling Objects in LabVIEW
Figure 3-3. Completed Browse To URL Block Diagram
❑ Open the block diagram of the VI. ❑ Place an Automation Open function on the block diagram. ❑ Right-click the automation refnum input of the Automation Open function and select Create»Constant from the shortcut menu to create an Automation Refnum constant. ❑ Right-click the Automation Refnum constant and choose Select ActiveX Class»Browse from the shortcut menu. ❑ Choose Microsoft Internet Controls from the Type Library pulldown menu. ❑ Double-click to open the InternetExplorer item and select IWebBrowser2 from the Objects list, as shown in Figure 3-4. ❑ Click the OK button to exit the dialog box.
Figure 3-4. Select Automation Object
3. Show the Internet Explorer window.
© National Instruments Corporation
3-9
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Right-click the automation refnum output of the Automation Open function and select Create»Property»Visible from the shortcut menu to create a Visible Property Node. ❑ Right-click the Property Node and select Change All To Write from the shortcut menu. 4. Place a True constant on the block diagram and wire it to the Property Node. ❑ Wire the error and refnum wires of the Automation Open function to the Visible Property Node. 5. Browse to a URL. ❑ Right-click the automation refnum output of the Automation Open function and select Create»Method»Navigate from the shortcut menu to create a Navigate Invoke Node. ❑ Wire the URL control to the Navigate Invoke Node. ❑ Wire the error and refnum wires of the Visible Property Node to the Navigate Invoke Node. 6. Close the automation reference. ❑ Place a Close Reference function on the block diagram. ❑ Wire the diagram as shown in Figure 3-3. 7. Create an icon and connector pane for the VI. ❑ Return to the front panel of the VI. ❑ Right-click the VI Icon and select Edit Icon from the shortcut menu. ❑ In the Icon Editor select Edit»Import Picture from File. Select C:\Exercises\LabVIEW Intermediate II\ Browse to URL\Images\ieicon.bmp as the file to import.
❑ Double-click the Selection tool to select the entire icon. ❑ Select Edit»Paste. ❑ Double-click the Rectangle tool to create a black box around the icon.
LabVIEW Intermediate II Course Manual
3-10
ni.com
Lesson 3
Calling Objects in LabVIEW
❑ Copy the 256 Colors icon into the 16 Colors and B&W icons by selecting each and then clicking the 256 Colors button under the Copy from section. ❑ Click the OK button to exit the Icon Editor. The icon should resemble Figure 3-5. ❑ Configure the connector pane for the VI similar to the example shown in Figure 3-5.
Figure 3-5. Browse to URL Icon and Connector Pane
8. Save the VI.
Testing 1. Browse to a file. ❑ Switch to the front panel of the VI. ❑ Enter C:\Program Files\National Instruments\ LabVIEW X.X\readme.html in the URL control, where X.X is your LabVIEW version. The preceding path may be different if you have installed LabVIEW to a directory other than the default installation directory. Note
❑ Run the VI. An Internet Explorer window should display the LabVIEW readme file. 2. Browse to a web site. ❑ Enter http://www.ni.com in the URL control. ❑ Run the VI. An Internet Explorer window should display the National Instruments website. Note
You can browse to a Web site only if your computer has internet access.
End of Exercise 3-1
© National Instruments Corporation
3-11
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
Exercise 3-2
VI Statistics Report
Goal Integrate Internet Explorer automation into an application.
Scenario In Exercise 2-4 you created a VI to gather information about the VIs running on a computer. Currently, the exercise only displays this data to the front panel of the VI. In order to make the data more accessible, publish the data into an HTML report and use the reusable web browser component to display the data.
Design Inputs and Outputs Table 3-2. VI Statistics Report Inputs and Outputs
Type
Name
Properties
Default Value
String Control
Machine Name
—
Empty (defaults to local machine)
Path Control
Report File Path
Browse button visible, New or Existing Selection Mode
C:\Exercises\LabVIEW Intermediate II \VI Statistics Report\VI Report.html
In order to display the VI statistics data in a web browser, you must first format the data into HTML format. While you could do this manually using string manipulation, the Report Generation VIs in LabVIEW simplify the task considerably. A subVI with the appropriate report generation code is provided in the C:\Exercises\VI Statistics Report directory. Use the Generate VI Statistics HTML VI provided, along with the Browse to URL VI that you created in Exercise 3-1 to display the results of the VI Statistics VI in a report. You can remove the current indicators to simplify wiring and avoid duplicating the displayed information.
LabVIEW Intermediate II Course Manual
3-12
ni.com
Lesson 3
Calling Objects in LabVIEW
Implementation 1. Modify the front panel of the original VI Statistics VI.
Figure 3-6. VI Statistics Report Front Panel
❑ Open the VI Statistics VI that you created in Exercise 2-2 located in the C:\Exercises\LabVIEW Intermediate II\ VI Statistics directory. ❑ Save the VI as VI Statistics Report.vi in the C:\Exercises\LabVIEW Intermediate II\ VI Statistics Report directory. Choose the Substitute
copy for original option in the Save As dialog box. ❑ Delete the VIs Open, VIs Running, and VIs Report indicators. ❑ Create the Report File Path control as described in Table 3-2. ❑ Arrange the front panel as shown in Figure 3-6. 2. Generate an HTML report for the data.
Figure 3-7. Completed VI Statistics Report Block Diagram
❑ Open the block diagram of the VI.
© National Instruments Corporation
3-13
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Place Generate VI Statistics HTML.vi, located in C:\Exercises\LabVIEW Intermediate II\ VI Statistics Report directory, on the block diagram.
❑ Open the subVI and inspect the code to generate the report. This subVI uses the Report Generation VIs in LabVIEW. ❑ Wire the subVI as shown in Figure 3-7. 3. Display the report in Internet Explorer. ❑ Place Browse to URL.vi, located in the C:\Exercises\ LabVIEW Intermediate II\Browse to URL directory on the block diagram. You created this subVI in Exercise 3-1 ❑ Place a Path to String function on the block diagram. ❑ Wire the diagram as shown in Figure 3-7. 4. Save the VI.
Testing 1. Run the VI. ❑ Switch to the front panel of the VI. ❑ Close all other open VIs. ❑ Run the VI. Notice that report generation loads a number of VIs into memory. 2. Test the VI under other conditions (optional). ❑ Open one or more other VIs and run the VI. Observe the difference in states between the running and non-running VIs. ❑ Enter the name of another machine in the Machine Name control and run the VI remotely.
End of Exercise 3-2
LabVIEW Intermediate II Course Manual
3-14
ni.com
Lesson 3
Calling Objects in LabVIEW
C. Using LabVIEW as an ActiveX Server The LabVIEW application, VIs, and control properties and methods are available through ActiveX calls from other applications. Other ActiveXenabled applications, such as Microsoft Excel, can request properties, methods, and individual VIs from LabVIEW, and LabVIEW acts as an ActiveX server. For example, you can embed a VI graph in an Excel spreadsheet and, from the spreadsheet, enter data in the VI inputs and run the VI. When you run the VI, the data plot to the graph. Refer to the labview\examples\comm\freqresp.xls for an example of using LabVIEW properties and methods in an Excel spreadsheet. LabVIEW supports an ActiveX interface to the VI Server. This server interface allows client applications to programmatically access LabVIEW. Figure 3-8 shows how LabVIEW acts as an ActiveX server to interact with client applications.
Client Application Possible Actions: Creates Object Instance Gets an Existing Object Gets or Sets Properties Invokes Methods Dispatches Action
LabVIEW also can act as an ActiveX server
Gets Properties
Maps Names to Interface
Sets Properties Automation Server: LabVIEW
Type Library (.tlb)
Defines and Exposes Automation Objects
Describes Programmable Objects (Can be Part of DLL or Stand-Alone)
Figure 3-8. LabVIEW ActiveX Automation Server
The LabVIEW type library, labview.tlb, provides information about LabVIEW objects, methods, and properties. Client applications can access methods and set or get properties of the LabVIEW ActiveX server. You can use LabVIEW as an ActiveX server, enabling other ActiveXenabled clients to request properties and methods from LabVIEW and individual VIs. To configure LabVIEW as an ActiveX server, select Tools»Options to display the Options dialog box. Select VI Server: Configuration from the top pull-down menu and place a checkmark in the ActiveX checkbox.
© National Instruments Corporation
3-15
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
Support for Custom ActiveX Automation Interfaces If you are writing an ActiveX client that accesses properties and methods from an ActiveX server using LabVIEW, you can access custom interfaces exposed by the server. You do not need to use IDispatch to do so. However, the developer of the ActiveX server must make sure the parameters of the properties and methods in these custom interfaces have Automation (IDispatch) data types. The developer of the server must do so to expose multiple interfaces from one object, rather than through multiple objects. You still can use the interfaces in the LabVIEW environment. Refer to your server development programming environment documentation for more information about accessing custom interfaces.
LabVIEW Intermediate II Course Manual
3-16
ni.com
Lesson 3
Exercise 3-3
Calling Objects in LabVIEW
Frequency Response VI
Goal To observe and run a Visual Basic script that uses ActiveX automation calls to access LabVIEW.
Description LabVIEW can be an effective tool for expanding the capabilities of other programs. By calling LabVIEW through its ActiveX interface, other programs, such as Microsoft Excel, can gain access to all of the analysis, hardware I/O and other capabilities of LabVIEW. In this exercise you use a macro in Excel to call LabVIEW. The LabVIEW VI provides data, based upon parameters passed from Excel, which can then be graphed or otherwise used in Excel.
Implementation 1. Launch Excel. The Excel file in this exercise uses macros to call LabVIEW through ActiveX. In order to edit and run the macros, you must have the Excel Macro Security Level, located at Tools»Macro»Security, set to Medium or Low. Note
2. Open the freqresp.xls file located in the C:\Exercises\LabVIEW Intermediate II\Frequency Response directory. Select the Enable macros option when prompted. 3. Select Tools»Macro»Macros, select the LoadData macro, and click the Edit button. Do not double-click LoadData. Double-clicking LoadData runs the macro, but you should view the macro code first. Note
4. The Visual Basic editor opens, and you can view the LoadData macro code. 5. Examine the script for the LoadData macro. The macro opens the Frequency Response VI from examples\apps\freqresp.llb. It then sets the values of the various front panel controls. Finally, it runs the VI, returns the array data, and plots the Response graph in Excel. Notice the following features of the source code: •
© National Instruments Corporation
The script creates an ActiveX object, LabVIEW.Application, using the CreateObject function.
3-17
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
•
The script loads the Frequency Response VI and returns a VI reference using the GetVIReference method.
•
The script calls the VI with the Call method. The front panel controls (inputs) and indicators (outputs) are passed as parameters to the Call method.
•
paramNames is an array of strings that contains the names of the
front panel objects of this VI. This VI has four inputs and one output. paramVals is an array that contains the input values for the input parameters and the return values from the output parameters in the order in which names were specified in paramNames. •
The fifth element in paramVals contains a cluster of two arrays as the value for the Response graph. In ActiveX, a cluster is an array of variant data types. Hence, a cluster of two elements x and y is an array of two variant elements.
•
The values of x coordinates and y coordinates are filled in columns 1 and 2 in Excel. Excel uses these columns to plot the chart.
6. After you examine the source code, close the Visual Basic editor by selecting File»Close and Return to Microsoft Excel. 7. Run the macro in Excel by pressing the keys. You can clear the chart by pressing the keys. 8. Try changing the Frequency Response Demo values in Excel and running the macro again. Notice that LabVIEW can be open or closed when you run the macro. 9. If time permits, complete the following challenge step. Otherwise, close Excel and the Frequency Response VI. Do not save changes.
Challenge Modify the LoadData macro in freqresp.xls to close the Frequency Response VI automatically.
End of Exercise 3-3
LabVIEW Intermediate II Course Manual
3-18
ni.com
Lesson 3
Calling Objects in LabVIEW
D. ActiveX Events To use ActiveX events in an application, you must register for the event and handle the event when it occurs. ActiveX event registration is similar to dynamic event registration. However, the architecture of an ActiveX event VI is different than the architecture of an event-handling VI. The following components make up a typical ActiveX event VI: •
ActiveX object for which you want to generate an event.
•
Register Event Callback function to specify and register for the type of event you want to generate.
•
Callback VI that contains the code you write to handle the event you specify.
You can generate and handle events on ActiveX objects in a container or on ActiveX objects you specify by using an Automation Refnum. For example, you can call a Windows tree control from an ActiveX container and specify that you want to generate a Double Click event for the items displayed in the tree control. The Register Event Callback function is a resizable node capable of handling multiple events, similar to the Register For Events function. When you wire an ActiveX object reference to the Register Event Callback function and specify the event you want to generate for that object, you are registering the ActiveX object for that event. After you register for the event, you create a callback VI that contains the code you write to handle the event. Different events may have different event data formats so changing the event after you create a callback VI might break wires on the block diagram. Select the event before you create the callback VI.
Handling ActiveX Events You must create a callback VI to handle events from ActiveX controls when the controls generate the registered events. The callback VI runs when the event occurs. To create a callback VI, right-click the VI Ref input of the Register Event Callback function and select Create Callback VI from the shortcut menu. LabVIEW creates a reentrant VI. Open the VI and edit the block diagram to handle the event. The callback VI contains the following elements: •
Event common data contains the following elements:
•
Source is a numeric control that specifies the source of the event, such as LabVIEW or ActiveX. A value of 1 indicates an ActiveX event.
•
Type specifies which event occurred. This is an enumerated type for user interface events and a 32-bit unsigned integer type for ActiveX and
© National Instruments Corporation
3-19
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
other event sources. For ActiveX events, the event type represents the method code, or ID, for the event registered. •
Time is the time stamp in milliseconds that specifies when the event was generated.
•
Control Ref is a reference to the ActiveX or Automation Refnum on which the event occurred.
•
Event Data is a cluster of the parameters specific to the event the callback VI handles. LabVIEW determines the appropriate Event Data when you select an event from the Register Event Callback function. If an event does not have any data associated with it, LabVIEW does not create this control in the callback VI.
•
Event Data Out is a cluster of the modifiable parameters specific to the event the callback VI handles. This element is available only if the ActiveX event has output parameters.
•
(Optional) User Parameter is data that you want to pass to the callback VI when the ActiveX object generates the event.
You can use an existing VI as a callback VI as long as the connector pane of the VI you intend to use matches the connector pane of the event data. The callback VI must be reentrant, and the reference to the callback VI must be strictly typed.
Note
You cannot make synchronous calls to non-modal dialog boxes from a callback VI. You must asynchronously call a non-modal dialog box from a callback VI by invoking a Run VI method on the dialog and wiring a FALSE Boolean constant to the Wait Until Done input of the method.
LabVIEW Intermediate II Course Manual
3-20
ni.com
Lesson 3
Calling Objects in LabVIEW
E. Calling Objects in LabVIEW Using .NET You can use LabVIEW as a .NET client to access the objects, properties, methods, and events associated with .NET servers. LabVIEW is not a .NET server. Other applications cannot communicate directly with LabVIEW through .NET unless you use .NET to connect to LabVIEW as an ActiveX server. With a .NET-enabled VI, you can connect to Windows services and APIs. The .NET framework includes COM+ component services, .NET remoting, and support for Web service protocols, such as, SOAP, WSDL, and UDDI. Creating and communicating with .NET objects requires the .NET Framework 1.1 Service Pack 1 or later. National Instruments also strongly recommends that you use .NET objects only in LabVIEW projects. Note
.NET Environment The following list provides a background of the various elements that make up the .NET environment. The purpose of this information is to help you understand .NET, but learning this information is not essential for you to use the .NET components in LabVIEW. •
Common Language Runtime (CLR)—A set of libraries responsible for run-time services, such as language integration, security enforcement, memory, garbage collection, process management, and thread management. To help .NET communicate with various programs, the CLR provides a data type system that spans programming languages and operating system boundaries. Developers then can view the system as a collection of data types and objects rather than as a collection of memory and threads. The CLR requires compilers and linkers to generate information in the CLR intermediate language (IL) metadata format. All .NET programming language compilers generate CLR IL code rather than the assembly code.
•
Class Libraries—A set of classes that provides standard functionality, such as input and output, string manipulation, security management, network communications, thread management, text management, user interface design features, and so on. These classes provide the same functionality as the Win32/COM system. In the .NET framework, you can use classes created in one .NET language in another .NET language.
•
Assemblies—A unit of deployment similar to a DLL, OCX, or executable for a component in COM. Assemblies are DLLs and executables you build using a .NET compiler. Assemblies can consist of a single file or multiple files. An assembly includes a manifest that contains information about the assembly name, version information, local information, publisher's security information, list of files that make
© National Instruments Corporation
3-21
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
up the assembly, list of dependent assemblies, resources, and exported data types. Single-file assemblies contain all the data in a single file, including the manifest and any resources it needs. Multi-file assemblies might have external resources, such as bitmaps, icons, sound files, and so on, or have one file for the core code and another for helper libraries. •
Assemblies can be public or private. .NET requires that private assemblies be in the same directory as the application directory and that public assemblies be in a system wide global cache called the Global Assembly Cache (GAC). The developer of the application typically writes private assemblies for use by that application. The developer of the assembly also decides the version control. The assembly name is the filename, minus any file extension, of the file that contains the manifest.
•
The .NET CLR uses configuration settings to determine the assembly version to load. These configuration settings might override your request for a specific assembly version. For example, the system administrator can configure your computer to load version 1.0.0.1 instead of 1.0.0.0. If you then try to load version 1.0.0.0, the .NET CLR promotes the assembly version to 1.0.0.1. LabVIEW also launches a dialog box that notifies you of the promotion.
•
Global Assembly Cache (GAC)—A listing of the public assemblies available on the system. The GAC is analogous to the registry COM uses.
.NET Functions and Nodes Use the following LabVIEW functions and nodes located on the .NET palette to access the objects, properties, and methods associated with .NET servers: •
Use the Constructor Node to select a constructor of a .NET class from an assembly and create an instance of that class on execution. When you place this node on the block diagram, LabVIEW displays the Select .NET Constructor dialog box.
•
Use the Property Node to get (read) and set (write) the properties associated with a .NET class.
•
Use the Invoke Node to invoke methods associated with a .NET class.
•
Use the Close Reference function to close all references to .NET objects when you no longer need the connection.
•
Use the Register Event Callback function to register and handle .NET events.
•
Use the Unregister For Events function to unregister a .NET event.
•
Use the To More Generic Class function to upcast a .NET reference to its base class.
LabVIEW Intermediate II Course Manual
3-22
ni.com
Lesson 3
Calling Objects in LabVIEW
•
Use the To More Specific Class function to downcast a .NET reference to its derived class.
•
Use the Static VI Reference function to create a strictly typed VI reference to a callback VI you create.
F. Implementing .NET You can implement .NET in LabVIEW in the following ways: •
Creating .NET objects
•
Setting .NET properties and invoking .NET methods
•
Registering .NET events
•
Maintaining .NET assemblies
•
Configuring a .NET client application
Creating .NET Objects You can create .NET objects on the front panel or the block diagram. Use a Constructor Node to create a .NET object on the block diagram. Use a .NET container to create a .NET control on the front panel. You also can add .NET controls to the Controls palette for later use. You cannot switch between design mode and run mode for a .NET container as you can for an ActiveX container. The behavior of a .NET container is similar to that of an ActiveX container in design mode. Note
If you create a VI with .NET controls, you must use the user interface execution system. Otherwise, the VI might fail with .NET exceptions at run time. Select File»VI Properties and select Execution from the pull-down menu to display the Execution Properties page. Then select user interface from the Preferred Execution System list. Use the same execution system as the caller for subVIs with references to .NET controls. Select File»VI Properties and select Execution from the pull-down menu to display the Execution Properties page. Then select same as caller from the Preferred Execution System list.
Setting.NET Properties and Invoking .NET Methods .NET-enabled applications include objects that have exposed properties and methods that other applications can access. Objects can be visible to the users, such as buttons, windows, pictures, documents, and dialog boxes, or invisible to the user, such as application objects. You access an application by accessing an object associated with that application and setting a property or invoking a method of that object.
© National Instruments Corporation
3-23
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
On the front panel or block diagram, right-click a .NET object and select Create»Property Node or Create»Invoke Node, and select a property or method from the shortcut menu to set a property or invoke a method for the object. You also can select .NET-specific properties or invoke .NET-specific methods for a .NET object. On the block diagram, right-click a .NET object and select Create»Property or Create»Invoke, and select a .NET-specific property or method from the shortcut menu. You cannot view and set .NET properties in a Property Browser as you can for ActiveX. You must set .NET properties using Property Nodes. Note
Maintaining .NET Assemblies LabVIEW can find .NET assemblies in the following places: •
Global Assembly Cache (GAC)—LabVIEW can access all assemblies in the GAC.
•
Specified subdirectories—LabVIEW can search directories for assemblies that you use. If you use .NET objects in a saved project, LabVIEW searches the directory that contains the project and all subdirectories of that project. If you use .NET objects in a shared library or stand-alone application, LabVIEW searches the directory that contains the library or application and the data and bin subdirectories. If you use .NET objects in a location other than a saved project, shared library, or stand-alone application, save the assembly files in the GAC or use a relative path.
•
Relative path—LabVIEW can access a relative path for assemblies that you use. Use relative paths only if you use .NET objects outside of a project.
After you create a VI that includes .NET components, you can build that VI into a shared library or stand-alone application. LabVIEW copies the associated private .NET assembly files to the data subdirectory in the same directory as the library or application. You also can distribute .NET VIs to another location. If you distribute .NET VIs, libraries, or stand-alone applications, you either must move the associated private .NET assembly files to subdirectories that LabVIEW can search, or you must save the files in the GAC. Make sure that the target computer has the .NET framework installed.
Configuring a .NET Client Application .NET provides administrative capability to an application by using configuration files. A configuration file contains XML content and typically has a .config extension. To configure a LabVIEW .NET client application, you can provide a configuration file for a saved project, shared
LabVIEW Intermediate II Course Manual
3-24
ni.com
Lesson 3
Calling Objects in LabVIEW
library, or stand-alone application. Name the configuration file the name of the project, library, or application with a .config extension, for example, MyApp.lvproj.config, MyApp.dll.config, or MyApp.exe.config. Save the configuration file in the directory that contains the project, library, or application. If you build a stand-alone application from a saved project with a configuration file, you must rename and save that configuration file in the directory that contains the application. For example, if you build a stand-alone application from foo.lvproj that has the configuration file foo.lvproj.config, rename the file foo.exe.config and save it in the directory that contains foo.exe, the stand-alone application.
© National Instruments Corporation
3-25
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
Exercise 3-4
Font Dialog
Goal Call a System .NET Assembly to display a Windows Common Dialog.
Scenario For many applications, you want to provide a familiar look and feel for your user. One technique for doing this is reusing Windows common dialogs whenever possible. For example, to have your user select a text font, you can call a font dialog from the operating system. The Windows Common Font Dialog creates a font style and color selection dialog which is familiar to users of most Windows based word processors.
Figure 3-9. Common Font Dialog
Create a subVI which calls a font dialog and returns references to the font and color selected by the user. The subVI should use proper error handling techniques and should return a value indicating if the user has canceled the dialog.
Design There are multiple ways to display Windows Common Dialogs. The Microsoft Common Dialog Control ActiveX server and ActiveX control provide access to the Color, Font, Help, Open, Printer, and Save dialogs. However, these ActiveX components require special licensing to use, which you can acquire through Microsoft Visual Studio. Alternately, you can create a FontDialog object from the System.Windows.Forms .NET Assembly. Using the .NET Assembly requires the .NET Framework to be installed, but does not require any additional licensing. Furthermore, the
LabVIEW Intermediate II Course Manual
3-26
ni.com
Lesson 3
Calling Objects in LabVIEW
.NET Assembly provides the newest version of the dialog, which has additional features and improved integration with other Windows components.
Font Dialog Inputs and Outputs Table 3-3. Font Dialog Inputs and Outputs
Type
Name
Properties
Default Value
Cluster Control
error in
Error Cluster
No Error
Constructor Node
Font
.NET Reference, System.Drawing.Font class
Not a refnum
Constructor Node
Color
.NET Reference, System.Drawing.Color class
Not a refnum
Enum Indicator
DialogResult
Values defined by FontDialog object
None
Cluster Indicator
error out
Error Cluster
No Error
The FontDialog SubVI should perform the following steps: 1. Create a FontDialog object using a .NET Constructor Node. 2. Set the ShowColor property to True so that the font dialog allows the user to select a color. 3. Call the ShowDialog method to show the dialog and return a result. Return the result to the calling VI. 4. Use the Font and Color properties to attain references to the selected font and color and return these references to the calling VI. 5. Close the reference to the FontDialog object.
FontDialog Object Description The FontDialog object creates a common dialog box that displays a list of fonts that are currently installed on the system. You can create a FontDialog class by selecting the FontDialog object from the System.Windows.Forms assembly using a .NET Constructor Node. You use the following properties and methods of the FontDialog object in this exercise. Full documentation for the FontDialog and other objects included in the .NET Framework can be found on MSDN or in the documentation for Microsoft Visual Studio .NET. ShowColor Property—Setting this to true instructs the FontDialog to show a selector for the font color. This property should be set before showing the dialog.
© National Instruments Corporation
3-27
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
ShowDialog Method—Displays the font dialog. This method returns an enumerated type which indicates the user’s response to the dialog. Notice that the enumerated type returned from this function is shared among many dialogs, and therefore not all the values are actually possible from a FontDialog. A FontDialog typically returns OK or Cancel. Two versions of the ShowDialog method exists, one takes no parameters and the other takes an IWin32Window object to designate the owning window for the dialog. For this exercise, use the version of the function with no parameters. This may occasionally cause the font dialog to show up behind the main application. You can solve this problem by using the IWin32Window version of the function, however this requires getting a reference to the window handle of the LabVIEW front panel and converting it to an IWin32Window object, which is beyond the scope of this exercise. Note
Font Property—Returns a .NET reference to a System.Drawing.Font object. You can use this reference to get information about the font, such as the font name and size, or you can pass this reference to other objects which take .NET Font references, such as a .NET RichTextBox control. Color Property—Returns a .NET reference to a System.Drawing.Color object. You can convert this color into a LabVIEW color by using the reference to get the R, G and B properties of the color and then using the RGB to Color VI. Alternately, you can pass this reference to any .NET object which uses colors.
Implementation 1. Create the VI. ❑ Open a blank VI and save it as C:\Exercises\LabVIEW Intermediate II\Font Dialog\Font Dialog.vi. ❑ Open the block diagram of the VI.
Figure 3-10. Completed Font Dialog Block Diagram
LabVIEW Intermediate II Course Manual
3-28
ni.com
Lesson 3
Calling Objects in LabVIEW
2. Open a .NET reference to the FontDialog object. ❑ Place a Constructor Node on the block diagram to display the Select .NET Constructor dialog box. ❑ Select System.Windows.Forms from the Assembly pull-down menu. ❑ Double-click the System.Windows.Forms item in the Object list and select FontDialog to add it to the Constructors list. ❑ Click the OK button. 3. Show the font dialog. ❑ Right-click the reference output of the Constructor Node and select Create»Property»ShowColor from the shortcut menu to create a FontDialog Property Node. ❑ Right-click the FontDialog Property Node and select Change All To Write from the shortcut menu. ❑ Right-click the ShowColor input of the FontDialog Property Node and select Create»Constant from the shortcut menu. Set the value of the constant to True. ❑ Right-click the reference output of the FontDialog Property Node and select Create»Method»ShowDialog() from the shortcut menu to create a FontDialog Invoke Node. ❑ Right-click the ShowDialog output of the FontDialog Invoke Node and select Create»Indicator from the shortcut menu to create a ring indicator for the DialogResult. You can later convert this ring indicator to the enum DialogResult output described in Table 3-3. 4. Get .NET references to font and color. ❑ Right-click the reference output of the FontDialog Invoke Node and select Create»Property»Font from the shortcut menu to create another FontDialog Property Node. ❑ Expand the second FontDialog Property Node to show two elements. Select Color as the second element. ❑ Right-click the Font output of the FontDialog Property Node and select Create»Indicator from the shortcut menu to create the Font output described in Table 3-3.
© National Instruments Corporation
3-29
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Right-click the Color output of the FontDialog Property Node and select Create»Indicator from the shortcut menu to create the Color output described in Table 3-3. 5. Close the reference and handle errors. ❑ Place a Close Reference function on the block diagram. ❑ Wire the Close Reference function as shown in Figure 3-10. ❑ Right-click the error in input of the Constructor Node and select Create»Control from the shortcut menu to create the error in input described in Table 3-3. ❑ Right-click the error out output of the Close Reference function and select Create»Indicator from the shortcut menu to create the error out output described in Table 3-3. ❑ Place a Case structure around the code as shown in Figure 3-10. Wire the error in control to the case selector terminal. ❑ Wire the error wire through the Error case of the Case structure to the error out indicator. 6. Create the icon and connector pane. ❑ Switch to the VI front panel. ❑ Organize the controls in a logical manner. ❑ Right-click the DialogResult control and select Replace»Modern» Ring & Enum»Enum from the shortcut menu. Converting the ring control into an enumerated type control allows you to better control Case structures with the result of the dialog.
Note
❑ Create an icon and connector pane similar to Figure 3-11.
Figure 3-11. Font Dialog Icon
7. Save the VI.
LabVIEW Intermediate II Course Manual
3-30
ni.com
Lesson 3
Calling Objects in LabVIEW
Testing 1. Test the VI as a top-level VI. ❑ Run the VI. A font dialog should display. Notice that the font dialog may be behind the front panel. Minimize the front panel or press the keys to find the font dialog window. ❑ Click the OK button in the font dialog to finish the VI.
Challenge 1. Test the VI as a subVI. ❑ Create a VI that calls the FontDialog VI. ❑ Check the DialogResult to determine if the user clicked the OK button. ❑ Use the Font reference to display the selected Font Name. ❑ Use the Color reference to display the selected color in a LabVIEW Color Box indicator. Refer to the Design section for a suggestion on how to convert a .NET Color reference to a LabVIEW color.
Tip
End of Exercise 3-4
© National Instruments Corporation
3-31
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
Exercise 3-5
Word Processor
Goal Use a Windows Forms .NET Control.
Scenario Develop a Word Processor in LabVIEW. The Word Processor should have the following features and should have a look and feel similar to other Windows word processors.
Word Processor Features •
Contains a standard, multiline area for typing text.
•
Displays scrollbars when necessary.
•
Provides a graphical toolbar to perform all functions.
•
Allows the user to create a new, blank file.
•
Allows the user to open a Rich Text File.
•
Allows the user to save the current text as a Rich Text File.
•
Allows the user to change the font, color, and effects for selected text or for new text at the cursor position.
•
Allows the user to search for a particular string within the text and select the string, if found.
•
Allows the user to cut text to the clipboard.
•
Allows the user to copy text to the clipboard.
•
Allows the user to paste text from the clipboard.
•
Allows the user to undo the last action.
•
Ends the application when the user clicks the close button on the title bar.
Design You could implement all of this functionality in LabVIEW by using a text box control. However, manually implementing each of these features would be a considerable undertaking. A better approach is to utilize an existing component which has most of these features built in. The .NET Framework contains common windows controls which you can use in a user interface. These controls behave very similarly to ActiveX controls in LabVIEW. One of the available controls is RichTextBox. This control is a text box, much like a LabVIEW string control, except that the control contains many built-in word processor functions. Most of the features specified in the Scenario are already included in RichTextBox.
LabVIEW Intermediate II Course Manual
3-32
ni.com
Lesson 3
Calling Objects in LabVIEW
However, you still need to provide an interface to activate the various functions.
Word Processor Inputs and Outputs Table 3-4. Word Processor Inputs and Outputs
Type
Name
Properties
Default Value
.NET Container
TextBox
.NET Container with a System.Windows.Forms.RichTextBox object inserted
N/A
Boolean button
New
Strict Type Definition Custom Control
False
Boolean button
Open
Strict Type Definition Custom Control
False
Boolean button
Save
Strict Type Definition Custom Control
False
Boolean button
Font
Strict Type Definition Custom Control
False
Boolean button
Find
Strict Type Definition Custom Control
False
Boolean button
Cut
Strict Type Definition Custom Control
False
Boolean button
Copy
Strict Type Definition Custom Control
False
Boolean button
Paste
Strict Type Definition Custom Control
False
Boolean button
Undo
Strict Type Definition Custom Control
False
Event Handling Design The user activates various functions of the word processor by pressing buttons on a toolbar. A common user interface event handler is the best design for this application as it allows you to efficiently monitor and react to these buttons. The program consists of an initialization section before the event loop, a number of different events, and a cleanup section after the event loop. With the exception of the Close event, all of the events are Value Change events for button controls. Initialization Section—Sets any properties which need to be set only once at the beginning of the program. For example, the scrollbars on the text box should be configured in this section by using the ScrollBars property of the RichTextBox. New Event—Calls the Clear method of the RichTextBox to erase all text and create a blank slate for the user to type.
© National Instruments Corporation
3-33
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
Open Event—Prompts the user to browse to a Rich Text File by using a standard file dialog. If the user successfully selects a file, the event case should call the LoadFile method of the RichTextBox. Save Event—Prompts the user to enter a filename and location by using a standard file dialog. If the user does not cancel the dialog, the event case should call the SaveFile method of the RichTextBox. Font Event—Calls the Font Dialog VI you wrote in Exercise 3-4 to allow the user to select the font, color and other effects. If the user does not cancel the dialog, the references for the font and color should be applied to the RichTextBox by using the SelectionFont and SelectionColor properties. Find Event—Prompts the user to enter a string to find. If the user does not cancel the find dialog, the event case should call the Find method of the RichTextBox to locate the string, then the Select method to select it and the Focus method to return the key focus to the text box. Cut Event—Calls the Cut method of the RichTextBox. Copy Event—Calls the Copy method of the RichTextBox. Paste Event—Calls the Paste method of the RichTextBox. Undo Event—Calls the Undo method of the RichTextBox Close Event—Exits the event loop and enter the cleanup section. This Event structure case should handle the Panel Close? filter event. Cleanup Section—Closes all open references, including the RichTextBox reference, and handle errors with a simple error handler.
RichTextBox Control Description The RichTextBox control is an enhanced text box with the ability to change text characteristics and a number of built-in word processor features. You can create a RichTextBox control by inserting the RichTextBox control from the System.Windows.Forms assembly into a .NET Container. You use the following properties and methods of the RichTextBox control in this exercise. Full documentation for the RichTextBox and other controls included in the .NET Framework can be found on MSDN or in the documentation for Microsoft Visual Studio .NET. ScrollBars Property—Controls the scrollbars on the RichTextBox. Use this property to show or hide the horizontal and vertical scrollbars or to set the scrollbars so that they display only when necessary. For this exercise, set the property to Vertical to cause the vertical scrollbar to appear only when necessary.
LabVIEW Intermediate II Course Manual
3-34
ni.com
Lesson 3
Calling Objects in LabVIEW
Clear Method—Removes all text from the text box. LoadFile Method—Loads the contents of a file into the RichTextBox. The default version of this method accepts a path and loads a Rich Text File into the text box. Another version of the method allows you to open file types other than Rich Text Files, such as Plain Text files or Unicode text files. For this exercise, you only need to load Rich Text Files. SaveFile Method—Saves the contents of the RichTextBox into a file. Like the LoadFile method, alternate versions of this method can save in different file types. However you only need to save Rich Text Files for this exercise. SelectionFont Property—Applies a Font reference to text in the RichTextBox. This property affects the font type, size, and effects, but does not set the font color. If no text is selected when this property is set, the font specified in this property is applied to the current insertion point and to all text that is typed into the control after the insertion point. The font setting applies until the property is changed to a different font or until the insertion point is moved to a different section within the control. If text is selected within the control, the selected text and any text entered after the text selection have the value of this property applied to it. SelectionColor Property—Applies a Color reference to text in the RichTextBox. This property behaves in the same way as SelectionFont with regards to selected text and insertion points. Find Method—Searches the RichTextBox for a string of characters. This method returns the offset within the function of the first character in the matching string. Select Method—Selects text in the text box. Use this property to select a string after it has been found with Find. Focus Method—Sets the input focus to the control. Use this property to return the cursor to the text box after displaying a dialog such as the font dialog or the dialog to search for a string. Cut Method—Copies selected text to the Windows clipboard and then deletes it. Copy Method—Copies selected text to the Windows clipboard. Paste Method—Pastes text that has been previously placed on the Windows clipboard at the current cursor location.
© National Instruments Corporation
3-35
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
Undo Method—Reverts the last change made in the RichTextBox control.
Implementation 1. Build the VI front panel.
Figure 3-12. Word Processor Front Panel
❑ Open a blank VI and save it as Word Processor.vi in the C:\Exercises\LabVIEW Intermediate II\Word Processor directory.
❑ Place a .NET Container on the front panel of the VI. Name the container TextBox. ❑ Right-click the .NET Container and select Insert .NET Control from the shortcut menu. ❑ Select System.Windows.Forms from the Assembly pull-down menu. ❑ Select RichTextBox from the Controls list. ❑ Click the OK button. ❑ Place the following custom controls located in the C:\Exercises\ LabVIEW Intermediate II\Word Processor\Controls
directory on the front panel. The custom buttons are configured as strict type definitions.
LabVIEW Intermediate II Course Manual
–
New Button.ctl
–
Open Button.ctl
–
Save Button.ctl
–
Font Button.ctl
3-36
ni.com
Lesson 3
–
Find Button.ctl
–
Cut Button.ctl
–
Copy Button.ctl
–
Paste Button.ctl
–
Undo Button.ctl
Calling Objects in LabVIEW
❑ Hide the labels for the .NET Container and all of the buttons. ❑ Arrange the controls and resize the front panel as shown in Figure 3-12. 2. Set window properties. ❑ Select File»VI Properties and choose Window Appearance from the Category pull-down menu. ❑ Click the Customize button and set the Window Appearance as shown in Figure 3-13.
Figure 3-13. Word Processor Window Appearance Options
© National Instruments Corporation
3-37
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
3. Create the Initialization section, Cleanup section, Close event, and main program structure.
Figure 3-14. Word Processor Block Diagram
❑ Switch to the VI block diagram. ❑ Right-click the TextBox terminal and select Create»Property» ScrollBars from the shortcut menu. ❑ Right-click the RichTextBox Property Node and select Change All to Write from the shortcut menu. ❑ Right-click the ScrollBars input of the RichTextBox Property Node and select Create»Constant from the shortcut menu. Set the value of the constant to Vertical. ❑ Place a While Loop on the block diagram as shown in Figure 3-14. ❑ Place an Event structure in the While Loop. ❑ Place an Unbundle By Name function in the While Loop. ❑ Place an Or function in the While Loop. ❑ Place a Close Reference function to the right of the While Loop. ❑ Place a Simple Error Handler to the right of the While Loop. ❑ Right-click the border of the Event structure and select Edit Events Handled by This Case from the shortcut menu. ❑ Select from the Event Sources list.
LabVIEW Intermediate II Course Manual
3-38
ni.com
Lesson 3
Calling Objects in LabVIEW
❑ Select Panel Close? from the Events list. LabVIEW generates two events when you close a panel. The Panel Close event is a notify event that occurs after the panel closes. The Panel Close? event is a filter event that occurs before the panel closes and allows you to prevent the panel from closing. To use the toolbar to stop the application you must use the filter event, otherwise the VI closes each time you stop it.
Tip
❑ Click the OK button. ❑ Place two True constants in the Event structure. ❑ Wire the objects as shown in Figure 3-14. Use shift registers for the refnum and error wires. 4. Create the New event.
Figure 3-15. New Event
❑ Right-click the border of the Event Structure and select Add Event Case from the shortcut menu. ❑ Select Controls»New from the Event Sources list. ❑ Select Value Change from the Events list. ❑ Click the OK button. ❑ Right click the .NET Refnum wire and select Create»Method» Clear() from the shortcut menu to create a Clear Invoke Node. ❑ Right-click the stop tunnel on the event structure and select Create»Constant from the shortcut menu to create a False constant. ❑ Wire the diagram as shown in Figure 3-15.
© National Instruments Corporation
3-39
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
You may want to resize the Event Data Node to make space for your error and refnum wires. You should do this for each subsequent event.
Note
5. Create the Cut event.
Figure 3-16. Cut Event Tip The order the events are created in makes no difference, so it makes sense to create all of the events which can be easily duplicated from the New event case first.
❑ Right-click the border of the Event Structure and select Duplicate Event Case from the shortcut menu. ❑ Select Controls»Cut from the Event Sources list. ❑ Select Value Change from the Events list. ❑ Click the OK button. ❑ Click the method in the RichTextBox Invoke Node and change it to Cut(). 6. Create the Copy event.
LabVIEW Intermediate II Course Manual
3-40
ni.com
Lesson 3
Calling Objects in LabVIEW
Figure 3-17. Copy Event
❑ Right-click the border of the Event Structure and select Duplicate Event Case from the shortcut menu. ❑ Select Controls»Copy from the Event Sources list. ❑ Select Value Change from the Events list. ❑ Click the OK button. ❑ Click the method in the RichTextBox Invoke Node and change it to Copy(). 7. Create the Paste event.
Figure 3-18. Paste Event
❑ Right-click the border of the Event structure and select Duplicate Event Case from the shortcut menu. ❑ Select Controls»Paste from the Event Sources list.
© National Instruments Corporation
3-41
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Select Value Change from the Events list. ❑ Click the OK button. ❑ Click the method in the RichTextBox Invoke Node and change it to Paste(). 8. Create the Undo event.
Figure 3-19. Undo Event
❑ Right-click the border of the Event structure and select Duplicate Event Case from the shortcut menu. ❑ Select Controls»Undo from the Event Sources list. ❑ Select Value Change from the Events list. ❑ Click the OK button. ❑ Click the method in the RichTextBox Invoke Node and change it to Undo(). 9. Create the Open event.
LabVIEW Intermediate II Course Manual
3-42
ni.com
Lesson 3
Calling Objects in LabVIEW
Figure 3-20. Open Event
❑ Right-click the border of the Event structure and select Add Event Case from the shortcut menu. ❑ Select Controls»Open from the Event Sources list. ❑ Select Value Change from the Events list. ❑ Click the OK button. ❑ Place a File Dialog Express VI in the event case. ❑ Select Files only and Existing only in the Configure File Dialog dialog box. ❑ Click OK to exit the Configure File Dialog dialog box. The default values allow the user to select a single new or existing file. Expand the File Dialog Express VI and select the terminals shown in Figure 3-20 to make the VI easier to wire.
Tip
❑ Right-click the prompt input of the File Dialog Express VI and select Create»Constant from the shortcut menu. ❑ Enter Select File To Open in the string constant. ❑ Right-click the pattern label input of the File Dialog Express VI and select Create»Constant from the shortcut menu. ❑ Enter Rich Text Files in the string constant. ❑ Right-click the pattern(all files) input of the File Dialog Express VI and select Create»Constant from the shortcut menu.
© National Instruments Corporation
3-43
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Enter *.rtf in the string constant. ❑ Place a Compound Arithmetic function in the event case. ❑ Right-click the Compound Arithmetic function and select Change Mode»AND from the shortcut menu. ❑ Wire the exists output of the File Dialog Express VI to the top terminal of the Compound Arithmetic function. ❑ Wire the cancelled output of the File Dialog Express VI to the bottom terminal of the Compound Arithmetic function. ❑ Right-click the bottom terminal of the Compound Arithmetic function and select Invert from the shortcut menu. ❑ Place a Case structure in the event case. ❑ Wire the output of the Compound Arithmetic function to the case selector terminal. ❑ Place a Path to String function inside the True case of the Case Structure. ❑ Right click the .NET Refnum wire and select Create»Method» LoadFile(String path) from the shortcut menu to create a LoadFile Invoke Node. Place the Invoke Node in the True case. ❑ Place the Clear Specific Error VI located in the C:\Exercises\ LabVIEW Intermediate II\Word Processor directory in the False case of the Case structure. ❑ Right-click the Code input of the Clear Specific Error VI and select Create»Constant from the shortcut menu to create a numeric constant. ❑ Enter 43 for the value of the numeric constant. The Font Dialog Express VI returns error 43 when the user clicks the cancel button. The Word Processor VI handles the cancel error explicitly by ignoring the open command and returning control to the user interface. Therefore, you can safely discard this error to prevent it from stopping the program and displaying an error message.
Note
❑ Right-click the stop tunnel on the Event structure and select Create»Constant from the shortcut menu to create a False constant. ❑ Wire the diagram as shown in Figure 3-20 and Figure 3-21.
LabVIEW Intermediate II Course Manual
3-44
ni.com
Lesson 3
Calling Objects in LabVIEW
Figure 3-21. Word Processor Open Event, False Case
10. Create the Save event.
Figure 3-22. Save Event
❑ Right-click the border of the Event structure and select Duplicate Event Case from the shortcut menu. ❑ Select Controls»Save from the Event Sources list. ❑ Select Value Change from the Events list. ❑ Click the OK button. ❑ Double-click the FileDialog2 Express VI and change the Selection Mode options to Files Only and New or existing files. ❑ Click the OK button. ❑ Change the constant wired to prompt to Select File to Save. ❑ Delete the Compound Arithmetic function.
© National Instruments Corporation
3-45
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Place a Not function in the event case. ❑ Wire the cancelled output of the File Dialog Express VI to the Not function and wire the output of the Not function to the case selector terminal. ❑ In the True case of the Case structure, click the method in the RichTextBox Invoke Node and change it to SaveFile(String path). 11. Create the Font event.
Figure 3-23. Font Event
❑ Right-click the border of the Event structure and select Add Event Case from the shortcut menu. ❑ Select Controls»Font from the Event Sources list. ❑ Select Value Change from the Events list. ❑ Click the OK button. ❑ Place the Font Dialog VI that you created in Exercise 3-4 inside the event case. The VI is located in the C:\Exercises\LabVIEW Intermediate II\Font Dialog directory. ❑ Place a Case structure in the event case. ❑ Wire the DialogResult output of the Font Dialog VI to the case selector terminal.
LabVIEW Intermediate II Course Manual
3-46
ni.com
Lesson 3
Calling Objects in LabVIEW
❑ Right-click the .NET Refnum wire and select Create»Property» SelectionFont from the shortcut menu to create a SelectionFont Property Node. Place the Property Node in the OK case of the case structure. ❑ Resize the Property Node to accept another property and set the second property to SelectionColor. ❑ Right-click the Property Node and select Change All to Write from the shortcut menu. ❑ Change to the None case of the Case structure. ❑ Change the case name to "Cancel", Default. ❑ Wire the error and refnum wires through the Cancel case of the case structure. ❑ Right-click the .NET Refnum wire and select Create»Method» Focus from the shortcut menu to create a Focus Invoke Node. Place the Invoke Node to the right of the Case structure. ❑ Right-click the stop terminal on the Event structure and select Create»Constant from the shortcut menu to create a False constant. ❑ Wire the diagram as shown in Figure 3-23. 12. Create the Find event.
Figure 3-24. Find Event
❑ Right-click the border of the Event structure and select Add Event Case from the shortcut menu. ❑ Select Controls»Find from the Event Sources list.
© National Instruments Corporation
3-47
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Select Value Change from the Events list. ❑ Click the OK button. ❑ Place a Prompt User for Input Express VI in the event case. Configure the Express VI as shown in Figure 3-25 and click the OK button.
Figure 3-25. Prompt User Configuration
❑ Place a Case structure in the event case. ❑ Wire the OK output of the Find Text Express VI to the case selector terminal. ❑ Right click the .NET Refnum wire and select Create»Method» Find(String str) from the shortcut menu to create a Find Invoke Node. Place the Invoke Node in the True case of the Case structure. ❑ Right click the .NET Refnum wire and select Create»Method» Select(Int32 start, Int32 length) from the shortcut menu to create a Select Invoke Node. Place the Invoke Node in the True case of the Case structure. ❑ Right click the .NET Refnum wire and select Create»Method» Focus() from the shortcut menu to create a Focus Invoke Node. Place the Invoke Node in the True case of the case structure.
LabVIEW Intermediate II Course Manual
3-48
ni.com
Lesson 3
Calling Objects in LabVIEW
❑ Place a String Length function in the True case of the Case structure. ❑ Right-click the stop terminal on the Event structure and select Create»Constant from the shortcut menu to create a False constant. ❑ Wire the diagram as shown in Figure 3-24. Wire the error and refnum wires through the False case of the case structure. 13. Place the button terminals in the event cases. Place each button terminal in the corresponding event case because the buttons use a latch Boolean mechanism. If the buttons are not in the event cases, they are not read when clicked, and remain pressed. Wait until the end of implementation to place the buttons in the cases to prevent creating duplicate buttons when you duplicate event cases. Note
❑ Place the Find terminal in the Find event case. ❑ Repeat this process for each of the other buttons. 14. Save the VI.
Testing 1. Test basic functionality. ❑ Run the VI. ❑ Enter text in the text box. ❑ Ensure that word wrap works by typing to the end of a line. 2. Test the text box scrollbar. ❑ Press the key repeatedly until there is enough text for the vertical scrollbar to appear. ❑ Use the scrollbar to scroll to the top of the document. 3. Test the Save function. ❑ Click the Save button. ❑ Click the Cancel button. The program should not stop or display an error. ❑ Click the Save button again. ❑ Navigate to the C:\Exercises\LabVIEW Intermediate II\ Word Processor directory and enter test.rtf for the file name.
© National Instruments Corporation
3-49
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Click the OK button. 4. Test the New function. ❑ Click the New button. The text field should clear and the scrollbar should disappear. 5. Test the Open function. ❑ Click the Open button. ❑ Click the Cancel button. The program should not stop or display an error. ❑ Click the Open button. ❑ Select C:\Exercises\LabVIEW Intermediate II\ Word Processor\test.rtf. ❑ Click the OK button. The text you entered and saved earlier should be displayed. 6. Test the Font function. ❑ Close the block diagram of the VI if it is still open, also close any other unused windows. This makes it easier to find the font dialog if it does not appear as the front window. ❑ Click the New button. ❑ Click the Font button and select the font dialog. Remember that the font dialog may appear behind other windows. ❑ Select a Font, a style, a size and a color different from the default values. ❑ Click the Cancel button. The cursor should return to the text box. ❑ Enter a few words of text. Because you clicked the Cancel button, the text should have the default font, not the font you selected in the font dialog. ❑ Click the Font button again and select the font dialog. ❑ Select a Font, a style, a size and a color different from the default values. ❑ Click the OK button. The cursor should return to the text box.
LabVIEW Intermediate II Course Manual
3-50
ni.com
Lesson 3
Calling Objects in LabVIEW
❑ Enter a few more words of text. The original text should be unchanged, but the new text should use the font, size, style, and color you selected. ❑ Use the mouse to select an area of text you have already entered. Try selecting an area around the change in fonts. ❑ Click the Font button and select the Font Dialog. ❑ Select a Font, a style, a size, and a color different from both the default values and the values you selected before. ❑ Click the OK button. The selected text should now have the new text characteristics. 7. Test the Find function. ❑ Click the Find button. ❑ Click the Cancel button. The cursor should be removed from the text box but nothing else should happen. ❑ Click the Find button again. Do not search for words which are not in your text box. You have not included error handling checks for this condition and so searching for a word which is not present causes your program to return an error and exit. Refer to the Challenge section for more information.
Caution
8. Enter a word which is in your text box. ❑ Click the OK button. The first instance of the word you searched for should be selected. 9. Test the Cut function. ❑ Ensure that a word is still selected in the text box and click the Cut button. The selected word should disappear. 10. Test the Paste function. ❑ Place the cursor at the end of the text you have entered. ❑ Click the Paste button. The word you cut should appear at the cursor location. 11. Test the Copy function.
© National Instruments Corporation
3-51
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Select an area of text. ❑ Click the Copy button. The text should remain in place. ❑ Move the cursor to a different location. ❑ Click the Paste button. The copied text should appear. 12. Test the Undo function. ❑ Click the Undo button. The text you just pasted should disappear. ❑ Click the Undo button repeatedly. The changes you have made should be reversed in order. 13. Test the Close function ❑ Click the Close button at the upper right hand corner of the window. The program should stop, but the VI should not close.
Challenge Currently the Find button stops the program with an error if a string which is not in the text box is entered. Modify the find event so that an error is not generated and so that a meaningful dialog is displayed to the user if the text is not found. Tip
The Find RichTextBox method returns a value of –1 if it does not find the string. There are many more features you can add to your word processor if time allows. Some suggestions include: •
Add a Redo function.
•
Add a display to the bottom of the window to display the number of lines and number of characters.
•
Add Run-Time menus to perform the functions on the toolbar.
•
Allow the find to search for instances of a string beyond the first.
•
Add an options page to your program which allows the user to select things such as the background color and whether word wrap or horizontal scroll bars are used.
•
Allow the user to resize the window. Make the text box resize, but prevent the resize from affecting the toolbar.
•
Allow the text box to open and close plain text files.
End of Exercise 3-5
LabVIEW Intermediate II Course Manual
3-52
ni.com
Lesson 3
Calling Objects in LabVIEW
G. Registering .NET Events Events are the actions taken on an object, such as clicking a mouse, pressing a key, or receiving notifications about things such as running out of memory or tasks completing. Whenever these actions occur to the object, the object sends an event to alert the .NET container along with the event-specific data. The .NET object defines the events available for an object. To use .NET events in an application, you must register for the event and handle the event when it occurs. .NET event registration is similar to dynamic event registration. However, the architecture of a .NET event VI is different than the architecture of an event-handling VI. The following components make up a typical .NET event VI: •
.NET object for which you want to generate an event.
•
Register Event Callback function to specify and register for the type of event you want to generate. The Register Event Callback function is a resizable node capable of handling multiple events, similar to the Register For Events function.
•
Callback VI that contains the code you write to handle the event you specify.
When you wire a .NET object to the Register Event Callback function and specify the event you want to generate for that object, you are registering the .NET object for that event. After you register for the event, create a callback VI that contains the code you write to handle the event. Different events may have different event data formats so changing the event after you create a callback VI might break wires on the block diagram. Select the event before you create the callback VI. You can handle events on .NET controls in a container. For example, you can place a calendar control in a .NET container and specify that you want to handle a DoubleClick event for the items displayed in the calendar.
Handling .NET Events You must create a callback VI to handle events from .NET objects when the objects generate the registered events. The callback VI runs when the event occurs. To create a callback VI, right-click the VI Ref input of the Register Event Callback function and select Create Callback VI from the shortcut menu. LabVIEW creates a reentrant VI. Open the VI and edit the block diagram to handle the event. The callback VI contains the following elements:
© National Instruments Corporation
3-53
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
•
Event Common Data contains the following elements: –
Event Source is a numeric control that specifies the source of the event, such as LabVIEW or .NET. A value of 2 indicates a .NET event.
–
Event Type specifies which event occurred. This is an enumerated type for user interface events and a 32-bit unsigned integer type for .NET and other event sources. For .NET events, the event type represents the method code, or ID, for the event registered.
–
Time Stamp is the time stamp in milliseconds that specifies when the event was generated.
•
Control Ref is a reference to the .NET object on which the event occurred.
•
Event Data is a cluster of the parameters specific to the event the callback VI handles. LabVIEW determines the appropriate Event Data when you select an event from the Register Event Callback function. If an event does not have any data associated with it, LabVIEW does not create this control in the callback VI.
•
Event Data Out is a cluster of the modifiable parameters specific to the event the callback VI handles. This element is available only if the .NET event has output parameters.
•
(Optional) user parameter is data that you want to pass to the callback VI when the .NET object generates the event.
You can use an existing VI as a callback VI as long as the connector pane of the VI you intend to use matches the connector pane of the event data. The callback VI must be reentrant, and the reference to the callback VI must be strictly typed.
Note
You cannot make synchronous calls to non-modal dialog boxes from a callback VI. You must asynchronously call a non-modal dialog box from a callback VI by invoking a Run VI method on the dialog and wiring a FALSE Boolean constant to the Wait Until Done input of the method.
LabVIEW Intermediate II Course Manual
3-54
ni.com
Lesson 3
Exercise 3-6
Calling Objects in LabVIEW
Auto Save
Goal Use .NET events to create a timer.
Scenario Word processors commonly contain an Auto Save feature that periodically saves the work in them. This features helps users avoid losing data in the event of a crash or power failure. Add an auto save function to the word processor. This function should save the document once every 30 seconds.
Design There are a number of ways to implement an auto save feature. You could use the Timeout event of the LabVIEW Event structure to save the contents of the text box. However, the timeout event occurs only after no events have fired for the specified time period. Therefore, if you configured the Timeout to 30 seconds, the program would only auto save if the user had not used any other functions for 30 seconds. You could use a smaller timeout, however you would need to track and check the amount of time since the last auto save. This would increase the complexity and decrease the performance of the program. You could use a second LabVIEW loop to implement the auto save. The second loop could call the save function directly by branching the .NET refnum, unfortunately, this could lead to errors if the first loop finished and closed the reference before the second loop finished. The second loop could also communicate with the main loop by firing a User Event every 30 seconds. This implementation is fairly elegant, however it significantly increases the complexity of the program. Furthermore, any implementation with a second loop must deal with a tradeoff between timing accuracy and increased processor usage from regularly checking the elapsed time. A better solution would be to asynchronously register an event which occurs at a specified period. You can do this by using the .NET Timer Object from the System.Timers Assembly. You can create a Timer object, specify a time interval and then the Timer periodically fires .NET events at the interval specified. You can handle the .NET event in LabVIEW by specifying a subVI to use as an event handler. By passing a reference to the RichTextBox to this subVI, you can asynchronously call the Save method every 30 seconds without having to program the timing mechanism in LabVIEW.
© National Instruments Corporation
3-55
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
Auto Save Inputs and Outputs Table 3-5. Auto Save Inputs and Outputs
Type
Name
Properties
Default Value
Cluster Control
error in
Error Cluster
No Error
.NET Refnum Control
TextBox reference
.NET Reference, System.Windows.Forms.RichTextBox class
Not a refnum
Numeric Control
Interval (ms)
Double precision numeric
30000
.NET Refnum Indicator
Timer reference
.NET Reference, System.Timers.Timer class
Not a refnum
.NET Refnum Indicator
TextBox reference out
.NET Reference, System.Windows.Forms.RichTextBox class
Not a refnum
Cluster Indicator
error out
Error Cluster
No Error
Timer Object Description The Timer class generates recurring .NET events at a frequency which you specify. You can create a Timer object by selecting the Timer object from the System.Timers assembly using a .NET Constructor Node. One of the constructors for the Timer takes a numeric value to specify the interval. Calling this constructor is the easiest way to initialize a Timer. Use the following event and method from the Timer class in this exercise. Full documentation for the Timer and other objects included in the .NET Framework can be found on MSDN or in the documentation for Microsoft Visual Studio .NET. Start Method—Calling this method instructs the timer to begin generating events. You can stop the event generation by calling the Stop method or by destroying the Timer reference using a Close Reference function. Elapsed Event—After a Timer has started, it repeatedly generates the Elapsed event. The time between events is equal to the Interval property, which can be set directly, or initialized through the class Constructor.
Implementation 1. Create the front panel. ❑ Open a blank VI and save it as Auto Save.vi in the C:\Exercises\LabVIEW Intermediate II\ Auto Save directory.
LabVIEW Intermediate II Course Manual
3-56
ni.com
Lesson 3
Calling Objects in LabVIEW
❑ Create the Interval control as described in Table 3-5. ❑ Create the Error In control as described in Table 3-5. ❑ Create the Error Out control as described in Table 3-5. ❑ Place a .NET Refnum on the front panel. ❑ Right-click the .NET Refnum and choose Select .NET Class»Browse from the shortcut menu. ❑ Select System.Windows.Forms from the Assembly pull-down menu. ❑ Double-click the System.Windows.Forms item in the Objects list and select RichTextBox. ❑ Click the OK button. ❑ Name the control TextBox Reference. ❑ Create a copy of the TextBox Reference control. Name the copy TextBox Reference out. ❑ Right-click the TextBox Reference Out control and select Change to Indicator from the shortcut menu. ❑ Arrange the front panel in a logical manner. 2. Create Timer object.
Figure 3-26. Completed Auto Save Block Diagram
❑ Open the VI block diagram. ❑ Place a Constructor Node on the block diagram. The Select .NET Constructor dialog box should appear. ❑ Select System from the Assembly pull-down menu.
© National Instruments Corporation
3-57
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Double-click the System.Timers item in the Objects list and select Timer to add Timer constructors to the Constructors list. ❑ Select Timer(Double interval) from the Constructors list. ❑ Click the OK button. ❑ Connect the Interval control to the interval input of the Constructor Node as shown in Figure 3-26. 3. Register a handler for the Elapsed event. ❑ Place a Register Event Callback function on the block diagram. ❑ Wire the reference output of the Constructor Node to the Event input of the Register Event Callback function as shown in Figure 3-26. ❑ Click the Event input of the Register Event Callback function and select Elapsed(Object sender, ElapsedEventArgs e). ❑ Wire the TextBox Reference to the user parameter input of the Register Event Callback function as shown in Figure 3-26. 4. Start the Timer. ❑ Right-click the reference output of the Constructor Node and select Create»Method»Start() from the shortcut menu. ❑ Right-click the reference output of the Start Invoke Node and select Create»Indicator from the shortcut menu. Name the indicator Timer Reference. ❑ Wire the block diagram as shown in Figure 3-26. You create the VI Ref constant in the following steps.
LabVIEW Intermediate II Course Manual
3-58
ni.com
Lesson 3
Calling Objects in LabVIEW
5. Create the Callback VI.
Figure 3-27. Auto Save Callback Block Diagram
❑ Save the Auto Save VI. ❑ Right-click the VI Ref input of the Register Event Callback node and select Create Callback VI from the shortcut menu. This opens a new VI with the appropriate connector pane for this event callback. ❑ Save the callback VI as Auto Save Callback.vi in the C:\Exercises\LabVIEW Intermediate II\Auto Save
directory. ❑ Open the block diagram of the callback VI. ❑ Right-click the TextBox reference terminal and select Create» Method»SaveFile(String path) from the shortcut menu to create a SaveFile Invoke Node. ❑ Place a Temporary Directory constant on the block diagram. ❑ Place a Build Path function on the block diagram. ❑ Right-click the name or relative path input of the Build Path function and select Create»Constant from the shortcut menu. Enter Word Processor Autosave.rtf for the value of the constant. ❑ Place a Path to String function on the block diagram. ❑ Wire the block diagram as shown in Figure 3-27. ❑ Save and close the Auto Save Callback VI. 6. Build the icon and connector pane for the Auto Save VI. ❑ Return to the front panel of the Auto Save VI.
© National Instruments Corporation
3-59
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Right-click the VI Icon and select Edit Icon from the shortcut menu. ❑ In the Icon Editor select Edit»Import Picture from File. Select C:\Exercises\LabVIEW Intermediate II\ Word Processor\Controls\Images\Save.gif as the file to
import. ❑ Double-click the Selection tool to select the entire icon. ❑ Select Edit»Paste. ❑ Double-click the Rectangle tool to create a black box around the icon. ❑ Copy the 256 Colors icon into the 16 Colors and B&W icons by selecting each and then clicking the 256 Colors button under the Copy from section. ❑ Click the OK button to exit the Icon Editor. The icon should resemble Figure 3-28.
Figure 3-28. Auto Save Icon
❑ Build the connector pane as shown in Figure 3-29.
Figure 3-29. Auto Save Connector Pane
7. Save the VI.
LabVIEW Intermediate II Course Manual
3-60
ni.com
Lesson 3
Calling Objects in LabVIEW
8. Add auto save functionality to the Word Processor.
Figure 3-30. Word Processor with Auto Save Block Diagram
❑ Open the Word Processor VI located in the C:\Exercises\ LabVIEW Intermediate II\Word Processor directory. ❑ Place the Auto Save VI on the block diagram of the Word Processor VI. ❑ Place a Close Reference function on the block diagram of the Word Processor VI. ❑ Right-click the Interval input of the Auto Save VI and select Create»Constant from the shortcut menu. The constant should default to 30000. ❑ Wire the diagram as shown in Figure 3-30. 9. Save the VI.
Testing 1. Navigate to the Windows\Temp directory. ❑ Minimize all programs to get to the desktop of the computer. Tip
Press the keys to display the desktop. ❑ Right-click the My Computer icon and select Properties from the shortcut menu to open the System Properties dialog box. ❑ Select the Advanced tab and click the Environment Variables button.
© National Instruments Corporation
3-61
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
❑ Select TEMP under User variables. If TEMP does not exist under User variables, locate it under System variables. ❑ Click the Edit button. ❑ Select all the text in the Variable value field then right-click the text and select Copy from the shortcut menu. ❑ Click the Cancel button. Do not change the value of the variable. ❑ Click the Cancel button twice to exit the Environment Variables and System Properties windows. This process shows you how to check the value of any system variable. However, an easier way to get the value of the TEMP variable would be to simply attach an indicator to a Temporary Directory constant in LabVIEW.
Tip
❑ Open Windows Explorer. ❑ Paste the temporary directory path into the Address field and press . Leave the Windows Explorer window open. Note If you try to browse to the temporary directory instead of pasting the path you may need to show hidden files from the Windows Explorer folder view options.
2. Test the Auto Save function. ❑ Run the Word Processor VI. ❑ Enter text into the text box. ❑ Wait 30 seconds and then switch to the Windows Explorer window. ❑ Double click the Word Processor Autosave.rtf and verify that your text shows up in the file.
End of Exercise 3-6
LabVIEW Intermediate II Course Manual
3-62
ni.com
Lesson 3
Calling Objects in LabVIEW
Summary •
COM and .NET are two different Windows communication platforms.
•
ActiveX is based on the COM platform and is an extension of OLE/OCX.
•
LabVIEW supports ActiveX as a client and/or a server and supports ActiveX containers.
•
An ActiveX server is an application that exposes objects.
•
An ActiveX client accesses objects that have been exposed by an ActiveX server.
•
LabVIEW allows you to write VIs that function as ActiveX clients.
•
Complete the following steps to create an ActiveX client VI. –
Open a reference to the Automation Server.
–
Use the returned reference to get/set properties and/or invoke methods.
–
Close the reference to the Automation Server.
•
The Microsoft object hierarchy defines the way objects are arranged relative to one another.
•
LabVIEW exports two classes of objects—Application class and Virtual Instrument class.
•
LabVIEW can act as a .NET client allowing access to .NET assemblies.
•
Assemblies are DLLs and executables you build using the .NET Common Language Runtime (CLR).
•
ActiveX events allow programmers to receive notification of a specific occurrence and then act accordingly. This is implemented through a Callback VI.
•
ActiveX events do not use the Event structure.
© National Instruments Corporation
3-63
LabVIEW Intermediate II Course Manual
Lesson 3
Calling Objects in LabVIEW
Notes
LabVIEW Intermediate II Course Manual
3-64
ni.com
4
Broadcasting Data
User Datagram Protocol, or UDP, provides a means for communicating short packets of data to one or more recipients. This lesson describes using UDP and LabVIEW to implement the broadcast model.
Topics A. Broadcasting Data Overview B. Implementing Broadcast Models
© National Instruments Corporation
4-1
LabVIEW Intermediate II Course Manual
Lesson 4
Broadcasting Data
A. Broadcasting Data Overview Broadcasting data is a method of placing data onto a network. Broadcasting data is not concerned with the network entities who are listening to the data being broadcast. Also, broadcasting data cannot guarantee that the data reaches its destination. The User Datagram Protocol, otherwise known as UDP, is the networking protocol that implements broadcasting.
Broadcast Communication Model Definition UDP provides simple, low-level communication among processes on computers. Processes communicate by sending datagrams to a destination computer or port. A port is the location where you send data. IP handles the computer-to-computer delivery. After the datagram reaches the destination computer, UDP moves the datagram to its destination port. If the destination port is not open, UDP discards the datagram. UDP shares the same delivery problems of IP. Use UDP in applications in which reliability is not critical. For example, an application might transmit informative data to a destination frequently enough that a few lost segments of data are not problematic. The broadcast model is very similar to a radio tower broadcasting a signal. The radio station doesn’t need to know who is listening to the broadcast signal. Also, there is the possibility that the listener is not able to receive the signal due to interference from other signals. The advantage to the broadcast model is there is no limit to the number of listeners, similar to a radio broadcast, as shown in Figure 4-1.
LabVIEW Intermediate II Course Manual
4-2
ni.com
Lesson 4
101.5
101.5
Broadcasting Data
MHz
99.1 MHz
MHz
Figure 4-1. Broadcast Model
Broadcast Model Definition Because UDP is not a connection-based protocol such as TCP, you do not need to establish a connection with a destination before you send or receive data. Instead, you specify the destination for the data when you send each datagram. Operating systems do not report transmission errors. Use the UDP Open function to open a UDP socket on a port. The number of simultaneously open UDP ports depends on the operating system. The UDP Open function returns a network connection refnum that uniquely identifies the UDP socket. Use this connection refnum to refer to this socket in subsequent VI calls. Use the UDP Write function to send data to a destination, and use the UDP Read function to read that data. Each write operation requires a destination address and port. Each read operation contains the source address and port. UDP preserves the datagram bytes that you specified for each command you send.
© National Instruments Corporation
4-3
LabVIEW Intermediate II Course Manual
Lesson 4
Broadcasting Data
In theory, you can send datagrams of any size. However, you typically would not use UDP to send large datagrams because it is not as reliable as TCP. When you finish all communications on a port, use the UDP Close function to free system resources.
UDP Communication Capabilities and Issues Unlike TCP, UDP does not guarantee the safe arrival of data to the destination. Furthermore, data sent in multiple packets may not arrive at the destination in the order they were sent. Therefore you should use UDP only to send short, non-critical messages to one or more destinations. The size limit of each packet is approximately 65K. Because UDP has little communication control, you do not need an explicit connection to the other side of communication to send or receive data. A receiver listens on a specified UDP port to receive any data broadcast to that port. In the following example, any data received is printed on a string indicator, along with the source address and port. If a timeout occurs on the UDP read function (after 250 ms) the VI ignores the error, nothing prints to the indicator, and the loop returns to the beginning and listens for data on the UDP port. Notice that the UDP connection must be opened and closed with the corresponding UDP functions.
The broadcaster is simpler because it does not require a wait. The broadcaster opens the UDP port, sends the data, and closes the port.
LabVIEW Intermediate II Course Manual
4-4
ni.com
Lesson 4
Broadcasting Data
Even though UDP has reliability issues, some applications may be better suited to UDP for the following reasons: •
No connection establishment—Unlike TCP, UDP does not wait to confirm a connection before transferring data, so no delay is introduced.
•
No connection state—Because UDP does not maintain a connection state, which includes send and receive buffers and congestion control settings, a UDP broadcaster can support more receivers.
•
Small overhead—UDP segments have 8 bytes of overhead, compared to 20 bytes of overhead for TCP segments.
•
Unregulated send rate—UDP send rate is only limited by the rate of data generation, CPU, clock rate, and access to Internet bandwidth
UDP Communication Reliability Reliability can be an issue with UDP. Network congestion can lead to data loss if the router buffer overflows. It is possible to build reliability into the UDP application by adding processes that acknowledge and retransmit data.
B. Implementing Broadcast Models You can create a UDP-based distributed system by using the LabVIEW UDP VI and functions.
Creating a Broadcast Model Distributed System You can use the UDP functions to communicate to a single client (singlecast) or to all computers on the subnet through a broadcast. If you want to communicate to multiple specific computers, you must configure the UDP functions to iterate through a list of clients. Using this technique creates duplicate network traffic because LabVIEW sends a separate copy of the data to each client and maintains a list of clients interested in receiving the data. Use multicasting to communicate between a single sender and multiple clients on a network without requiring the sender to maintain a list of clients or send multiple copies of the data to each client. To receive data broadcast by a multicast sender, all clients must join a multicast group. The sender does not have to join a group to send data. The sender specifies a multicast IP address, which defines a multicast group. Multicast IP addresses are in the 224.0.0.0 to 239.255.255.255 range. When a client wants to join a multicast group, it subscribes to the multicast IP address of the group. After subscribing to a multicast group, the client receives data sent to the multicast IP address. To multicast in LabVIEW, use the UDP Multicast Open VI to open connections capable of reading, writing, or reading and writing UDP data.
© National Instruments Corporation
4-5
LabVIEW Intermediate II Course Manual
Lesson 4
Broadcasting Data
Specify the time-to-live (TTL) for writing data, the multicast address for reading data, and the multicast port number for reading and writing data. The default TTL is 1, which means LabVIEW sends the datagram only to the local subnet. When a router receives a multicast datagram, it decrements the datagram TTL. If the TTL is greater than 1, the router forwards the datagram to other routers. The following table lists what action occurs to a multicast datagram when you specify a value for the time-to-live parameter. 0
Datagram remains on the host computer.
1
Datagram sent to every client on the same local subnet that subscribes to that IP address. Hubs/repeaters and bridges/ switches forward the datagram. Routers do not forward the datagram if the TTL is 1.
Refer to the following VIs for examples of using UDP multicasting: •
UDP Multicast Receiver VI: labview\examples\comm\UDP.llb
•
UDP Multicast Sender VI: labview\examples\comm\UDP.llb
UDP VI and Functions Use the UDP VI and functions to exchange data with devices on a remote UDP socket. •
UDP Open—Opens a UDP socket on the port. Close the socket with the UDP Close function. Use the UDP Multicast Open VI instead of this function to open connections capable of reading, writing, or reading and writing data to or from UDP Multicast sockets.
•
UDP Multicast Open—Opens a UDP multicast socket on the port. You must manually select the polymorphic instance you want to use. Use the pull-down menu to select an instance of this VI. You can select from Read-Only, Read-Write and Write-Only instances.
•
UDP Read—Reads a datagram from a UDP socket, returning the results in data out. The function returns data when it receives any bytes, and waits the full timeout ms only if it receives no bytes.
•
UDP Write—Writes to a remote UDP socket.
•
UDP Close—Closes a UDP socket.
LabVIEW Intermediate II Course Manual
4-6
ni.com
Lesson 4
Exercise 4-1
Broadcasting Data
VI Statistics Broadcast
Goal Transmit data using a UDP broadcast.
Scenario In Exercise 2-2 you created a VI to gather information about the VIs running on a computer. Now you need to send some of this data to several other computers so that they can continuously monitor the VI usage on the computer in question. The number of VIs in memory and the number of VIs running should be broadcast to a location where multiple computers can read them.
Design Inputs and Outputs Table 4-1. VI Statistics Report Inputs and Outputs
Type
Name
Properties
Default Value
String Control
Multicast Address
—
234.5.7.9
Numeric Control
Number Running Port
Unsigned 16-bit Integer 58431
Numeric Control
Number in Memory Port
Unsigned 16-bit Integer 58432
Numeric Control
Local Port
Unsigned 16-bit Integer 58433
One technique for displaying the data to multiple receiver computers would be to publish an HTML report like the one in Exercise 3-1 and then place the report on a web server. However, this requires the computer in question to run a web server, which creates a number of potential security and logistical problems. Furthermore, in order to continuously monitor the VI usage, the data must be regularly updated. In order for the receivers to view updated data they would either have to regularly update their browsers or the web page would have to update using a script. In addition, if the other computers needed to process or programmatically act upon the data, they would need to extract it from the web page. An alternate method for making the data available to other computers is to initiate a UDP Multicast. A UDP Multicast, which you use for this exercise, avoids the issues discussed in the previous paragraph. One disadvantage is that you need a specific UDP receiver to access the data, instead of a generic web browser.
© National Instruments Corporation
4-7
LabVIEW Intermediate II Course Manual
Lesson 4
Broadcasting Data
In order to convert the application to a UDP broadcaster, perform the following tasks: 1. Convert the VI statistics application to run continuously by adding a While Loop. The data should update once per second. 2. Open a UDP multicast session. 3. Write the data to the UDP multicast address. Use separate ports for the number of VIs running and the number of VIs in memory. 4. Close the UDP multicast session.
Implementation 1. Convert the application to run continuously.
Figure 4-2. Continuous VI Statistics
❑ Open the VI Statistics VI located in the C:\Exercises\LabVIEW Intermediate II\VI Statistics directory. You created this VI in Exercise 2-2. ❑ Save the VI as VI Statistics Broadcast.vi in the C:\Exercises\LabVIEW Intermediate II\ VI Statistics Broadcast directory. Select the Substitute
copy for original option in the Save As dialog box. ❑ Open the block diagram. ❑ Add a While Loop between the open and close functions for the application reference as shown in Figure 4-2. Use shift registers for the application reference and the error wire.
LabVIEW Intermediate II Course Manual
4-8
ni.com
Lesson 4
Broadcasting Data
Opening and closing the application reference outside of the loop saves processor time because the reference does not have to be re-opened during every loop iteration.
Tip
❑ Right-click the stop terminal of the While Loop and select Create»Control from the shortcut menu. ❑ Place a Wait Until Next ms Multiple function in the loop. ❑ Create a U32 constant with the value 1000 and wire it to the Wait Until Next ms Multiple function. ❑ Run the VI. The VIs Open and VIs Running indicators should now update each time you open or run a VI. 2. Modify the front panel.
Figure 4-3. VI Statistics Broadcast Front Panel
❑ Delete the VI Report, VIs Open, and VIs Running indicators and the Machine Name control. ❑ Create the Multicast Address, Number Running Port, Number in Memory Port, and Local Port controls as described in Table 4-1. ❑ Arrange the front panel as shown in Figure 4-3. 3. Add UDP communication.
© National Instruments Corporation
4-9
LabVIEW Intermediate II Course Manual
Lesson 4
Broadcasting Data
Figure 4-4. Completed VI Statistics Broadcast Block Diagram
❑ Place a UDP Multicast Open VI to the left of the While Loop. ❑ Click the polymorphic VI selector of the UDP Multicast Open VI and select Write Only. ❑ Place two UDP Write functions inside the While Loop. ❑ Place a UDP Close function to the right of the While Loop. ❑ Place two Number to Decimal String functions inside the While Loop. Use the Number to Decimal String function to format the VIs Running and VIs in memory data into strings so you can transfer them using UDP. ❑ Place a String to IP function to the left of the While Loop. This function allows you to convert the Multicast Address into a numeric IP network address that can be read by the UDP functions. 4. Stop the broadcast in the event of an error. ❑ Place an Unbundle by Name function inside the While Loop. ❑ Place an Or function inside the While Loop. ❑ Wire the diagram as shown in Figure 4-4. 5. Save the VI.
LabVIEW Intermediate II Course Manual
4-10
ni.com
Lesson 4
Broadcasting Data
Testing 1. Run the VI. ❑ Switch to the front panel of the VI. ❑ Close all other VIs. ❑ Run the VI. 2. Inspect the VI Statistics Receiver VI. ❑ Open the VI Statistics Receiver VI located in the C:\Exercises\ LabVIEW Intermediate II\VI Statistics Broadcast
directory. ❑ Open the block diagram of the VI. ❑ Inspect the block diagram of the VI. Notice the differences between UDP Broadcasters and UDP Receivers.
Figure 4-5. VI Statistics Receiver
3. Test UDP communication. ❑ Run the VI Statistics Receiver VI. The VI should begin charting the open VIs. ❑ Open an additional VI and then run the VI. Observe the changes to the chart as the Broadcaster updates the values. ❑ If another machine is available, run the transmitter on one machine and the receiver on another.
© National Instruments Corporation
4-11
LabVIEW Intermediate II Course Manual
Lesson 4
Broadcasting Data
Challenge If you close a VI while the application is running, the close may occur between when the VI reads the list of open VIs and when it opens a reference to the closed VI. If this occurs, the Open VI Reference function generates error code 1004, VI is Not in Memory. In the current implementation, this error stops the application and displays a message. Implement an error check after the Open VI Reference function to check for and handle this error. If the error occurs, the application continues running, but the number of VIs in memory does not increment for that particular VI.
End of Exercise 4-1
LabVIEW Intermediate II Course Manual
4-12
ni.com
Lesson 4
Broadcasting Data
Summary •
UDP provides a simple, low-level communication protocol to send data on a network.
•
UDP broadcasts data, but does not guarantee that the data reaches its destination.
•
Use UDP to create an efficient, distributed communication system.
© National Instruments Corporation
4-13
LabVIEW Intermediate II Course Manual
Lesson 4
Broadcasting Data
Notes
LabVIEW Intermediate II Course Manual
4-14
ni.com
Serving Data to a Client Using TCP/IP
5
You can use TCP/IP to communicate over single networks or interconnected networks. The individual networks can be separated by large geographical distances. TCP/IP routes data from one network or Internet-connected computer to another. Because TCP/IP is available on most computers, it can transfer information among diverse systems.
Topics A. TCP/IP Overview B. Implementing the Client/Server Model
© National Instruments Corporation
5-1
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
A. TCP/IP Overview TCP ensures reliable transmission across networks, delivering data in sequence without errors, loss, or duplication. TCP retransmits the datagram until it receives an acknowledgment. TCP is a connection-based protocol, which means that sites must establish a connection before transferring data. The data transmission occurs between a client and a server. TCP permits multiple, simultaneous connections. You initiate a connection by waiting for an incoming connection or by actively seeking a connection with a specified address. In establishing TCP connections, you have to specify the address and a port at that address. Different ports at a given address identify different services at that address.
Client/Server Model Overview The client/server model is a common model for networked applications. In this model, one set of processes (clients) requests services from another set of processes (servers) as shown in Figure 5-1. Server
Client
Service Provider
Service Requestor
Figure 5-1. Client/Server Model
Client Model Overview Figure 5-2 shows the flowchart model for TCP/IP communication in LabVIEW.
No Open Connection to Server
Execute Command on Server
Done? Yes
Close Connection to Server
Figure 5-2. LabVIEW TCP/IP Client Model
For higher performance, you can process multiple commands after you open the connection. After executing the commands, you can close the
LabVIEW Intermediate II Course Manual
5-2
ni.com
Lesson 5
Serving Data to a Client Using TCP/IP
connection. This flowchart serves as a model to demonstrate implementing a given protocol in LabVIEW.
Client Model Communication Steps The client model allows a client to communicate to a server by first opening a connection to the server, sending a command to the server, receiving a command from the server, and then closing the connection to the server. Open a Connection to the Server The first step is to open a connection to the server. The client must open a network port on the local machine, and then specify the IP address of the server to connect to. Send Commands to the Server After a connection is established to the server, the client sends a message that the server recognizes. This message causes the server to perform work. Receive Responses from the Server After a message is sent to the server, the client needs to know that the message was accepted and work was performed by the server. This occurs by the server responding to the client. Close the Connection to the Server and Report Errors After all of the commands are sent to the server, the client closes the connection, and reports errors.
Server Model Overview Figure 5-3 shows a simplified model for a server in LabVIEW.
Wait for a Connection
Initialize Server
Wait for a Command No Return Command
Done?
Execute Command
Yes
Close Connection
Figure 5-3. LabVIEW TCP/IP Server Model
© National Instruments Corporation
5-3
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
LabVIEW repeats this entire process until it is shut down remotely by sending a command to end the VI. This VI does not report errors. It might return a response indicating that a command is invalid, but it does not display a dialog box when an error occurs. Because a server might be unattended, consider carefully how the server should handle errors. You probably do not want to display a dialog box on an error because it requires user interaction at the server. Someone would need to click the OK button. However, you might want LabVIEW to write a log of transactions and errors to a file or a string. You can increase performance by allowing the connection to stay open. You can receive multiple commands this way, but it also blocks other clients from connecting until the current client disconnects. You can restructure the block diagram to handle multiple clients simultaneously, as shown in Figure 5-4.
Figure 5-4. Handling Multiple Clients Simultaneously
The block diagram uses the LabVIEW multitasking capabilities to run two loops simultaneously. The top loop continuously waits for a connection and then adds the connection to a synchronized queue. The bottom loop checks each of the open connections and executes any commands that have been received. If an error occurs on one of the connections, the connection is disconnected. When the user aborts the server, all open connections close.
LabVIEW Intermediate II Course Manual
5-4
ni.com
Lesson 5
Serving Data to a Client Using TCP/IP
Server Model Communication Steps The server model is more complex to allow for multiple clients to access the server. The server must first initialize itself, and then wait for a connection from a client. Once the connection is established, the server will wait for a command. The server will process and execute any commands and return results back to the client. Once the client is finished sending commands to the server, the connection between the server and client can be closed. Initialize the Server The server is initialized by listening for a connection on a particular network port. Wait for a Connection The server model allows for multiple clients to connect to the server. This is accomplished by waiting for a connection from a client, and then placing the connection information into a queue using a producer/consumer design pattern. The consumer waits for a command to be received from the client. Wait for a Command Waiting for a command allows multiple commands to be received from multiple clients. This is accomplished by using a consumer to iterate through each of the clients to determine if a message has been sent by a client. Execute the Command and Return Results After a command is received by the server from a client, the server executes the command by performing work. Once the work is finished, the server responds with the results of the work or an error if it was not possible to perform the work. Close the Connection After all of the clients have finished sending messages to the server, the connection to the network port must be closed.
Client/Server Model Capabilities and Issues The client/server model provides a reliable mechanism for sending data on network reliably. But, with the added reliability, the client/server model adds complexity over the broadcast model. This complexity is due to the extra amount of communication between the client and the server to verify that messages are being received. This extra amount of communication causes the client/server model to be slower.
© National Instruments Corporation
5-5
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
Exercise 5-1
Concept: Simple Data Client VI and Simple Data Server VI
Goal In this exercise, you will open and examine two of the TCP/IP example VIs that show how LabVIEW can be used as both a TCP client and a TCP server.
Scenario Transferring data over TCP/IP is easy with LabVIEW. It is necessary to define the method that the data is transferred. The TCP VIs in LabVIEW only send string data. So, all data types in LabVIEW need to be converted to a string before they are passed to TCP. Also, it is necessary to send the size of the data packet with the packet. In this exercise, notice how the data is passed from the server to the client. In particular, notice how the size of the data packet is determined and then sent to the server, before the data packet.
Implementation TCP Client 1. Open the NI Example Finder by clicking Help»Find Examples. 2. Select the Search tab and enter simple data client in the Enter keyword(s) text box. 3. Double-click Simple Data Client.vi in the search results. Do not close NI Example Finder.
Figure 5-5. Simple Data Client VI Front Panel
4. Open and examine the block diagram.
LabVIEW Intermediate II Course Manual
5-6
ni.com
Lesson 5
Serving Data to a Client Using TCP/IP
Figure 5-6. Simple Data Client VI Block Diagram
The TCP Open Connection function specifies which address and port you should use to open the connection. The TCP Read function is configured to read four bytes of information. These four bytes are the size of the data and are type cast to a 32-bit signed integer (I32) and used for the bytes to read input on the second TCP Read function. The resulting data is type cast to an array of doubleprecision, floating-point scalar numbers (DBL) and displayed in a chart. The TCP Read functions are continuously called in a loop until you click the STOP button or an error occurs. The Error to Warning VI converts non-critical connection errors to warnings. The TCP Close Connection function is wired to stop the connection when you click the STOP button or an error occurs, and errors are reported by the Simple Error Handler VI.
TCP Server 1. Return to NI Example Finder and double-click Simple Data Server.vi in the search results.
Figure 5-7. Simple Data Server VI Front Panel
2. Open and examine the block diagram.
© National Instruments Corporation
5-7
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
Figure 5-8. Simple Data Server VI Block Diagram
The TCP Listen VI waits for a connection on the specified port for five seconds. The default timeout ms of –1 causes the VI to wait indefinitely. The TCP Listen VI contains a TCP Create Listener function and a function to determine if a listener has already been created. After a connection is made, either a random or sine waveform is generated, based on the value of the Function control, and type cast to a string. The length of that string is then type cast to a string and sent to the client with the TCP Write function. The first TCP Write function sets the amount of data to send. A second TCP Write function then sends the waveform string. If a connection error occurs, error checking in the loop stops the loop. The Error to Warning VI converts non-critical connection errors to warnings. 3. If the computer is connected through TCP/IP to another computer that has LabVIEW, and each computer has a unique IP address, you can run the Simple Data Client VI on one computer and the Simple Data Server VI on the other computer. ❑ Find a partner and exchange IP addresses. Decide which computer is the server. Run the Simple Data Server VI on that computer. ❑ Run the Simple Data Client VI with the IP address or hostname of the server on the other computer. You should see the random or sine waveform on the chart in the client VI as you change the Function control on the server VI. ❑ To end the connection, click the STOP button on the client VI. Stop the server VI by clicking the Abort button on the toolbar because there is no other way to end its execution. You can run the client and server VIs on the same computer if the computer is not networked.
Note
LabVIEW Intermediate II Course Manual
5-8
ni.com
Lesson 5
Serving Data to a Client Using TCP/IP
4. Close the Simple Data Client VI and Simple Data Server VIs. Do not save changes.
End of Exercise 5-1
© National Instruments Corporation
5-9
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
B. Implementing the Client/Server Model Use the TCP/IP VI and functions located on the TCP palette to implement the client/server model using LabVIEW as a client or server application.
TCP/IP VI and Functions The TCP/IP VIs are organized similar to other LabVIEW functions, where you must first open, then read/write, and close. The LabVIEW TCP/IP VIs have other functionality that is specific to the maintenance of a TCP/IP network connection such as the TCP Listen VI, and the IP to String, and String to IP functions.
TCP Open Connection Function (Client) Use the TCP Open Connection function to actively establish a connection with a specific address and port. If the connection is successful, the function returns a network connection refnum that uniquely identifies that connection. Use this connection refnum to refer to the connection in subsequent VI calls. If the connection is not established in the specified timeout period, the function completes and returns an error. connection ID is a network connection refnum that uniquely identifies the TCP connection. error in and error out clusters describe any error conditions. The address identifies a computer on the network and can be expressed in IP dot notation or as the hostname. The port is an additional number that identifies a communication channel on the computer that the server uses to listen for communication requests. When you create a TCP server, you specify the port that you want the server to use for communication. If the connection is successful, the TCP Open Connection function returns a connection ID that uniquely identifies that connection. You use this connection ID to refer to the connection in subsequent VI calls.
TCP Read Function (Client and Server) The TCP Read function reads a number of bytes from a TCP network connection, returning the results in data out. mode indicates the behavior of the read operation based on the following four options. •
Standard (default)—Waits until all bytes requested have arrived or until the time specified in timeout ms runs out. Returns the number of bytes that have been received so far. If fewer bytes than the requested number arrive, returns the partial number of bytes and reports a timeout error.
•
Buffered—Waits until all bytes requested have arrived or until the time runs out. If fewer bytes than the requested number of bytes arrive, returns no bytes and reports a timeout error.
LabVIEW Intermediate II Course Manual
5-10
ni.com
Lesson 5
Serving Data to a Client Using TCP/IP
•
CRLF—Waits until receiving a CR (carriage return) followed by a LF (line feed) within the number of bytes requested or until the time runs out. Returns the bytes received up to and including the CR and LF. If a CR and LF are not found, returns no bytes and reports a timeout error.
•
Immediate—Waits until receiving any bytes. Waits the full timeout only if no bytes have been received. Returns the number of bytes received so far. Reports a timeout error if no bytes are received.
TCP Write Function (Client and Server) The TCP Write function writes data to a TCP network connection. All the data written or read is in a string data type. The TCP/IP protocol does not state the type or format of the data transferred, so a string type is the most flexible method. You can use the Type Cast and Flatten to String functions to send binary or complicated data types. If you send binary or complicated data types, you must inform the receiver of the exact type and representation of the data sent to reconstruct the original information. Also, when you use the TCP Read function, you must specify the number of bytes to read. A common method is to send a 32-bit integer first to specify the length of the data string that follows. The TCP example VIs provided with LabVIEW and the exercises in this lesson provide more information about these topics and about how the data typically is formatted for TCP/IP communications.
TCP Close Connection Function (Client and Server) Use the TCP Close Connection function to close the connection to the remote application. If unread data remains and the connection closes, you might lose data. Use a higher level protocol for your computer to determine when to close the connection. After a connection is closed, you cannot read from it or write to it again.
TCP Listen VI, TCP Create Listener Function and TCP Wait on Listener Function(Server) A communication program needs the ability to wait for an incoming connection. The procedure is to create a listener and wait for an accepted TCP connection at a specified port. If the connection is successful, the function returns a connection ID and the address and port of the remote TCP. Refer to the Data Server VI located in examples\comm\TCP.llb for an example of this architecture. You can use the following techniques to wait for an incoming connection: •
© National Instruments Corporation
Use the TCP Listen VI to create a listener and wait for an accepted TCP connection at a specified port. If the connection is successful, the VI
5-11
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
returns a connection refnum, the address, and the port of the remote TCP client. •
Use the TCP Create Listener function to create a listener and use the TCP Wait on Listener function to listen for and accept new connections. The TCP Wait on Listener function returns the same listener ID you wired to the function and the connection refnum for a connection. When you finish waiting for new connections, use the TCP Close Connection function to close a listener. You cannot read from or write to a listener.
The advantage of using the second technique is that you can use the TCP Close Connection function to cancel a listen operation, which is useful when you want to listen for a connection without using a timeout, but you want to cancel the listen when another condition becomes true. You can close the listen VI at any time. When you establish a connection, use the TCP Read function and the TCP Write function to read and write data to the remote application.
String to IP The String to IP function converts a string to an IP network address or an array of IP network addresses. If String to IP is in single output mode, the net address is the first result returned by the operating system resolver. If String to IP is in multiple output mode, the result is an array of all IP network addresses returned by the operating system resolver. If the node fails to convert the string, the result is a value of zero in single output mode or an empty array in multiple output mode.
IP to String The IP to String function converts an IP network address to a string.
LabVIEW Intermediate II Course Manual
5-12
ni.com
Lesson 5
Exercise 5-2
Serving Data to a Client Using TCP/IP
TCP File Transfer
Goal Create a file transfer program using TCP.
Scenario You typically use TCP communication in situations where you need to reliably transfer data, with no loss of data. An example of this situation is file transfer. When you transfer files, reliability is very important, because losing any part of the file corrupts most binary files, rendering them unusable. Write an application which uses TCP to transfer a file from one computer to another. The application should accept any file type or size and should perform error checking to ensure that the file transfers correctly.
Design In order to create a file transfer program that can handle large files and check for errors, you need to use some common data transfer and storage techniques. Use chunking to transfer the files one piece at a time and checksums to identify transmission errors.
Chunking In order to transfer large files, it is inefficient, and potentially impossible, to store the entire file in memory at once. Therefore, you typically use a technique known as chunking to process large files. When using chunking, instead of reading and transferring the entire file at once, you read a portion of the file, transmit that portion, and then repeat the process with the next portion. The size of each portion, or chunk, is known as the chunk size. In order to use chunking, the sender must transmit information about the chunk size and number of chunks to the receiver. The number of chunks can be transmitted as a header before the chunks are transmitted, or a special termination code can be sent after the last chunk. The size of each chunk can be transmitted at the beginning of the chunk, or each chunk can have a fixed size. Using a fixed size for each chunk requires the sender to pad the final chunk with excess data to enlarge it to the required size. For the file transfer program, transmit the number of chunks at the beginning of the program and then transmit the size of each chunk immediately before the chunk itself.
© National Instruments Corporation
5-13
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
Checksums A simple technique for detecting transmission errors is a checksum. In order to perform a checksum, the sender should convert each byte of data to an integer, and then arithmetically add all of the integers which represent the data together to calculate the checksum. You can then transmit the checksum to the receiver, which can perform the same calculations on its received data and compare the calculated checksum to the transmitted one. If the checksums are not equal, then one or more bytes has been lost or altered in transition. The file transfer program should calculate a checksum for each chunk of data and then append the checksum to the end of each chunk.
Client/Server Architecture Since a TCP client-server connection is bi-directional it does not matter whether the file sender or the file receiver is the server. For this program the file sender acts as the client and the file receiver acts as the server. This configuration is similar to executing a "put" command on a traditional FTP application. Client
Server
TCP File Sender
TCP File Receiver
File Read
File Write
TCP
Original File
New File
Figure 5-9. Client/Server Architecture
LabVIEW Intermediate II Course Manual
5-14
ni.com
Lesson 5
Serving Data to a Client Using TCP/IP
TCP File Sender Inputs and Outputs Table 5-1. TCP File Sender Inputs and Outputs
Type
Name
Properties
Default Value
Path Control
File Path
Existing only browse option, Browse Button Visible
Empty
String Control
Address
—
localhost
Numeric Control
Port
Unsigned 16-bit Integer
5280
Numeric Control
Chunk Size
Signed 32-bit Integer
1000
TCP File Sender Program Flow The TCP File Sender is the client for this application. The TCP File Sender should perform the following tasks: 1. Open a connection to the TCP File Receiver and a reference to the file. 2. Calculate the number of chunks needed to transfer the data based upon the chunk size and the file size. 3. Transfer the number of chunks to the TCP File Reciever. 4. Transfer each chunk to the TCP File Receiver, using the following steps: a. Calculate the size of the chunk. b. Send the size of the chunk to the TCP File Reciever. c. Calculate the checksum of the chunk. d. Append the checksum to the tail of the chunk. e. Send the chunk to the TCP File Reciever. 5. Close the TCP connection and the file reference.
TCP File Receiver Inputs and Outputs Table 5-2. TCP File Receiver Inputs and Outputs
Type
Name
Properties
Default Value
Path Control
File Path
New or Existing browse option, Browse Button Visible
Empty
Numeric Control
Port
Unsigned 16-bit Integer
5280
TCP File Receiver Program Flow The TCP File Receiver acts as the server for this application. The TCP File Receiver should perform the following tasks: © National Instruments Corporation
5-15
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
1. Open a reference to a new file and create a TCP listener for the TCP File Sender to connect to. 2. Read the number of chunks from the TCP File Sender. 3. Receive each chunk, using the following steps: a. Read the size of the chunk from the TCP File Sender. b. Read the chunk data. c. Split the chunk into data and a checksum. d. Calculate the checksum of the received data and compare it to the received checksum. e. Write the chunk data to the file. 4. Close the listener and file reference.
Implementation Part A: TCP File Sender 1. Build the VI front panel.
Figure 5-10. TCP File Sender Front Panel
❑ Open a blank VI and save the VI as TCP File Sender.vi in the C:\Exercises\LabVIEW Intermediate II\TCP File Transfer directory.
❑ Create the File Path control as described in Table 5-1. ❑ Create the Address control as described in Table 5-1. ❑ Create the Port control as described in Table 5-1. ❑ Create the Chunk Size control as described in Table 5-1. ❑ Arrange the controls as shown in Figure 5-10. 2. Open the TCP connection and file reference. ❑ Open the block diagram.
LabVIEW Intermediate II Course Manual
5-16
ni.com
Lesson 5
Serving Data to a Client Using TCP/IP
❑ Place an Open/Create/Replace File function on the block diagram. ❑ Right-click the operation input of the Open/Create/Replace File function and select Create»Constant from the shortcut menu. Set the value of the constant to open. ❑ Right-click the access input of the Open/Create/Replace File function and select Create»Constant from the shortcut menu. Set the value of the constant to read-only. ❑ Place a TCP Open Connection function on the block diagram. ❑ Wire the front panel controls to the open VIs as shown in Figure 5-11. 3. Calculate number of chunks. ❑ Place a Get File Size function on the block diagram. ❑ Place a Divide function on the block diagram. ❑ Place a Round To +Infinity function on the block diagram. ❑ Place a To Long Integer function on the block diagram ❑ Complete the wiring to calculate the number of chunks as shown in Figure 5-11. 4. Send the number of chunks through TCP.
Figure 5-11. Send Number of Chunks
❑ Place a TCP Write function on the block diagram. ❑ Place a Flatten To String function on the block diagram. © National Instruments Corporation
5-17
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
❑ Wire the diagram as shown in Figure 5-11. 5. Send the data chunks.
Figure 5-12. Send Data Chunks
❑ Place a For Loop on the block diagram as shown in Figure 5-12. ❑ Place a Read From Binary File function inside the For Loop. ❑ Wire the Chunk Size terminal to the count terminal of the Read From Binary File function. ❑ Place a Clear Specific Error VI, located in the C:\Exercises\ LabVIEW Intermediate II\TCP File Transfer directory in the For Loop. ❑ Place a Create Chunk VI located in the C:\Exercises\LabVIEW Intermediate II\TCP File Transfer directory in the For Loop. ❑ Open the Create Chunk VI and observe the block diagram. This VI takes the raw binary data, calculates the checksum, appends the checksum to the data to create a chunk, calculates the chunk size, and returns both the chunk and the chunk size as strings so they can be transmitted via TCP. ❑ Place two TCP Write functions inside the For Loop. ❑ Wire a Numeric Constant with a U8 representation to the data type input of the Read Binary function.
LabVIEW Intermediate II Course Manual
5-18
ni.com
Lesson 5
Serving Data to a Client Using TCP/IP
❑ Right-click the code input of the Clear Specific Error VI and select Create»Constant from the shortcut menu. Set the value of the constant to 4. The Read Binary function returns an End of File error during the final iteration of the loop because the last chunk usually is not full. The Read Binary function returns all of the data up to the end of the file, and the size of each chunk is transmitted through TCP, so this error is not a problem. The Clear Specific Error VI ignores the End of File error. The error code for an End of File error is 4. Note
❑ Wire the contents of the For Loop as shown in Figure 5-12. Use shift registers for the error and refnum wires. 6. Close references and handle errors.
Figure 5-13. TCP File Sender Block Diagram
❑ Place a Close File function to the right of the For Loop. ❑ Place a TCP Close Connection function to the right of the For Loop. ❑ Place a Simple Error Handler VI to the right of the For Loop. ❑ Finish wiring the diagram as shown in Figure 5-13. 7. Save the VI.
Part B: TCP File Receiver 1. Build the VI front panel
Figure 5-14. TCP File Receiver Front Panel
© National Instruments Corporation
5-19
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
❑ Open a blank VI and save the VI as TCP File Receiver.vi in the C:\Exercises\LabVIEW Intermediate II\ TCP File Transfer directory. ❑ Create the File Path control as described in Table 5-2. ❑ Create the Port control as described in Table 5-2. ❑ Arrange the controls as shown in Figure 5-14. 2. Open the TCP listener and create the file. ❑ Open the block diagram. ❑ Place an Open/Create/Replace File function on the block diagram. ❑ Right-click the operation input of the Open/Create/Replace File function and select Create»Constant from the shortcut menu. Set the value of the constant to replace or create. ❑ Right-click the access input of the Open/Create/Replace File function and select Create»Constant from the shortcut menu. Set the value of the constant to write-only. ❑ Place a TCP Listen VI on the block diagram. ❑ Wire the open functions as shown in Figure 5-15. 3. Read the number of chunks from the TCP File Sender.
Figure 5-15. Read Number of Chunks
❑ Place a TCP Read function on the block diagram.
LabVIEW Intermediate II Course Manual
5-20
ni.com
Lesson 5
Serving Data to a Client Using TCP/IP
❑ Right-click the bytes to read input of the TCP Read function and select Create»Constant from the shortcut menu. Set the value of the constant to 4. ❑ Place an Unflatten From String function on the block diagram. ❑ Wire a Numeric Constant with a I32 representation to the type input of the Unflatten From String function. Note The TCP File Sender flattened the I32 value which represents the number of chunks to a string and then transferred it. An I32 value requires 4 bytes to store, so the TCP File Receiver reads a 4-byte string and then unflattens it back to an integer. You will repeat this process to get the size of each data chunk.
❑ Wire the diagram as shown in Figure 5-15. 4. Read the data chunks from the TCP File Sender.
Figure 5-16. Read Data Chunks
❑ Place a For Loop on the block diagram as shown in Figure 5-16. ❑ Place two TCP Read functions in the For Loop. ❑ Right-click the bytes to read input of the first TCP Read function and select Create»Constant from the shortcut menu. Set the value of the constant to 4. ❑ Place an Unflatten From String function in the For Loop. ❑ Wire a numeric constant with a I32 representation to the type input of the Unflatten From String function.
© National Instruments Corporation
5-21
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
❑ Place a Decode Chunk VI, from the C:\Exercises\LabVIEW Intermediate II\TCP File Transfer directory in the For Loop. ❑ Open the Decode Chunk VI and observe the block diagram. This VI takes transmitted string data, splits it into a checksum and binary data, calculates the checksum of the binary data, compares the transmitted checksum to the calculated one, generates an error if necessary and returns the binary data so that it can be written to file. ❑ Place a Write to Binary File function in the For Loop. ❑ Right-click the prepend array or string size? input of the Write to Binary File function and select Create»Constant from the shortcut menu. Set the value of the constant to False. ❑ Wire the contents of the For Loop as shown in Figure 5-16. Use shift registers for the error and refnum wires. 5. Close references and handle errors.
Figure 5-17. TCP File Receiver Block Diagram
❑ Place a Close File function to the right of the For Loop. ❑ Place a TCP Close Connection function to the right of the For Loop. ❑ Place a Simple Error Handler VI to the right of the For Loop. ❑ Finish wiring the diagram as shown in Figure 5-13. 6. Save the VI.
LabVIEW Intermediate II Course Manual
5-22
ni.com
Lesson 5
Serving Data to a Client Using TCP/IP
Testing 1. Transfer a file on the same machine. ❑ Ensure that the default values on both VIs match Table 5-1 and Table 5-2. ❑ Enter C:\Exercises\LabVIEW Intermediate II\ TCP File Transfer\Image Copy.jpg in the Path control of the TCP File Receiver VI. ❑ Run the TCP File Receiver VI. ❑ Enter C:\Exercises\LabVIEW Intermediate II\ TCP File Transfer\Image.jpg in the Path control of the TCP File Sender VI. ❑ Run the TCP File Sender VI. ❑ Browse to C:\Exercises\LabVIEW Intermediate II\ TCP File Transfer\Image Copy.jpg using Windows Explorer and open the image. 2. Transfer files to another machine. (optional) ❑ Copy the TCP File Receiver and TCP File SenderVIs to another machine, or interact with your neighbor’s VIs. ❑ Transfer a file from your development machine to the remote machine. ❑ Transfer a file from the remote machine to your development machine. 3. Transfer other file types. (optional) ❑ Transfer a VI using the TCP File Receiver and TCP File Sender. ❑ Transfer a text file using the TCP File Receiver and TCP File Sender. ❑ Experiment by transferring other file types.
End of Exercise 5-2
© National Instruments Corporation
5-23
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
Summary •
The client/server model is commonly used for networked communication.
•
A client application initiates the connection and instructs the server to read and/or write data.
•
A server application waits for a connection and then reads or writes data as instructed by the client.
LabVIEW Intermediate II Course Manual
5-24
ni.com
Lesson 5
Serving Data to a Client Using TCP/IP
Notes
© National Instruments Corporation
5-25
LabVIEW Intermediate II Course Manual
Lesson 5
Serving Data to a Client Using TCP/IP
Notes
LabVIEW Intermediate II Course Manual
5-26
ni.com
6
Publishing Data to a Subscriber
This lesson describes using shared variables in LabVIEW to implement the publisher/subscriber communication model.
Topics A. Publisher/Subscriber Communication Model Overview B. Implementing the Publisher/Subscriber Communication Model
© National Instruments Corporation
6-1
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
A. Publisher/Subscriber Communication Model Overview Shared variables are configured software items that can send data between VIs. Use shared variables to share data among VIs or between locations in an application that cannot be connected with wires. A shared variable can represent a value or an I/O point. You can change the properties of a shared variable without having to edit the block diagram of the VIs that use the shared variable. You can share data using shared variables with little or no block diagram programming. Configuration options for shared variables, such as buffering and single-writer restriction, are available through the Shared Variable Properties dialog box. The Variable Type pull-down list configures whether the shared variable can share data on the local computer or across a network. Select Network-Published from the Variable Type list to create shared variables that you want to read and write on remote computers and targets on the same network. Select Single-Process from the Variable Type list to create shared variables that you want to read and write on a single computer. Configuration options vary depending on the Variable Type you select. LabVIEW modules and toolkits you have installed might provide additional shared variable types, configuration options, and limitations. Refer to the documentation for the LabVIEW module or toolkit for more information about the shared variable types, configuration options, and limitations that product adds to shared variables. Note If you are using a network-published Shared Variable node that is configured to read data, you must run each Shared Variable node before the node subscribes and starts receiving buffered values. If a buffer for a network-published shared variable overflows, the data is lost, and LabVIEW does not return an error.
Shared variables must exist within a project library. LabVIEW stores shared variable configuration data in the .lvlib file for the project library that contains the shared variable. Network-published shared variables communicate between VIs, remote computers, and hardware through the Shared Variable Engine. The Shared Variable Engine uses the NI Publish-Subscribe Protocol (NI-PSP) data transfer protocol to write and allow users to read live data. LabVIEW identifies network-published shared variables through a network path that includes the computer name, project library name(s), and shared variable name.
LabVIEW Intermediate II Course Manual
6-2
ni.com
Lesson 6
Publishing Data to a Subscriber
Publisher/Subscriber Communication Model You can configure a shared variable to have a data source. Possible data sources for shared variables include DAQ channels, data items, NI-PSP data items, such as other shared variables, and data items from I/O servers that are defined outside of the active project. For example, you might choose to define a FieldPoint data item as the data source of a shared variable. The FieldPoint process monitors the values that the hardware acquires. When the FieldPoint process sends new data to the Shared Variable Engine, the Shared Variable Engine updates the shared variable value. Configure a shared variable to have a data source by placing a checkmark in the Bind to Source checkbox on the Variable page of the Shared Variable Properties dialog box. When you configure a shared variable to have an existing data source across a network, LabVIEW does not track configuration changes to the data source. Therefore, changes to the data source could break the connected shared variable. For example, suppose you create a shared variable named VarSource in one project, and in a separate project, you create a second shared variable, VarDest. You now want to make the VarSource shared variable the data source for the VarDest shared variable. Because the data source you want to use is outside of the active project, you must browse the network to select the data source. After you create and configure the VarDest shared variable, LabVIEW retains the URL and configuration. Now, any configuration changes you make to the VarSource shared variable are unknown to the VarDest shared variable. If you change the variable name for VarSource, the URL in the destination project is broken, and you need to update the configuration of VarDest with the new name of VarSource.
Creating Shared Variables You must have a project open to create a shared variable. To add a shared variable to a project, right-click a target, a project library, or a folder within a project library in the Project Explorer window and select New»Variable from the shortcut menu to display the Shared Variable Properties dialog box. Select among the shared variable configuration options and click the OK button. Shared variables must be inside project libraries. If you create a shared variable from a target or folder that is not inside a project library, LabVIEW creates a new project library and places the shared variable inside. LabVIEW modules and toolkits you have installed might not support shared variables. Note
© National Instruments Corporation
6-3
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
Each shared variable on a target has a location that NI-PSP uses to identify the shared variable. Right-click the project library for the shared variable and select Deploy from the shortcut menu to deploy the library. You must deploy the owning library to connect to the shared variable from front panel objects, Shared Variable nodes on the block diagram, and other shared variables. You also can right-click a project library and select Deploy All to deploy all project libraries for shared variables on that target. LabVIEW automatically deploys the project libraries for shared variables that you read or write in a VI if the projects containing those variables are open. Note
Configuring Shared Variables You can change the shared variable configuration by right-clicking the shared variable in the Project Explorer window and selecting Properties from the shortcut menu to display the Variable page of the Shared Variable Properties dialog box. After you change the configuration for a shared variable, right-click the project library in which the shared variable resides under the target and select Deploy from the shortcut menu to update the properties of the shared variable on the target.
Network Technologies of the Publisher/Subscriber Communication Model Network-published shared variables communicate between VIs, remote computers, and hardware through the Shared Variable Engine. The Shared Variable Engine uses the NI Publish-Subscribe Protocol (NI-PSP) data transfer protocol to write and allow users to read live data. NI-PSP is a proprietary technology that provides fast and reliable data transmission for large and small applications and is installed as a service on the computer when you install LabVIEW. The NI-PSP networking protocol uses psp URLs to transmit data across the network. You can browse to any NI-PSP data item on the network to seamlessly bind shared variables to other shared variables or to server and device data items. An NI-PSP data item can be a shared variable in a project other than an active project or a data item on a connected server or device, such as an OPC server or FieldPoint module. You can use the Shared Variable Engine to deploy data only from Windows NT/ 2000/XP and RT targets. However, you can use the NI-PSP protocol to read and write data on all LabVIEW-supported platforms. Note
To read and write shared variable values from an unsupported platform, create and deploy a shared variable on the target that has LabVIEW and the Shared Variable Engine, such as My Computer. Then add Shared Variable
LabVIEW Intermediate II Course Manual
6-4
ni.com
Lesson 6
Publishing Data to a Subscriber
nodes from the target hosting the Shared Variable Engine to the block diagram of a VI, and deploy the VI to the target that does not support the Shared Variable Engine.
Network Paths Shared variables outside of the active project appear as data items when you browse NI-PSP data items on the network. The network path to shared variables in other projects consists of the computer name, the name of the project library in which the shared variable resides, and the shared variable name: \\computer\library\variable. For example, the network path \\computer1\mylib\myvariable identifies a shared variable named myvariable in the mylib project library on a computer named computer1. If the shared variable exists in a sub-project library named mysublib, the shared variable path includes the sub-project library, such as \\computer1\mylib\mysublib\myvariable. The network path to a psp data item consists of the computer name, the name of the process in which the data item resides, and the data item name: \\computer\process\data_item.
Shared Variable Deployment You must deploy a shared variable for the variable to be available to other projects and remote computers. LabVIEW deploys shared variables when the Shared Variable Engine is running. You can deploy a shared variable by running the VI in which the shared variable resides. You also can right-click the owning project library of the shared variable and select Deploy from the shortcut menu. To disable a shared variable so it does not deploy when you run the VI in which it resides, right-click the owning project library and remove the checkmark next to the Autodeploy Variables shortcut menu item. When you run a VI containing a shared variable, the Shared Variable Engine deploys all shared variables in the owning project library for the variable in the VI, even if the shared variables are not all in currently running VIs. During deployment, LabVIEW reports any conflicts in the Shared Variable Engine, such as when you deploy shared variables that are not in the active project to the Shared Variable Engine. Stopping the VI that contains a shared variable does not undeploy the shared variable. To undeploy a shared variable, right-click the owning project library for the shared variable and select Undeploy from the shortcut menu.
© National Instruments Corporation
6-5
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
Publisher/Subscriber Capabilities and Performance Issues Keep in mind the following capabilities and performance issues when you use the publisher/subscriber communication model.
Using Shared Variables in VIs After you create a shared variable, you can access the shared variable data in LabVIEW in several ways, regardless of the configuration: •
Front panel data binding—Bind front panel objects. You can bind front panel objects only to network-published shared variables.
•
Shared Variable node—Read and write shared variable data on the block diagram with little to no programming.
•
DataSocket functions—Read and write shared variable data on the block diagram with more options for customization.
•
VI Server interface—Use Variable properties and methods and Control properties and methods to configure shared variables or control shared variable lifetimes. You also can use the Library methods to programmatically create libraries and shared variables in applications where you need to create complicated or large numbers of connections dynamically.
Shared Variables and Stand-Alone Applications If you plan to distribute a stand-alone application that uses shared variables, do not include the .lvlib file in an LLB or in the executable. Use the Source Files Setting page of the Application Properties dialog box to change the Destination of the .lvlib file to a destination outside the executable or LLB. You can deploy the shared variables in two ways: •
Write the application so that it programmatically deploys shared variables at start time. Call the Deploy Library Method in the top-level VI of the application. In the Library Path input of the method, use the relative path to the .lvlib file that contains the shared variable.
•
Manually deploy the shared variables to the computer or target Shared Variable Engine before running the built application.
If you plan to distribute a shared library (DLL) that uses shared variables, do not include the .lvlib file in the DLL. Use the Source Files Setting page of the Shared Library Properties dialog box to change the Destination of the .lvlib file to a destination outside the DLL.
Buffering Data If you use shared variables or a psp or dstp URL to share data programmatically, LabVIEW by default writes only the most recent value to all readers. When one client writes values to the server faster than another client reads them, newer values overwrite older, unprocessed values before LabVIEW Intermediate II Course Manual
6-6
ni.com
Lesson 6
Publishing Data to a Subscriber
the clients read them. If the reader does not receive a value before receiving the following value, the data is lost. This loss of unprocessed data can occur at the server or at the client. This loss of data might not be a problem if you are reading data and you want to receive only the most recent value written to the server. However, if you want to receive every value written to the server or if lossy transfers are unacceptable, you must buffer the data on the client. Client-Side Buffering Buffering allows you to lessen the potential timing difference between the reader and writer but does not guarantee data delivery. If the data in a buffer at the server or client exceeds the buffer size, the buffer discards older values in place of newer values. You can set the size of a buffer for a shared variable on the Variable page of the Shared Variable Properties dialog box to set how many data packets the shared variable retains before overwriting old data. You also can specify programmatically the maximum number of bytes and the maximum number of values, in terms of packets, that the buffer for each item can hold. National Instruments recommends that you specify both the Buffer Maximum Bytes and Buffer Maximum Packets properties when you buffer data. If incoming data exceeds the maximum number of bytes or the maximum number of values, LabVIEW removes older data from the buffer to accommodate the new data. When configuring buffering programmatically, wire the written data to the Set Variant Attribute function to detect discarded values in a data stream by uniquely identifying each value in the writer and checking for discarded sequence IDs in the reader. If you want the buffer-enabled client to receive all data, use the DataSocket Write function to write live data programmatically. Writing data from the front panel can result in data loss. Client-side buffering also applies to other protocols, such as opc and file. However, in some cases these servers might lose data. Note
Set the mode input of the DataSocket Open function to BufferedRead or BufferedReadWrite and use a Property Node to set the DataSocket properties for the size of a first-in-first-out (FIFO) buffer. Doing so ensures that LabVIEW stores the values the client receives in a buffer rather than overwriting them every time the value changes. If you use DataSocket properties to set the size of a FIFO buffer, you must set the mode input of the DataSocket Open function to BufferedRead or BufferedReadWrite. Otherwise, the item at the server is not buffered for the connection. Note
© National Instruments Corporation
6-7
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
The following block diagram uses buffering programmatically.
You also can enable buffering when sharing data using the DataSocket functions by adding the string ?maxbytes=1000&maxpackets=10, to the end of the URL, where 1000 is the maximum number of bytes the buffer contains and 10 is the maximum number of packets the buffer contains. Buffering applies when you use the DataSocket Read function to read data a server writes. Buffering is not available when you use front panel DataSocket data binding to read data. Buffering is available for front panel data binding through the Shared Variable Engine if you bind controls to shared variables with buffering enabled on the Variable page of the Shared Variable Properties dialog box. Note
Reporting Diagnostics
Use the Buffer Utilization (Bytes) property or the Buffer Utilization (Packets) property to request diagnostic information about the buffers you specify. Use these properties to check the percentage of buffer in use on the client to determine whether the current buffer size is sufficient. If the value of either of these properties approaches the maximum value of the buffer, increase the buffer size to make sure you receive all values the server writes. You also can increase the rate at which the While Loop containing the DataSocket functions executes to increase the read rate. Server-Side Buffering When you configure client-side buffering, servers might lose data in some cases if the server sends data faster than the network can accept. Server-side buffering for NI-PSP is available only if you are connecting to an existing shared variable with buffering enabled on the Variable page of the Shared Variable Properties dialog box. To use dstp buffering, you also must use the DataSocket Server Manager to configure server-side buffering. Refer to the DataSocket Server Help for more information about server-side
LabVIEW Intermediate II Course Manual
6-8
ni.com
Lesson 6
Publishing Data to a Subscriber
buffering for the DataSocket Server. For other protocols, refer to the server documentation for more information about server-side buffering for that server.
B. Implementing the Publisher/Subscriber Communication Model You can implement the publisher/subscriber communication model on the front panel or the block diagram.
Creating a Publisher/Subscriber on the Front Panel Use front panel data binding to read or write live data in a front panel object. Note
You can bind front panel objects only to network-published shared variables. Drag a shared variable from the Project Explorer window to the front panel of a VI to create a control bound to the shared variable. You also can use the options on the Data Binding page of the control Properties dialog box to bind the control to a shared variable or to an NI Publish-Subscribe Protocol (NI-PSP) data item on the network.
Note If you are using a network-published Shared Variable node that is configured to read data, you must run each Shared Variable node before the node subscribes and starts receiving buffered values. If a buffer for a network-published shared variable overflows, the data is lost, and LabVIEW does not return an error.
When you enable data binding for a control, changing the value of the control changes the value of the shared variable to which the control is bound. Front panel data binding is primarily intended for sharing live data. To read data in local files, ftp servers, or Web servers, use the DataSocket Read function, the File I/O VIs and functions, or the Application Control VIs and functions. You can set the value of a front panel control directly on the front panel and then write the data, or you can build a block diagram, wire the output of a VI or function to an indicator, and write the data from that indicator. Typical scenarios for using front panel data binding with shared variables or NI-PSP data items include the following: •
© National Instruments Corporation
Manipulate a front panel control and write the data for other users to read through a control or indicator. For example, if you place a knob on your front panel that raises or lowers temperature, a user on another
6-9
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
computer can view the data in an indicator or read the data and use it in a control wired to a subVI or function. •
Write a value that appears in a front panel indicator so another user can read and view the data in a control or indicator on the front panel or use the results as data in a control wired to an input in a subVI or function. For example, a VI that calculates the mean temperature and displays the temperature in a thermometer on the front panel can write the temperature data.
•
Read a value that appears in a control or indicator on the front panel of another VI to view data in a front panel indicator on your VI. If you read the data with a control, you can use the data in your VI by wiring the control to an input of a subVI or function.
•
Read and write data from a front panel control so users can manipulate a control on the front panel of a VI from the front panel of another VI. When you run the first VI, the front panel control on that VI retrieves the current value that the second VI or application wrote through a shared variable. When a user changes the control value on the front panel of the first VI, the shared variable writes the new value to the front panel control of the second VI. If you then manipulate the value of that front panel control, the second VI writes the value to the front panel objects in other VIs that are bound to the shared variable.
The front panel objects that read data do not have to be the same kind of objects that write the data. However, the front panel objects must be the same data type. If the front panel objects are of the numeric type, the data types must coerce. For example, you can use a digital indicator in your VI to view the data that a thermometer in another VI generates. The thermometer can be a floating-point number, and the digital indicator can be an integer.
Front Panel Data Binding You can connect front panel objects using the dstp, opc, ftp, http, and file protocols by selecting DataSocket from the Data Binding Selection drop-down list on the Data Binding page of the control Properties dialog box. However, using front panel data binding to control a front panel control remotely through the Shared Variable Engine provides faster and more reliable data transmission as well as seamless connections to shared variables and NI-PSP data items. Select Shared Variable Engine (NI-PSP) from the Data Binding Selection drop-down list on the Data Binding page of the control Properties dialog box to bind the control through the Shared Variable Engine. Front panel data binding connections through the Shared Variable Engine use NI-PSP, the protocol that transmits shared variable data. dstp connections pass through the DataSocket Server.
LabVIEW Intermediate II Course Manual
6-10
ni.com
Lesson 6
Publishing Data to a Subscriber
Troubleshooting Front Panel Data Binding While the VI is running, if the connection to the Shared Variable Engine is successful, a small green indicator appears next to the front panel object on the VI. If the connection is not successful, a small red indicator appears. Before LabVIEW attempts to connect to the server, a small transparent indicator appears. A status message also appears if you move the cursor over the indicator. You can hide this indicator by right-clicking the front panel object and selecting Visible Items»PSP LED from the shortcut menu. You also can use the Data Binding:LED Visible property to hide the indicator programmatically. If you receive errors when attempting to read or write data from the front panel, investigate the following possible causes: •
If binding to a shared variable in another project, the shared variable must be currently deployed. To deploy the shared variable, right-click the owning project library and select Deploy from the shortcut menu. You also can right-click a project library and select Deploy All to deploy all project libraries for shared variables on that target.
•
Ensure that the device for the target on which the shared variable resides is functional and supports front panel data binding. LabVIEW modules and toolkits you have installed might not support front panel data binding.
Creating a Publisher/Subscriber on the Block Diagram A Shared Variable node is a block diagram object that points to the corresponding shared variable in the Project Explorer window. Use a Shared Variable node to read and write the value of the shared variable and to read the timestamp for the shared variable data. Drag a shared variable from the Project Explorer window onto the block diagram of a VI in the same project to create a Shared Variable node. You also can place a Shared Variable node on the block diagram from the Data Communication palette. To bind a Shared Variable node on the block diagram to a shared variable in the active project, double-click the Shared Variable node to display the Select Variable dialog box. You also can rightclick the Shared Variable node and select Select variable from the shortcut menu. Navigate to a shared variable in the Shared Variable list in the Select Variable dialog box and click the OK button. By default, the Shared Variable node is set to read. To change the Shared Variable node on the block diagram to write, right-click the Shared Variable node and select Change to write from the shortcut menu. The Shared Variable node in the following figure is set to write.
© National Instruments Corporation
6-11
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
Use the timestamp indicator to determine if the shared variable value is stale, or if it has been updated since the last read. Add a timestamp indicator to a Shared Variable node by right-clicking the Shared Variable node on the block diagram and selecting Show timestamp from the shortcut menu. If your application requires more than one recent value, configure buffering. The Shared Variable node uses the configuration you set for the shared variable in the Shared Variable Properties dialog box. When you update the shared variable configuration, LabVIEW updates the Shared Variable node. For example, if you change the Data Type of the shared variable, LabVIEW updates the Shared Variable node to the new data type in the block diagram. You also can use the DataSocket VI and functions to share shared variable data programmatically using NI-PSP.
Sharing Live Data Programmatically You can wire a Shared Variable node into VIs and functions or use the DataSocket VI and functions to programmatically configure, read, or write live data. You read or write data by specifying a URL in much the same way you specify URLs in a Web browser.
Specifying a URL URLs use communication protocols, such as psp, dstp, opc, ftp, http, and file, to transfer data. The protocol you use in a URL depends on the type of data you want to write and how you configure your network. You can use the following protocols when you read or write data using the DataSocket VI and functions: •
(Windows or RT Module) NI Publish-Subscribe Protocol (psp)—National Instruments technology for transmitting data between the network and your local computer. When you use this protocol, the VI communicates
LabVIEW Intermediate II Course Manual
6-12
ni.com
Lesson 6
Publishing Data to a Subscriber
with the Shared Variable Engine. Use the psp protocol to connect to shared variables and server or device data items. You must provide a name for the data item, which is appended to the URL. The data connection uses that name to address a particular data item in the Shared Variable Engine. You also can use this protocol when using front panel data binding. You can use the fieldpoint protocol as an alias for NIPSP. You can use the NI-PSP protocol to write data only from Windows NT/2000/XP and RT platforms. However, you can use the NI-PSP protocol to read data on all LabVIEW-supported platforms. Note
•
DataSocket Transport Protocol (dstp)—When you use this protocol, the VI communicates with the DataSocket Server. You must provide a named tag for the data, which is appended to the URL. The data connection uses the named tag to address a particular data item on a DataSocket Server. To use this protocol, you must run a DataSocket Server.
•
(Windows) OLE for Process Control (opc)—Designed specifically for
sharing real-time production data, such as data generated by industrial automation operations. To use this protocol, you must run an OPC server. •
(Windows) File Transfer Protocol (ftp)—You can use this protocol to specify a file from which to read data from an ftp server.
To read a text file from an FTP site using DataSocket functions, add [text] to the end of the URL. Note
•
file—You can use this protocol to provide a link to a local or network
file that contains data. •
http—You can use this protocol to provide a link to a Web page that
contains data. The following table shows examples of each protocol URL.
© National Instruments Corporation
6-13
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
URL psp
Example For shared variables: psp://computer/library/shared_variable \\computer\library\shared_variable
For NI-PSP data items, such as server and device data items: psp://computer/process/data_item \\computer\process\data_item fieldpoint://host/FP/module/channel dstp
dstp://servername.com/numeric, where numeric is
the named tag for the data opc
opc:\National Instruments.OPCTest\item1 opc:\\computer\National Instruments.OPCModbus\Modbus Demo Box.4:0 opc:\\computer\National Instruments.OPCModbus\Modbus Demo Box.4:0?updaterate=100&deadband=0.7
ftp
ftp://ftp.ni.com/datasocket/ping.wav ftp://ftp.ni.com/support/00README.txt[text]
file
file:ping.wav file:c:\mydata\ping.wav file:\\computer\mydata\ping.wav
http
http://ni.com
Use the psp, dstp, and opc URLs to share live data because these protocols can update remote and local controls and indicators. Use the ftp and file URLs to read data from files because these protocols cannot update remote and local controls and indicators.
LabVIEW Intermediate II Course Manual
6-14
ni.com
Lesson 6
Exercise 6-1
Publishing Data to a Subscriber
Publisher and Subscriber
Goal Use a network published shared variable to share data between computers.
Scenario Create a publisher VI that generates a sine wave. Create a subscriber VI that displays the sine wave, and allows the user to modify the time between each acquisition of the sine wave data. Use one Stop button to stop both VIs.
Design Two VIs and two pieces of shared data are necessary for this scenario: •
First shared variable: Stop Boolean
•
Second shared variable: Data Numeric
•
Publisher: generate sine, write sine to Data shared variable, read Stop shared variable to stop loop
•
Subscriber: read Data shared variable, display on chart, write Stop button to Stop shared variable
© National Instruments Corporation
6-15
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
Implementation 1. Open a blank project. 2. Save the project as Publish and Subscribe.lvproj in the C:\Exercises\LabVIEW Intermediate II\Publisher and Subscriber directory.
3. Create a shared variable for the Stop button. ❑ Switch to the Project Explorer window. ❑ Right-click My Computer and select New»Variable from the shortcut menu. ❑ Give the new variable the following properties: Name: Stop Data Type: Boolean Variable Type: Network-Published ❑ Click the OK button to close the Shared Variable Properties dialog box. Notice that a new library is created to hold the variable. 4. Save the library. ❑ Right-click the library and select Save from the shortcut menu. ❑ Save the library as Shared Data.lvlib in the C:\Exercises\ LabVIEW Intermediate II\Publisher and Subscriber
directory. 5. Create a shared variable for the Data numeric. ❑ Switch to the Project Explorer window. ❑ Right-click Shared Data.lvlib and select New»Variable from the shortcut menu. ❑ Give the new variable the following properties: Name: Data Data Type: Double Variable Type: Network-Published
LabVIEW Intermediate II Course Manual
6-16
ni.com
Lesson 6
Publishing Data to a Subscriber
❑ Click the OK button to close the Shared Variable Properties dialog box.
Generate Data VI 1. Open a blank VI. 2. Save the VI as Publisher.vi in the C:\Exercises\LabVIEW Intermediate II\Publisher and Subscriber directory. 3. Open the block diagram of the VI. 4. Build the block diagram shown in Figure 6-1.
Figure 6-1. Publisher Block Diagram Without Shared Variables
5. Save the VI. 6. Write the data generated to the Data shared variable. ❑ Switch to the Project Explorer window. ❑ Select the Data shared variable and drag it inside the While Loop of the Publisher.vi block diagram. ❑ Right-click the global variable and select Change to Write from the shortcut menu. ❑ Wire the Sine function output to the Data shared variable. 7. Read the Stop shared variable to stop the While Loop. ❑ Switch to the Project Explorer window. ❑ Select the Stop shared variable and drag it inside the While Loop of the Publisher.vi block diagram. ❑ Wire the Stop shared variable to the loop condition terminal. 8. Initialize the Stop shared variable. ❑ Switch to the Project Explorer window.
© National Instruments Corporation
6-17
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
❑ Select the Stop shared variable and drag it to the left of the While Loop of the Generate Data.vi block diagram. ❑ Right-click the Stop shared variable on the block diagram and select Change to Write from the shortcut menu. ❑ Right-click the input of the Stop shared variable and select Create»Constant from the shortcut menu. ❑ Use the Operating tool to change the constant to a False if necessary. ❑ Place a Simple Error Handler VI to the right of the While Loop. ❑ Use the shared variable error clusters to ensure order of operations. Refer to Figure 6-2 for assistance wiring this block diagram.
Figure 6-2. Publisher Block Diagram With Shared Variables
9. Select File»Save All. 10. Close the block diagram.
Read Data VI 1. Open a blank VI. 2. Save the VI as Subscriber.vi in the C:/Exercises/LabVIEW Intermediate II/Publisher and Subscriber directory. 3. Build the front panel shown in Figure 6-3.
LabVIEW Intermediate II Course Manual
6-18
ni.com
Lesson 6
Publishing Data to a Subscriber
Figure 6-3. Read Data Front Panel
4. Open the block diagram. 5. Build the block diagram shown in Figure 6-4.
Figure 6-4. Read Data Block Diagram Without Shared Variables
6. Read the data from the Data shared variable and display it on the waveform chart. ❑ Switch to the Project Explorer window. ❑ Select the Data shared variable and drag it inside the While Loop of the Subscriber VI block diagram. ❑ Wire the output of the Data global variable to the Data Chart terminal. 7. Write the value of the Stop button to the Stop shared variable. ❑ Switch to the Project Explorer window.
© National Instruments Corporation
6-19
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
❑ Select the Stop shared variable and drag it inside the While Loop of the Subscriber VI block diagram. ❑ Right-click the Stop shared variable and select Change to Write from the shortcut menu. ❑ Wire the Stop terminal to the Stop shared variable. 8. Use the shared variable error clusters to ensure order of operations. Refer to Figure 6-5 for assistance wiring this block diagram.
Figure 6-5. Read Data Block Diagram With Shared Variables
9. Save the VI. 10. Close the block diagram. 11. Save the project.
Test 1. Arrange to test your code with the person sitting next to you or copy your code to an unused nearby computer. Choose one computer as a server and the other as a client. 2. Open Publish and Subscribe.lvprj in the Project Explorer on both your server and client computer. 3. Right-click the Stop shared variable on your client computer and select Properties. 4. Place a checkmark in the Bind to Source checkbox. 5. Enter \\\Shared Data\Stop in the Path text box, where is the name or IP address of your server.
LabVIEW Intermediate II Course Manual
6-20
ni.com
Lesson 6
Publishing Data to a Subscriber
6. Click the OK button to exit the Shared Variable Properties dialog box. 7. Right-click the Data shared variable on your client computer and select Properties from the shortcut menu. 8. Place a checkmark in the Bind to Source checkbox. 9. Enter \\\Shared Data\Data in the Path text box, where is the name or IP address of your server. 10. Click OK to exit the Shared Variable Properties dialog box. 11. Run the Publisher VI on the server computer. 12. Run the Subscriber VI on the client computer. The network variable transfers the sine wave from the server to the client. 13. Modify the value of the Time Delay (ms) control. The Time Delay (ms) control determines how often to read the shared variable. What happens if you set the Time Delay to zero? When you access shared data, you may read the value more than once before it is updated to a new value, or you may miss a new value altogether. If you enable buffering on the shared variable you can avoid or reduce the chance of missing data, however you may still read a value more than once before it is updated. 14. Run the Publisher VI on the client computer. 15. Run the Subscriber VI on the server computer. Notice that the publisher/subscriber model allows transfer of data in both directions. 16. Stop and close the VIs and the project when you are finished.
End of Exercise 6-1
© National Instruments Corporation
6-21
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
Summary •
Use shared variables to share data among VIs or between locations in an application that cannot be connected with wires.
•
Network-published shared variables communicate between VIs, remote computers, and hardware through the Shared Variable Engine.
•
Use front panel data binding to read or write live data in a front panel object.
•
Use a Shared Variable node to read and write the value of the shared variable and to read the timestamp for the shared variable data.
LabVIEW Intermediate II Course Manual
6-22
ni.com
Lesson 6
Publishing Data to a Subscriber
Notes
© National Instruments Corporation
6-23
LabVIEW Intermediate II Course Manual
Lesson 6
Publishing Data to a Subscriber
Notes
LabVIEW Intermediate II Course Manual
6-24
ni.com
Additional Information and Resources
A
This appendix contains additional information about National Instruments technical support options and LabVIEW resources.
National Instruments Technical Support Options Visit the following sections of the National Instruments Web site at ni.com for technical support and professional services. •
Support—Online technical support resources at ni.com/support include the following: –
Self-Help Resources—For answers and solutions, visit the awardwinning National Instruments Web site for software drivers and updates, a searchable KnowledgeBase, product manuals, step-bystep troubleshooting wizards, thousands of example programs, tutorials, application notes, instrument drivers, and so on.
–
Free Technical Support—All registered users receive free Basic Service, which includes access to hundreds of Application Engineers worldwide in the NI Developer Exchange at ni.com/ exchange. National Instruments Application Engineers make sure every question receives an answer. For information about other technical support options in your area, visit ni.com/services or contact your local office at ni.com/ contact.
•
System Integration—If you have time constraints, limited in-house technical resources, or other project challenges, National Instruments Alliance Partner members can help. The NI Alliance Partners joins system integrators, consultants, and hardware vendors to provide comprehensive service and expertise to customers. The program ensures qualified, specialized assistance for application and system development. To learn more, call your local NI office or visit ni.com/ alliance.
If you searched ni.com and could not find the answers you need, contact your local office or NI corporate headquarters. Phone numbers for our worldwide offices are listed at the front of this manual. You also can visit the Worldwide Offices section of ni.com/niglobal to access the branch office Web sites, which provide up-to-date contact information, support phone numbers, email addresses, and current events.
© National Instruments Corporation
A-1
LabVIEW Intermediate II Course Manual
Appendix A
Additional Information and Resources
Other National Instruments Training Courses National Instruments offers several training courses for LabVIEW users. These courses continue the training you received here and expand it to other areas. Visit ni.com/training to purchase course materials or sign up for instructor-led, hands-on courses at locations around the world.
National Instruments Certification Earning an NI certification acknowledges your expertise in working with NI products and technologies. The measurement and automation industry, your employer, clients, and peers recognize your NI certification credential as a symbol of the skills and knowledge you have gained through experience. areas. Visit ni.com/training for more information about the NI certification program.
LabVIEW Resources This section describes how you can receive more information regarding LabVIEW.
LabVIEW Publications LabVIEW Technical Resource (LTR) Newsletter Subscribe to LabVIEW Technical Resource to discover power tips and techniques for developing LabVIEW applications. This quarterly publication offers detailed technical information for novice users as well as advanced users. In addition, every issue contains a disk of LabVIEW VIs and utilities that implement methods covered in that issue. To order the LabVIEW Technical Resource, contact LTR publishing at (214) 706-0587 or visit www.ltrpub.com.
LabVIEW Books Many books have been written about LabVIEW programming and applications. The National Instruments Web site contains a list of all the LabVIEW books and links to places to purchase these books. Publisher information is also included so you can directly contact the publisher for more information on the contents and ordering information for LabVIEW and related computer-based measurement and automation books.
LabVIEW Intermediate II Course Manual
A-2
ni.com
Appendix A
Additional Information and Resources
info-labview Listserve info-labview is an email group of users from around the world who
discuss LabVIEW issues. The list members can answer questions about building LabVIEW systems for particular applications, where to get instrument drivers or help with a device, and problems that appear. To subscribe to info-labview, send email to:
[email protected]
To subscribe to the digest version of info-labview, send email to:
[email protected]
To unsubscribe to info-labview, send email to:
[email protected]
To post a message to subscribers, send email to:
[email protected]
To send other administrative messages to the info-labview list manager, send email to:
[email protected]
You also may want to search previous email messages at: www.searchVIEW.net
The info-labview web page is available at www.info-labview.org
© National Instruments Corporation
A-3
LabVIEW Intermediate II Course Manual
Index Symbols
B
.NET, 3-21 assemblies, 3-21 callback VI, 3-53 class libraries, 3-21 Common Language Runtime, 3-21 configuration files, 3-24 Constructor Nodes, 3-22 containers, 3-23 controls, 3-23 distributing applications, 3-24 distributing libraries, 3-24 environment, 3-21 events, 3-53 framework, 3-21 Global Assembly Cache, 3-22 handling events, 3-53 objects, 3-23 promoting assembly versions, 3-21 properties, 3-23 registering events, 3-53
buffered data DataSocket functions, 6-6
C Call Library Function Node configuring, 1-3 creating parameter list, 1-4 using, 1-1 callback VI .NET, 3-53 ActiveX, 3-19 certification (NI resources), A-2 Code Interface Node using, 1-1 communication DataSocket VI and functions, 6-12 valid URLs, 6-12 configuring .NET client applications, 3-24 containers ActiveX, 3-2 controls ActiveX, 3-2 automation refnum, 3-2 creating shared variables, 6-3
A ActiveX, 3-1 callback VI, 3-19 containers, 3-2 controls, 3-2 custom interfaces, 3-16 indicators, 3-2 Invoke Nodes, 3-2 objects, 3-2 properties, 3-2 Property Browser, 3-5 Property Nodes, 3-5 property pages, 3-5 viewing properties, 3-5 VIs, 3-2 automation custom interfaces, 3-16 refnum control, 3-2
© National Instruments Corporation
D DataSocket functions buffered data, 6-6 http protocol, 6-13 OLE for Process Control protocol, 6-13 opc protocol, 6-13 protocols, 6-12 URLs, 6-12 diagnostic tools (NI resources), A-1 documentation NI resources, A-1
I-1
LabVIEW Intermediate II Course Manual
Index
N
drivers (NI resources), A-1 dstp protocol, 6-13
National Instruments support and services, A-1 NI Certification, A-2 NI-PSP, 6-12 NI-PSP networking protocol, 6-4
E editing shared variables, 6-4 events .NET, 3-53 handling .NET, 3-53 examples (NI resources), A-1
O
file protocol, 6-13 front panel shared variables, 6-9 ftp protocol, 6-13
objects .NET, 3-23 ActiveX, 3-2 OLE for Process Control protocol DataSocket functions, 6-13 opc protocol DataSocket functions, 6-13
H
P
help technical support, A-1
KnowledgeBase, A-1
programming examples (NI resources), A-1 promoting .NET assembly versions, 3-21 properties .NET, 3-23 ActiveX, 3-2 setting ActiveX, 3-5 viewing ActiveX, 3-5 Property Nodes ActiveX, 3-5 protocols dstp, 6-12 psp protocol, 6-12
L
R
live data sharing, 6-2
refnums automation, 3-2 remotely calling VIs, 2-2
F
I indicators ActiveX, 3-2 instrument drivers (NI resources), A-1 Invoke Nodes ActiveX, 3-2
K
M
S
methods .NET, 3-23 ActiveX, 3-2 multicasting, 4-5
LabVIEW Intermediate II Course Manual
shared variables, 6-2 configuration, 6-4 creating, 6-3
I-2
ni.com
Index
editing, 6-4 front panel, 6-9 in libraries, 6-3 sharing live data with other VIs and applications, 6-12 sharing data valid URLs, 6-12 software (NI resources), A-1 stand-alone applications .NET, 3-24 support technical, A-1
Web resources, A-1
T TCP using, 5-2 technical support, A-1 training (NI resources), A-2 troubleshooting (NI resources), A-1
U UDP multicast, 4-5 using, 4-2 User Datagram Protocol (UDP) See also UDP
V variant data ActiveX, 3-2 VI Server calling other application instances on Web, 2-2 calling VIs remotely, 2-2 VIs calling remotely, 2-2
W Web calling other instances, 2-2
© National Instruments Corporation
I-3
LabVIEW Intermediate II Course Manual
Course Evaluation Course _______________________________________________________________________________________ Location _____________________________________________________________________________________ Instructor _________________________________________
Date ____________________________________
Student Information (optional) Name ________________________________________________________________________________________ Phone ___________________________________
Company _________________________________________
Instructor Please evaluate the instructor by checking the appropriate circle.
Unsatisfactory Poor
Satisfactory Good
Excellent
Instructor’s ability to communicate course concepts
❍
❍
❍
❍
❍
Instructor’s knowledge of the subject matter
❍
❍
❍
❍
❍
Instructor’s presentation skills
❍
❍
❍
❍
❍
Instructor’s sensitivity to class needs
❍
❍
❍
❍
❍
Instructor’s preparation for the class
❍
❍
❍
❍
❍
❍
❍
❍
❍
❍
❍
❍
❍
❍
❍
Course Training facility quality Training equipment quality Was the hardware set up correctly? The course length was
❍ Too long
❍ Yes
❍ No
❍ Just right
❍ Too much
The detail of topics covered in the course was The course material was clear and easy to follow. Did the course cover material as advertised?
❍ Too short
❍ Yes
❍ Yes
❍ Just right
❍ No
❍ Not enough
❍ Sometimes
❍ No
I had the skills or knowledge I needed to attend this course. ❍ Yes ❍ No If no, how could you have been better prepared for the course? ____________________________________________________________________ _____________________________________________________________________________________________ What were the strong points of the course? __________________________________________________________ _____________________________________________________________________________________________ What topics would you add to the course? ___________________________________________________________ _____________________________________________________________________________________________ What part(s) of the course need to be condensed or removed? ____________________________________________ _____________________________________________________________________________________________ What needs to be added to the course to make it better? ________________________________________________ _____________________________________________________________________________________________ How did you benefit from taking this course? ________________________________________________________ _____________________________________________________________________________________________ Are there others at your company who have training needs? Please list. ____________________________________ _____________________________________________________________________________________________ _____________________________________________________________________________________________ Do you have other training needs that we could assist you with? _________________________________________ _____________________________________________________________________________________________ How did you hear about this course? ❍ NI Web site ❍ NI Sales Representative ❍ Mailing
❍ Co-worker
❍ Other _____________________________________________________________________________________