Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Задани на лабораторные работы. ПРК / Professional Microsoft Robotics Developer Studio

.pdf
Скачиваний:
126
Добавлен:
20.04.2015
Размер:
16.82 Mб
Скачать

www.it-ebooks.info

Chapter 10: Microsoft Visual Programming Language Basics

Figure 10-22

This diagram is significantly simpler than previous implementations of the ForLoop. When a message is passed to the input, the If activity determines whether any counts are remaining. If so, it passes a message to the Calculate activity, which calculates the value of the Current variable plus one and then sets it back into the Current variable. The final Calculate is used to put the previous value of the Current variable on the wire to be output as a CountNotification and a result message.

Execute this diagram to verify that it does count in the proper order and then take the time to step through it using the debugger if the execution order is not immediately clear.

Another possible way to improve the ForLoop custom activity is to add an End notification that sends a message when the loop has completed. You’ll see how to add this in Example 9 in the next section.

Using Lists and Switch Activities

The only activities left to describe in the Basic Activities toolbox are the List activities, the List Functions activities, and the Switch activities.

The Switch activity is much like the If activity. Instead of conditions, the Switch activity expects data values to be specified, like case statements associated with a switch statement in an imperative language. The data values are compared to the data value on the wire and the input message is propagated to the first case that matches. If none of the cases matches, the message is propagated to the Else output.

The Switch activity is useful for taking an action based on a specific data value on the wire. This is often done when implementing a state machine. In this case, the values in the Switch activity represent

493

www.it-ebooks.info

Part III: Visual Programming Language

various possible states, and the action that the state machine takes depends on the value of the state variable.

List and ListFunctions activities are used together to manage and operate on collections of typed data. A List activity generates an empty list of a specific type. Select the type of the list from the drop-down menu at the bottom of the activity icon. All of the basic VPL types are supported.

A list may be stored in a variable like any other data value. Simply create a new variable with the desired list type and use the Set and Get actions on the Variable action to set and retrieve the list.

The List Functions activity performs one of several possible operations on a list. Its inputs and outputs depend on the function that is selected from the drop-down menu on the bottom of the List Functions activity icon. The possible functions are listed in the following table:

Function

Inputs

 

 

Append

List: A list

 

Item: A data item of the same type as the list. The item on the

 

Item input is appended to the end of the list and the

 

resulting list is present on the output pin.

Concatenate

List1: A list

 

List2: A list of the same type

 

List2 is concatenated on the end of List1 and the resulting list

 

is present on the output pin.

Reverse

List: A list. A new list is constructed with the items in reverse

 

order from the input List. The new list is present on the

 

output pin.

Sort

List: A list. A new list is constructed with the items from the

 

input List sorted in ascending order.

RemoveItem

List: A list

 

Index: An integer that represents the position of the item to

 

be removed. Index 0 refers to the first item in the list.

 

The resulting list is present on the output pin.

InsertItem

List: A list

 

Item: A data item of the same type as the list

 

Index: An integer representing the position where the item is

 

to be inserted. Index 0 refers to the first item in the list.

 

The resulting list is present on the output pin.

GetIndex

List: A list

 

Item: A data item of the same type as the list. If the data item

 

is present in the list, an integer representing its position is

 

present on the output pin. As with the other functions, index

 

0 refers to the first item in the list.

 

 

494

www.it-ebooks.info

Chapter 10: Microsoft Visual Programming Language Basics

An Example Using List Activities

The 9-Lists project in the Chapter10 directory provides several examples showing how these activities can be used, including the Switch activity and a slightly enhanced version of the ForLoop activity from the previous section.

This diagram, shown in Figure 10-23, does text processing to transform input text into output text by replacing keywords with random words, similar to Mad Libs. In Mad Libs, a story is constructed by substituting new words into a story framework. A list of plural nouns, a list of adjectives, a list of professions, and a list of source phrases are all initialized and then manipulated by the diagram. The source phrases are replaced, if necessary, with random words from the other list and then concatenated into a final output, which is displayed in a dialog and spoken by the TexttoSpeechTTS activity.

Figure 10-23

The various lists are initialized at the top of the diagram. The Data activity in the upper left passes a message to the Initialize action of the PluralNouns activity. When it has initialized itself, it passes a message from its output to the Initialize action of the Adjectives activity. The Professions activity is initialized next and then the Phrases activity. The Phrases activity outputs a message with an integer Count value that represents the number of phrases in the list. This value is used to initialize the ForLoop activity in the second row of the diagram, much like what you have seen in previous diagrams.

The ForLoop activity begins counting and passes a CountNotification message to the GetOne action input on the Phrases activity. The phrase identified by that index is passed to a Calculate activity

495

www.it-ebooks.info

Part III: Visual Programming Language

where the value.Result string is placed on the input to the Switch activity. The Switch activity checks whether the input string is either “adj,” “pluralnoun,” or “profession.” If it matches any of those cases, it replaces that word with a Random entry from the appropriate list by passing a message to the GetRandom action input of the associated activity. The random string is passed to the Merge activity. If none of these keywords is matched, the string is passed unmodified to the MERGE.

The updated phrase is passed to a Calculate activity that concatenates the current Result with a space and the value of the phrase. The result is stored in the Result variable and a message is passed back to the ForLoop activity telling it to generate another CountNotification.

After all of the phrases in the Phrases activity have been processed, the ForLoop sends an EndNotification message to the Variable activity at the bottom of the diagram. The value of the Result variable is retrieved and sent to an AlertDialog as well as the TexttoSpeechTTS activity.

The source text was taken from a paragraph in the MRDS documentation, which describes potential users of VPL:

VPL is targeted for beginner programmers with a basic understanding of concepts like variables and logic. However, VPL is not limited to novices. The compositional nature of the programming language may appeal to more advanced programmers for rapid prototyping or code development. As a result, VPL may appeal to a wide audience of users including students, enthusiasts/hobbyists, as well as possibly web developers and professional programmers.

Some of the words in the text were replaced with one of the three keywords described above:

VPL is targeted for adj profession with a basic understanding of concepts like pluralnoun and pluralnoun. However, VPL is not limited to pluralnoun. The adj nature of the programming language may appeal to adj pluralnoun for rapid prototyping or code development. As a result, VPL may appeal to a wide audience of pluralnoun including profession, profession, as well as possibly profession and adj profession.

Each time the diagram is executed, a new paragraph is generated with different word substitutions. Go ahead and run the diagram a few times to see and hear its output.

The PluralNouns Activity

The PluralNouns, Adjectives, and Professions activities are essentially identical to each other except that they maintain different lists. The Initialize action of the PluralNouns activity is shown in Figure 10-24.

496

www.it-ebooks.info

Chapter 10: Microsoft Visual Programming Language Basics

Figure 10-24

The List activity in the upper right builds a new list and passes it to the first List Functions activity when a message is received on the input pin. The first Data activity also generates a single string of data and passes it to the first List Functions activity, which then adds it to the end of the list. Subsequent List Functions and Data activities are then executed until 10 plural nouns have been added to the list. At that point, the list is stored to the PluralNouns variable associated with this activity and a response message is sent to the output pin. The Initialize actions are nearly identical for the Adjectives and

Professions activities.

The Phrases Activity

The Phrases activity passes the number of items in its list as an output to be used by the main diagram. Figure 10-25 shows the Initialize action of the Phrases activity. Notice how the source text has been broken up into discrete phrases so that the keywords are isolated and can be replaced before the output text is reconstructed.

497

www.it-ebooks.info

Part III: Visual Programming Language

Figure 10-25

The GetRandom Action

The PluralNouns, Adjectives, and Professions activities support a GetRandom action that chooses a random element from each of their respective lists and places it on the output pin. Figure 10-26 shows the GetRandom action from the PluralNouns activity.

Figure 10-26

498

www.it-ebooks.info

Chapter 10: Microsoft Visual Programming Language Basics

Here, the MathFunctions activity from the Services toolbox is used to generate a random floating-point number between 0.0 and 1.0, inclusive. The MathFunctions activity supports a number of math functions, including random, trigonometry, exponent and logarithm, round and truncate, power, square root, and conversion functions between radians and degrees.

The Calculate activity calculates an index into the PluralNouns list with the following expression:

(int)(Result * 0.99 * state.PluralNouns.Count)

The resulting index ranges from 0 to the index of the last element in the list, inclusive. The 0.99 factor is to slightly scale the random number so that if a 1.0 value is input, the index will not reference past the end of the list.

The syntax used to retrieve an element from the list is similar to array indexing in C#:

state.PluralNouns[(int)(Result * 0.99 * state.PluralNouns.Count)]

The string retrieved from the list is passed to the output pin.

The GetOne action on the Phrases activity is very similar except that the input integer value is used to index the list instead of a random number.

A Final ForLoop Improvement

The ForLoop activity includes one small enhancement from the previous section. In the Count action, an EndNotification has been added. This notification is triggered once when the count has exceeded its maximum. The diagram for this action is shown in Figure 10-27.

Figure 10-27

499

www.it-ebooks.info

Part III: Visual Programming Language

This diagram is guaranteed to produce endless hours of entertainment for you and your coworkers, and with only slight modifications it can be used to generate haiku poetry for fun and profit.

Summary

This chapter has shown how to implement basic diagrams in VPL using the built-in basic activities along with a handful of services such as the TexttoSpeechTTS activity and the SimpleDialog activity. The VPL debugger was also demonstrated as a way to understand and debug diagram execution.

The next chapter demonstrates how to use VPL to control simulated and real-world robots.

500

www.it-ebooks.info

Visually Programming

Robots

The Microsoft Visual Programming Language (VPL) can be used to implement general-purpose programs that have nothing to do with robotics, but because it is part of the Microsoft Robotics Developer Studio SDK, this chapter focuses on robotic applications.

First, the relationship between VPL activities and DSS services is explained, and you’ll learn how to compile a diagram into a C# service implementation. Next you’ll learn how to associate an activity with a specific service. Simple examples are provided that demonstrate how to control actuators and read data from sensors.

More complicated examples are presented in Chapter 12.

VPL Activities and Services

A VPL activity can represent a DSS service. As explained in Chapter 3, a service implements a specific contract by supporting a number of operations on its main port. A service may also implement an alternate contract and its associated operations on a separate port. The VPL activity that represents the service has inputs for all of the operations on the main port and any alternate ports.

You know from the previous chapter that an activity may have more than one action associated with it. Each action has its own set of inputs and outputs. Each action associated with an activity corresponds to an operation supported by the service. For example, when you connect a wire to the input of the SimpleDialog service, three possible actions are supported: AlertDialog, PromptDialog, and ConfirmDialog. If you look at the implementation of the simple dialog in samples\Misc\Utility\Dialog\DialogTypes.cs, the DialogOperations class has operations defined for DsspDefaultLookup, DsspDefaultDrop, Alert, Prompt, and Confirm. The DisplayName attribute for the Alert class is “AlertDialog,” and this Alert operation corresponds to the Alert action in the SimpleDialog activity. The inputs and outputs for this

www.it-ebooks.info

Part III: Visual Programming Language

action are also defined by the Alert class. The input message for this operation is an AlertRequest class that contains a single DataMember string with the DisplayName attribute of “AlertText.” The output or response message is a DefaultSubmitResponseType or a Fault.

When you define an activity in a VPL diagram, you are really defining a DSS port. Each action in the activity corresponds to an operation on that port. The inputs and outputs of each action correspond to the input and response messages of that operation. The logic implemented in the diagram for a particular action defines what happens in the handler for that particular input message. VPL is really just a graphical way of describing the DSS model of service ports and messages.

As you might imagine, the notification outputs of an action correspond to notifications from a service, and a connection from a notification output to an input pin on a service corresponds to that service subscribing to the notifications. Not only do activities within a diagram correspond to ports within services, the top-level diagram itself represents a single service.

Note that VPL doesn’t enable any service functionality that is not already achievable using C# or some other .NET language and programming directly to the DSS model. However, nearly anyone who has written code to define services and pass messages between them will agree that VPL is a much simpler and more concise way of specifying the same functionality.

Compiling Diagrams to Services

Now that you know that VPL diagrams represent the DSS model of services, ports, and messages, you might wonder if it is possible to convert services to diagrams and whether it is also possible to convert a diagram to a service. Of course, the answer is yes; otherwise, this would be a very short section.

In the case of converting services to diagrams, you have already seen how this works in Chapter 10. All of the activities in the Services toolbox represent services that are present on the current machine. Each time one of these services is dragged onto the diagram, an activity icon is displayed that represents the service. All of the information about the service is available on the input and output pins showing

the various actions (operations) supported by the service port and the data passed in the input and response messages of each operation.

The more interesting case is converting a diagram to a service. When you press F5 or F10 to run a service, VPL has an interpreter, which executes the diagram. Another way to execute the diagram is to compile it into a service and then run that service.

You can compile a diagram into a service by clicking Build Compile as a Service. The first time you select this option for a particular diagram, VPL prompts for the destination directory for the service.

Service Compilation Options

A number of other properties affect how the service will be compiled. You can display these properties by clicking the Diagrams item in the Project toolbox. The properties are displayed in the Properties toolbox under the CompileSetting heading. The compile properties for the 8-CustomActivity (in order) VPL diagram are shown in Figure 11-1.

502