LabVIEW Intermediate II (Connectivity Course Manual) PDF
LabVIEW Intermediate II (Connectivity Course Manual) PDF
TM
Course Software Version 8.0 October 2005 Edition Part Number 323758B-01 LabVIEW Intermediate II Course Manual
Copyright 20042005 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 19952003 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: HelpPatents 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 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 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
iii
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
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 New User Begin Here LabVIEW Basics I* LabVIEW Basics II* Skills learned: LabVIEW environment navigation Basic application creation using LabVIEW Experienced User LabVIEW Intermediate I* LabVIEW Intermediate II* Skills learned: Modular application development Structured design and development practices Memory management and VI performance improvement Advanced User LabVIEW Advanced Application Development Skills learned: Large application design Code reuse maximization Object-oriented programming in LabVIEW
Certifications Certified LabVIEW Associate Developer Exam Skills tested: LabVIEW environment knowledge Certified LabVIEW Developer Exam 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.
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 lessons 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
Description Folder containing all the VIs and support files needed to complete the exercises in this course Folder containing the completed versions of the VIs you build in the exercises for this course
Solutions
vi
ni.com
Student Guide
E. Course Goals
This course presents the following topics: Networking technologies External procedure call model Broadcast model Client/server model Publish/subscribe model Calling shared libraries from LabVIEW Programmatically controlling VIs using the VI Server Using the VI Server functions to programmatically load and operate VIs and LabVIEW itself Using LabVIEW as an ActiveX client Using LabVIEW as an ActiveX server ActiveX events Using LabVIEW as a .NET client
vii
Student Guide
.NET events
Implementing the broadcast model Using the UDP VI and functions to create a UDP multicast session Using the TCP/IP VI and functions to communicate with other applications locally and over a network Using the Shared Variable node to read, write, and share data among VIs and other applications locally and over a network Implementing the client/server model
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 HelpFind 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 FilePage SetupOptions 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 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.
italic
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. 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. Text in this font denotes a specific platform and indicates that the text following it applies only to that platform.
monospace bold
platform
ix
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
1-1
Lesson 1
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.
1-2
ni.com
Lesson 1
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.
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
1-3
Lesson 1
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.
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
1-4
ni.com
Lesson 1
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.
1-5
Lesson 1
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:
Note
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. Use the Pass pull-down menu to indicate whether you want to pass the value or a pointer to the value.
1-6
ni.com
Lesson 1
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 Pointera string followed by a null character Pascal String Pointera string preceded by a length byte String Handlea 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.
Note
Do not attempt to resize a string with system functions, such as realloc, because your system might crash. 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.
1-7
Lesson 1
String Data
\00
\00
\00
\04
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.
1-8
ni.com
Lesson 1
NULL Character
\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.
1-9
Lesson 1
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.
Note
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.
1-10
ni.com
Lesson 1
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.
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.
1-11
Lesson 1
Exercise 1-1
Goal
Computer Name
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 computers network address in LabVIEW by using the String to IP and IP to String functions located on the TCP/IP palette.
Note
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
1-12
ni.com
Lesson 1
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.
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. Stop Case The stop case simply finishes the state machine, thereby ending the While Loop and the program.
1-13
Lesson 1
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.
1-14
ni.com
Lesson 1
LabVIEW Data Type String (Pass as C String Pointer) U32 U32 (Pass by pointer) I32 Varies (Use Adapt to Type) 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.
1-15
Lesson 1
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.
1-16
ni.com
Lesson 1
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.
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.
1-17
Lesson 1
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.
1-18
ni.com
Lesson 1
Confirm that the function prototype matches Figure 1-4. Click the OK button.
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.
1-19
Lesson 1
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.
1-20
ni.com
Lesson 1
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.
1-21
Lesson 1
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.
1-22
ni.com
Lesson 1
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
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.
1-23
Lesson 1
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.
Set the value of the constant to 00000200. Label the constant Ignore Arguments.
1-24
ni.com
Lesson 1
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.
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.
1-25
Lesson 1
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.
1-26
ni.com
Lesson 1
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: 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
Lesson 1
Notes
1-28
ni.com
VI Server
2
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. A. What is VI Server? B. VI Server Programming Model C. VI Server Functions D. Remote Communication E. Dynamically Calling and Loading VIs
Topics
2-1
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 FileVI 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.
2-2
ni.com
Lesson 2
VI Server
ActiveX Interface
TCP/IP
LabVIEW
TCP/IP Client
Block Diagram AccessLabVIEW 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 AccessIf you are using the VI Server on a remote computer, LabVIEW uses the TCP/IP protocol as the means of communication. ActiveX InterfaceActiveX clients such as Visual Basic, Visual C++, and Excel applications can use the VI Server to run LabVIEW applications.
2-3
Lesson 2
VI Server
With a refnum to a VI, you can update all the properties of the VI available in the FileVI 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.
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.
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 ReferenceOpens a reference to a local or remote application instance. Open VI ReferenceOpens a reference to a VI on the local or remote computer or dynamically loads a VI from disk. Property NodeGets and sets VI, object, or application properties. Invoke NodeInvokes methods on a VI, object, or application. Call By Reference NodeCalls a dynamically loaded VI. Close ReferenceCloses open references to the VI, object, or application you accessed using the VI Server.
2-5
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 CreateInvoke Node, and selecting a method from the shortcut menu.
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
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.
2-7
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 FileVI 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.
Tip
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.
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.
2-8
ni.com
Lesson 2
VI Server
Tip
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.
VI Server Configuration
To configure the VI Server, select ToolsOptions 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. ProtocolsSets the protocols for the VI Server. TCP/IPEnables 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. PortSets 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 nameSets 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. Use defaultSets 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
Lesson 2
VI Server
ActiveX(Windows) Enables VI server support for ActiveX Automation. This checkbox is checked by default.
Accessible Server ResourcesIndicates the tasks that remote applications can accomplish. VI callsAllows 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 methodsAllows 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 propertiesAllows remote applications to read and set the properties of the VI Server. This checkbox is checked by default. Control methods and propertiesAllows 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.
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 listLists 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/addressEnter the name or IP address of the machine you want to add to the Machine access list. Allow AccessAllows access to the machine(s) selected in Machine access list. Deny AccessDenies access to the machine(s) selected in Machine access list. AddAdds a new entry to the Machine access list. The new entry appears below the selected entry in the Machine access list. RemoveRemoves the selected entry from the Machine access list.
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,
2-11
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.
2-12
ni.com
Lesson 2
VI Server
Exercise 2-1
Goal
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 ToolsOptions 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
2-13
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.
2-14
ni.com
Lesson 2
VI Server
Exercise 2-2
Goal
VI Statistics
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.
Properties String 32-bit Integer 32-bit Integer Table, Column headers visible
Default Value Empty (defaults to local machine) 0 0 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.
2-15
Lesson 2
VI Server
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.
2-16
ni.com
Lesson 2
VI Server
Implementation
1. Create the front panel as shown in Figure 2-3.
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 ItemsColumn 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
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 CreateProperty ApplicationExported VIs in Memory from the shortcut menu to create an ExportedVIs Property Node. Place a Close Reference function on the block diagram.
Tip
Make sure to leave plenty of space between the Property Node and the Close Reference function because you insert more code between them. Wire the block diagram as shown in Figure 2-4.
2-18
ni.com
Lesson 2
VI Server
3. Access 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 CreatePropertyVI 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.
2-19
Lesson 2
VI Server
Tip
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. 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.
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.
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 CaseIdle 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.
Tip
The Format Into String function determines the string representation of an enumerated value. 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.
2-21
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.
Tip
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. 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.
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.
2-23
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.
2-24
ni.com
Lesson 2
VI Server
Exercise 2-3
Goal
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.
2-25
Lesson 2
VI Server
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 WindowOpen 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.
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.
2-27
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 ToolsOptions 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.
2-28
ni.com
Lesson 2
VI Server
2-29
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 ControlsAll ControlsRefnum and place a VI refnum on the front panel. Right-click the refnum and select Select VI Server ClassBrowse 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.
2-30
ni.com
Lesson 2
VI Server
Tip
You also can create a strictly typed refnum by dragging and dropping a VI icon onto the refnum. 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.
2-31
Lesson 2
VI Server
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.
2-32
ni.com
Lesson 2
VI Server
strictly typed referenceand 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.
2-33
Lesson 2
VI Server
Exercise 2-4
Goal
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 VIs 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 ClassBrowse 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.
2-34
ni.com
Lesson 2
VI Server
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
2-35
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.
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.
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.
2-37
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.
2-38
ni.com
Lesson 2
VI Server
Notes
2-39
Lesson 2
VI Server
Notes
2-40
ni.com
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
3-1
Lesson 3
Tip
Select Tools.NET & ActiveXAdd ActiveX Controls to Palette to add custom control files to the ActiveX Controls palette.
3-2
ni.com
Lesson 3
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 Sets Properties Automation Server Defines and Exposes Automation Objects Type Library (.TLB) Describes Programmable Objects (Can be Part of DLL or Stand-Alone)
Gets Properties
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.
3-3
Lesson 3
3-4
ni.com
Lesson 3
run. The default mode is run mode, where you interact with the object as a user would.
3-5
Lesson 3
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.
3-6
ni.com
Lesson 3
Exercise 3-1
Goal
Browse to URL
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.
Properties
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.
3-7
Lesson 3
object in the InternetExplorer folder. In this exercise, you use the following properties and methods of the IWebBrowser2 object: Visible propertyWhen 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 methodThe 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.
Tip
The LabVIEW context help provides descriptions of many ActiveX properties and methods.
Implementation
1. Create the front panel as shown in Figure 3-2.
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.
3-8
ni.com
Lesson 3
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 CreateConstant from the shortcut menu to create an Automation Refnum constant. Right-click the Automation Refnum constant and choose Select ActiveX ClassBrowse 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.
3-9
Lesson 3
Right-click the automation refnum output of the Automation Open function and select CreatePropertyVisible 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 CreateMethodNavigate 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 EditImport 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 EditPaste. Double-click the Rectangle tool to create a black box around the icon.
3-10
ni.com
Lesson 3
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.
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.
3-11
Lesson 3
Exercise 3-2
Goal
VI Statistics Report
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.
Properties
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.
3-12
ni.com
Lesson 3
Implementation
1. Modify the front panel of the original VI Statistics VI.
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.
3-13
Lesson 3
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.
3-14
ni.com
Lesson 3
Client Application Possible Actions: Creates Object Instance Gets an Existing Object Gets or Sets Properties Invokes Methods Dispatches Action Sets Properties Automation Server: LabVIEW Defines and Exposes Automation Objects Type Library (.tlb) Describes Programmable Objects (Can be Part of DLL or Stand-Alone) LabVIEW also can act as an ActiveX server
Gets Properties
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 ToolsOptions to display the Options dialog box. Select VI Server: Configuration from the top pull-down menu and place a checkmark in the ActiveX checkbox.
3-15
Lesson 3
3-16
ni.com
Lesson 3
Exercise 3-3
Goal
Frequency Response VI
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 ToolsMacroSecurity, 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 ToolsMacroMacros, 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: The script creates an ActiveX object, LabVIEW.Application, using the CreateObject function.
3-17
Lesson 3
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 FileClose and Return to Microsoft Excel. 7. Run the macro in Excel by pressing the <Ctrl-L> keys. You can clear the chart by pressing the <Ctrl-M> 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.
3-18
ni.com
Lesson 3
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.
3-19
Lesson 3
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.
Note
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. 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.
3-20
ni.com
Lesson 3
.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 LibrariesA 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. AssembliesA 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
3-21
Lesson 3
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.
3-22
ni.com
Lesson 3
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
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 FileVI 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 FileVI 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.
3-23
Lesson 3
On the front panel or block diagram, right-click a .NET object and select CreateProperty Node or CreateInvoke 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 CreateProperty or CreateInvoke, 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
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.
3-24
ni.com
Lesson 3
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.
3-25
Lesson 3
Exercise 3-4
Goal
Font Dialog
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.
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
3-26
ni.com
Lesson 3
.NET Assembly provides the newest version of the dialog, which has additional features and improved integration with other Windows components.
Type Cluster Control Constructor Node Constructor Node Enum Indicator Cluster Indicator
Properties
.NET Reference, System.Drawing.Font class .NET Reference, System.Drawing.Color class Values defined by FontDialog object Error Cluster
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.
3-27
Lesson 3
ShowDialog MethodDisplays the font dialog. This method returns an enumerated type which indicates the users 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 PropertyReturns 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 PropertyReturns 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.
3-28
ni.com
Lesson 3
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 CreatePropertyShowColor 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 CreateConstant from the shortcut menu. Set the value of the constant to True. Right-click the reference output of the FontDialog Property Node and select CreateMethodShowDialog() from the shortcut menu to create a FontDialog Invoke Node. Right-click the ShowDialog output of the FontDialog Invoke Node and select CreateIndicator 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 CreatePropertyFont 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 CreateIndicator from the shortcut menu to create the Font output described in Table 3-3.
3-29
Lesson 3
Right-click the Color output of the FontDialog Property Node and select CreateIndicator 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 CreateControl 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 CreateIndicator 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 ReplaceModern Ring & EnumEnum from the shortcut menu.
Note
Converting the ring control into an enumerated type control allows you to better control Case structures with the result of the dialog. Create an icon and connector pane similar to Figure 3-11.
3-30
ni.com
Lesson 3
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 <Alt-Tab> 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.
Tip
Refer to the Design section for a suggestion on how to convert a .NET Color reference to a LabVIEW color.
3-31
Lesson 3
Exercise 3-5
Goal
Word Processor
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.
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.
3-32
ni.com
Lesson 3
However, you still need to provide an interface to activate the various functions.
Name TextBox
Properties .NET Container with a System.Windows.Forms.RichTextBox object inserted Strict Type Definition Custom Control Strict Type Definition Custom Control Strict Type Definition Custom Control Strict Type Definition Custom Control Strict Type Definition Custom Control Strict Type Definition Custom Control Strict Type Definition Custom Control Strict Type Definition Custom Control Strict Type Definition Custom Control
Boolean button Boolean button Boolean button Boolean button Boolean button Boolean button Boolean button Boolean button Boolean button
3-33
Lesson 3
Open EventPrompts 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 EventPrompts 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 EventCalls 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 EventPrompts 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 EventCalls the Cut method of the RichTextBox. Copy EventCalls the Copy method of the RichTextBox. Paste EventCalls the Paste method of the RichTextBox. Undo EventCalls the Undo method of the RichTextBox Close EventExits the event loop and enter the cleanup section. This Event structure case should handle the Panel Close? filter event. Cleanup SectionCloses all open references, including the RichTextBox reference, and handle errors with a simple error handler.
3-34
ni.com
Lesson 3
Clear MethodRemoves all text from the text box. LoadFile MethodLoads 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 MethodSaves 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 PropertyApplies 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 PropertyApplies 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 MethodSearches the RichTextBox for a string of characters. This method returns the offset within the function of the first character in the matching string. Select MethodSelects text in the text box. Use this property to select a string after it has been found with Find. Focus MethodSets 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 MethodCopies selected text to the Windows clipboard and then deletes it. Copy MethodCopies selected text to the Windows clipboard. Paste MethodPastes text that has been previously placed on the Windows clipboard at the current cursor location.
3-35
Lesson 3
Implementation
1. Build the VI front panel.
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.
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
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 FileVI 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.
3-37
Lesson 3
3. Create the Initialization section, Cleanup section, Close event, and main program structure.
Switch to the VI block diagram. Right-click the TextBox terminal and select CreateProperty 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 CreateConstant 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 <This VI> from the Event Sources list.
3-38
ni.com
Lesson 3
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. 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.
Right-click the border of the Event Structure and select Add Event Case from the shortcut menu. Select ControlsNew from the Event Sources list. Select Value Change from the Events list. Click the OK button. Right click the .NET Refnum wire and select CreateMethod Clear() from the shortcut menu to create a Clear Invoke Node. Right-click the stop tunnel on the event structure and select CreateConstant from the shortcut menu to create a False constant. Wire the diagram as shown in Figure 3-15.
3-39
Lesson 3
Note
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. 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 ControlsCut 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.
3-40
ni.com
Lesson 3
Right-click the border of the Event Structure and select Duplicate Event Case from the shortcut menu. Select ControlsCopy 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.
Right-click the border of the Event structure and select Duplicate Event Case from the shortcut menu. Select ControlsPaste from the Event Sources list.
3-41
Lesson 3
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.
Right-click the border of the Event structure and select Duplicate Event Case from the shortcut menu. Select ControlsUndo 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.
3-42
ni.com
Lesson 3
Right-click the border of the Event structure and select Add Event Case from the shortcut menu. Select ControlsOpen 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.
Tip
Expand the File Dialog Express VI and select the terminals shown in Figure 3-20 to make the VI easier to wire. Right-click the prompt input of the File Dialog Express VI and select CreateConstant 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 CreateConstant 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 CreateConstant from the shortcut menu.
3-43
Lesson 3
Enter *.rtf in the string constant. Place a Compound Arithmetic function in the event case. Right-click the Compound Arithmetic function and select Change ModeAND 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 CreateMethod 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 CreateConstant from the shortcut menu to create a numeric constant. Enter 43 for the value of the numeric constant.
Note
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. Right-click the stop tunnel on the Event structure and select CreateConstant from the shortcut menu to create a False constant. Wire the diagram as shown in Figure 3-20 and Figure 3-21.
3-44
ni.com
Lesson 3
Right-click the border of the Event structure and select Duplicate Event Case from the shortcut menu. Select ControlsSave 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.
3-45
Lesson 3
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.
Right-click the border of the Event structure and select Add Event Case from the shortcut menu. Select ControlsFont 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.
3-46
ni.com
Lesson 3
Right-click the .NET Refnum wire and select CreateProperty 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 CreateMethod 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 CreateConstant from the shortcut menu to create a False constant. Wire the diagram as shown in Figure 3-23. 12. Create the Find event.
Right-click the border of the Event structure and select Add Event Case from the shortcut menu. Select ControlsFind from the Event Sources list.
3-47
Lesson 3
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.
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 CreateMethod 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 CreateMethod 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 CreateMethod Focus() from the shortcut menu to create a Focus Invoke Node. Place the Invoke Node in the True case of the case structure.
3-48
ni.com
Lesson 3
Place a String Length function in the True case of the Case structure. Right-click the stop terminal on the Event structure and select CreateConstant 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 <Enter> 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.
3-49
Lesson 3
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.
3-50
ni.com
Lesson 3
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.
Caution
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. 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.
3-51
Lesson 3
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.
3-52
ni.com
Lesson 3
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.
3-53
Lesson 3
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.
Note
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. 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.
3-54
ni.com
Lesson 3
Exercise 3-6
Goal
Auto Save
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.
3-55
Lesson 3
Type Cluster Control .NET Refnum Control Numeric Control .NET Refnum Indicator .NET Refnum Indicator Cluster Indicator
Name error in TextBox reference Interval (ms) Timer reference TextBox reference out error out Error Cluster
Properties
Default Value No Error Not a refnum 30000 Not a refnum Not a refnum No Error
.NET Reference, System.Windows.Forms.RichTextBox class Double precision numeric .NET Reference, System.Timers.Timer class .NET Reference, System.Windows.Forms.RichTextBox class Error Cluster
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.
3-56
ni.com
Lesson 3
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 ClassBrowse 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.
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.
3-57
Lesson 3
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 CreateMethodStart() from the shortcut menu. Right-click the reference output of the Start Invoke Node and select CreateIndicator 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.
3-58
ni.com
Lesson 3
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 MethodSaveFile(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 CreateConstant 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.
3-59
Lesson 3
Right-click the VI Icon and select Edit Icon from the shortcut menu. In the Icon Editor select EditImport 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 EditPaste. 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.
3-60
ni.com
Lesson 3
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 CreateConstant 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 <Windows Logo-D> 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.
3-61
Lesson 3
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.
Tip
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. Open Windows Explorer. Paste the temporary directory path into the Address field and press <Enter>. 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.
3-62
ni.com
Lesson 3
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 objectsApplication 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.
3-63
Lesson 3
Notes
3-64
ni.com
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
4-1
Lesson 4
Broadcasting Data
4-2
ni.com
Lesson 4
Broadcasting Data
101.5
MHz
101.5
MHz
99.1 MHz
4-3
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.
The broadcaster is simpler because it does not require a wait. The broadcaster opens the UDP port, sends the data, and closes the port.
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 establishmentUnlike TCP, UDP does not wait to confirm a connection before transferring data, so no delay is introduced. No connection stateBecause 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 overheadUDP segments have 8 bytes of overhead, compared to 20 bytes of overhead for TCP segments. Unregulated send rateUDP send rate is only limited by the rate of data generation, CPU, clock rate, and access to Internet bandwidth
4-5
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 1
Datagram remains on the host computer. 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
4-6
ni.com
Lesson 4
Broadcasting Data
Exercise 4-1
Goal
VI Statistics Broadcast
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.
Name Multicast Address Number Running Port Number in Memory Port Local Port
Properties
Unsigned 16-bit Integer 58431 Unsigned 16-bit Integer 58432 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.
4-7
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.
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.
4-8
ni.com
Lesson 4
Broadcasting Data
Tip
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. Right-click the stop terminal of the While Loop and select CreateControl 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.
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.
4-9
Lesson 4
Broadcasting Data
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.
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.
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.
4-11
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.
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.
4-13
Lesson 4
Broadcasting Data
Notes
4-14
ni.com
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
5-1
Lesson 5
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.
For higher performance, you can process multiple commands after you open the connection. After executing the commands, you can close the
5-2
ni.com
Lesson 5
connection. This flowchart serves as a model to demonstrate implementing a given protocol in LabVIEW.
Initialize Server
Yes
Close Connection
5-3
Lesson 5
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.
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.
5-4
ni.com
Lesson 5
5-5
Lesson 5
Exercise 5-1
Goal
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.
5-6
ni.com
Lesson 5
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.
5-7
Lesson 5
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.
Note
You can run the client and server VIs on the same computer if the computer is not networked.
5-8
ni.com
Lesson 5
4. Close the Simple Data Client VI and Simple Data Server VIs. Do not save changes.
5-9
Lesson 5
5-10
ni.com
Lesson 5
CRLFWaits 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. ImmediateWaits 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 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: 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
Lesson 5
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.
5-12
ni.com
Lesson 5
Exercise 5-2
Goal
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.
5-13
Lesson 5
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 TCP File Sender TCP Server TCP File Receiver
File Read
Original File
New File
5-14
File Write
ni.com
Lesson 5
Properties Existing only browse option, Browse Button Visible Unsigned 16-bit Integer Signed 32-bit Integer
Properties New or Existing browse option, Browse Button Visible Unsigned 16-bit Integer
Lesson 5
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.
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.
5-16
ni.com
Lesson 5
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 CreateConstant 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 CreateConstant 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.
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
Wire the diagram as shown in Figure 5-11. 5. Send the 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.
5-18
ni.com
Lesson 5
Right-click the code input of the Clear Specific Error VI and select CreateConstant 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.
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.
5-19
Lesson 5
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 CreateConstant 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 CreateConstant 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.
5-20
ni.com
Lesson 5
Right-click the bytes to read input of the TCP Read function and select CreateConstant 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.
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 CreateConstant 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.
5-21
Lesson 5
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 CreateConstant 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.
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.
5-22
ni.com
Lesson 5
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 neighbors 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.
5-23
Lesson 5
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.
5-24
ni.com
Lesson 5
Notes
5-25
Lesson 5
Notes
5-26
ni.com
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
6-1
Lesson 6
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.
6-2
ni.com
Lesson 6
6-3
Lesson 6
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.
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
6-4
ni.com
Lesson 6
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.
6-5
Lesson 6
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
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
6-7
Lesson 6
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
6-8
ni.com
Lesson 6
buffering for the DataSocket Server. For other protocols, refer to the server documentation for more information about server-side buffering for that server.
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: 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
Lesson 6
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.
6-10
ni.com
Lesson 6
6-11
Lesson 6
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.
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
6-12
ni.com
Lesson 6
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
contains data. The following table shows examples of each protocol URL.
6-13
Lesson 6
URL
psp
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
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.
6-14
ni.com
Lesson 6
Exercise 6-1
Goal
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
6-15
Lesson 6
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 NewVariable 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 NewVariable from the shortcut menu. Give the new variable the following properties: Name: Data Data Type: Double Variable Type: Network-Published
6-16
ni.com
Lesson 6
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.
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.
6-17
Lesson 6
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 CreateConstant 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.
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.
6-18
ni.com
Lesson 6
4. Open the block diagram. 5. Build the block diagram shown in Figure 6-4.
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.
6-19
Lesson 6
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.
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 \\<Computer Name>\Shared Data\Stop in the Path text box, where <Computer Name> is the name or IP address of your server.
6-20
ni.com
Lesson 6
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 \\<Computer Name>\Shared Data\Data in the Path text box, where <Computer Name> 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.
6-21
Lesson 6
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.
6-22
ni.com
Lesson 6
Notes
6-23
Lesson 6
Notes
6-24
ni.com
This appendix contains additional information about National Instruments technical support options and LabVIEW resources.
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.
A-1
Appendix A
LabVIEW Resources
This section describes how you can receive more information regarding LabVIEW.
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.
A-2
ni.com
Appendix A
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 send other administrative messages to the info-labview list manager, send email to:
[email protected]
A-3
Index
Symbols
.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
B
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
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
Index
N
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
objects .NET, 3-23 ActiveX, 3-2 OLE for Process Control protocol DataSocket functions, 6-13 opc protocol DataSocket functions, 6-13
F
file protocol, 6-13 front panel shared variables, 6-9 ftp protocol, 6-13
H
help technical support, A-1
P
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
I
indicators ActiveX, 3-2 instrument drivers (NI resources), A-1 Invoke Nodes ActiveX, 3-2
K
KnowledgeBase, A-1
L
live data sharing, 6-2
R
refnums automation, 3-2 remotely calling VIs, 2-2
M
methods .NET, 3-23 ActiveX, 3-2 multicasting, 4-5
S
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
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
I-3
Course Evaluation
Course _______________________________________________________________________________________ Location _____________________________________________________________________________________ Instructor _________________________________________ Date ____________________________________
Instructor
Please evaluate the instructor by checking the appropriate circle. Instructors ability to communicate course concepts Instructors knowledge of the subject matter Instructors presentation skills Instructors sensitivity to class needs Instructors preparation for the class
Unsatisfactory Poor Satisfactory Good Excellent
Course
Training facility quality Training equipment quality Was the hardware set up correctly? The course length was Too long Yes No Too short Just right Not enough No Sometimes Too much Yes Yes No Just right
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?
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 _____________________________________________________________________________________