Sie sind auf Seite 1von 30

~ g

Microsoft Visual
',o
Programming
Language Basics
The Microsoft Visual Programming Language (VPL) is a new application development
environment designed specificaIly to work with 055 services. Programs are defined graphically in
data f10w diagrams rather than the typical sequence of commands and instructions found in other
programming languages. VPL provides an easy way to quickly define how data f10ws between
services. It is useful for beginning programmers because they can quickly specify their intent, but
it is also welI suited to help with prototyping and code generation for more experienced
prograrnmers. lt is also useful for specifying robotic orchestration services within the context of the
Microsoft Robotics Developer Studio SDK, but it can be used outside of robotics as welI.
This chapter covers what it means to work with a data f10w language, how to specify a data f10w
diagram using the basic activities provided by VPL, and how to debug and run it. You won't find
any robots in this chapter but you willlearn how to use VPL to control robots in Chapter 11.
What 15 a Data Flow Language?
Many people learn how to program using an imperative language such as BASIC or c++. Such a
language uses control statements to modify program state. This matches the underlying hardware
implementation of the CPU well because it is built to execute machine code statements that
modify memory.
When a program is data- or event-driven and has different parts that execute asynchronously, the
imperative programming model can become inefficient and difficult to use. The folIowing example
shows why this might sometimes be true.
Imagine a program as a city grid. Each intersection represents sorne processing that must be done,
and cars on the roads between intersedions r e p r e ~ n t data, as shown in Figure 10-1.
'\
Part 111: Visual Programming Language
....

... ::::::=....=...= ...=....
" e
/: :l..\-- ....-...-...=...=...
........ A
Figure 1.0-1.
A typical imperative program might take the folIowing form:
For each intersection
nat enough cars are waiting
Sleep far a time.
Do sorne calculations and call the next intersection routine with the results
The calculations done at each intersection can be arbitrarily camplex and may depend on the state of
multiple cars waiting at the intersection. This approach can lead to inefficency because the instructions
associated with each intersection must periodicaIly run to detennine whether enough cars are waiting.
In addition, because cars may arrive at each intersection at an arbitrary time, race conditions can arise if
the processing instructions at each intersection are not carefully defined.
In a data f10w language, the emphasis is on following the cars rather than processing the intersections.
A data f10w diagram for the city example above would look much like the city grid, with the roads
representing data connections and the intersections representing processing activities. None of the
intersection code runs until it is presented with data.
Let's say that data enters the diagram at the bottom and approaches intersection A. The code for
intersection A runs to process the data and puts the resulting state on the way to intersection B. The code
for intersection B then runs and sends the modified state to intersection C. Intersection e is prograrnmed
to wait until data is available on at least two of its roads befare passng the resulting data off to the left
and out of the grid. Now that there is no data in the grid, no cade runs until more data is available.
Multiple cars in the grid represent multiple data packets being processed simultaneously. Because the
calculations at each intersection depend only on the cars waiting for it, they can run at the same time as
another intersection.
It is to write a program for each intersection than it is to write instructions for managing the
entire grid. Similarly, it is simpler and more efficient to write small segments of cade that respond to data
inputs than it is to write cacle that attempts to contra! every intersection simuItaneously.
472
Chapter 10: Microsoft Visual Programming Language Basics
VPL is a data flow language that enables you to specify one or more MRDS services to process data in
parallel and to define the data connections between those services. In a robotics context, it is useful for
writing high-level orchestration services that control robot behavior. In the rest of this chapter, you will
learo how to implement algorithms using VPL.
The VPL Development Environment
5tart the VPL development environrnent by clicking 5tart Visual Programming Language. A window
similar to the one shown in Figure 10-2 is displayed.
FIle Edlt v-... BuId Run HeIp
a.1il; Actlvilles -" o.ag.... ",
"iI"AcIMly
-l
l

SJoin
i
eMerge i
iill
iis-.*h
.U.I
-x
{ f;-;d,

15. a:tr.;!'ES o sen'ces tri
I An:as Bu:nper , " hc-T'l '..,Me b:it:I...""s Ccn'"'eCt b'. &a;-g.ong M7n ,he o;lm b:",der
, AMasCore
:s-:)-J'ce t' thp lE-1 t,,")"'Op[
AMosllrM>
,
il\A.""" 5yn6cabon G
.BIoll Trn<ke<
, .. BIoll Trn<ker Calobf,
Bo&&t 9ASIC 51.>
Genen; C<
Boe-6Dt Generit Of
;10. Bo&&t Genen; fA,
., Cornman OSS Test


Figure 10-2
Note the following about the environrnent:
o The main cornmands are accessible from the main menu bar and the most cornmon cornmands
are on the toolbar.
o The work area consists of a central diagram aTea surrounded by four toolboxes. A diagrarn
consists of one or more activity boxes that are connected together. You drag acti\'ity boxes
from the various toolboxes to the central area. These toolboxes include the foIlowing:
O The Basic Activities toolbox contains blocks that control data flow and create data and
\l3riables.
O The Service toolbox shows aH of the services available to VPL. This list includes aH of the
services that are present in the MRDS bin directory.
473
Part 111: Visual Programming Language
Q The Project toolbox shows the diagrams and service configuration files induded in y
project.
Q The Properties toolbox shows the properties for the currently selected item so that Y'
view and edit the settings exposed by a service or activity.
A Simple VPL Diagram
VPL programs are called diagrams because they are defined by placing graphical icons in a diagra
connecting them with data How connections in the VPL development enviranment. Once the diagJ
has been defined, it can be executed within the VPL development environment or you can generat
MRDS service fram the diagram and ron that.
The easiest way to see how a diagram works is to actually build one. The following sections descri
how to create a new diagram and run it.
Creating a VPL Diagram
To create a pragram, follow these steps:
1. Start with a fresh diagram by clicking File Q New:The enviranment should look like Figu
Drag a Data activity fram the Basic Activities toolbox into the diagram space.
2. Click the data type drop-down arraw at the bottom of the activity and select string for the
of data. Type a string such as, Helio world, I'm VPL!, in the input field of the Data activil
activity should look like Figure 10-3.
Figure 10-3
3. No\\' drag the Text.t.oSpeechTTS activity fram the Services toolbox. The Services toolbox
contains a lot oE enmes so it often saves time to type par! of the name of the service that ye
in the Search box aboye the list of services. TIUs narraws the list down to only those servio
contain the search texto Position the 'I'ext toSpeechTTS activity to the right of the Da ta acl
474
Chapter 10: Microsoft Visual Programrning Language Basics
your
5earch Groups in the Services Toolbox
The Services toolbox contains many services, so the Search box at the top is very
you can
helpful. You will probably find that you do sorne of the same searches repeated.ly. The
Services toolbox provides a way for you to save common searches. Type dialog into the
Search box and a few services are displayed. Now click the plus (+) symbol next to All
Found. 1his creates another heading in the services list that contains all the services
that this search finds. You can expand or contract the list using the icon to the left of the
dialog heading. All the other services are found under the All Found heading. When
ramand
you no longer want to keep the dialog search results, you can click the X symbol to the
gram
right of this heading and it is deleted.
atean
:ribe
4. Place the mouse on the right output pin of the Data activity and drag the mouse to the
TexttoSpeechTTS activity. Notice that the comers of the TexttoSpeechTTS activity tum green,
indicating that this connection is allowed. When you release the mouse button, the Connection
dialog appears. This dialog enables you to select which message is being output from the source
activity and which message accepts the input in the destinatioI'J, activity. In this case, select
DataValue in the From: box and SayText in the To: box and press OK.
;ure 10-2. 5. Now the Data Connections dialog box opens. 1his enables you to map a particular data value in
the message output from the source to a target value in the mssage input to the destination.
Because the data value being passed is a string, it has a value and a length. Select value in the
he type
Value box and SpeechText in the Target box. A connection should appear between the two
vity. The
activities in the diagram as shown in Figure 10-4.
TexttoSpeechTTS
Figure 10-4
JX
you need
Congratulations! You have just written your first VPL diagram. Save it by clicking File Q Save As and
vices that
select an appropriate directory and project name. If you have any trouble creating this diagram, you can
activity.
find it in the ChapterlO directory in the l-Hello folder.
Running a VPL Diagram
To ron a diagram, first click File Q Open to load a previously saved diagram. Then follow these steps:
1. Click Run Q Start and press F5, or press the green forward arrow in the toolbar to run your
programo A dialog box appears that shows the console output as the program is executed.
-After a few seconds, you should hear your computer speak the words in the Data activity box.
The console output window is shown in Figure 10-5.
475
Part 111: Visual Prograrnming Language
S SeI\o1CB l.1f1
9 Moun'.ed _ res<>unes for assemt>ly "f.leJIJCJMierosoll Robolits SlOO>o (15)IbWds5runIime
ffi S!aftr'9 manites. load fi'-e:/,I/C 1Micms<>!1%2ORobobcs%20SIud!oIlo20(1 5)/1d226&I-1dl8-49aJ-bdE
Manifesl tomplete
i!l Mounled _ resoun:es lar assembIy 'tileJIICAfitrosoft Robotts Stud;o (1
.. L()al1!'q f f' ':"::< :l1h)3t .... "DO 'lt' :;,.1(-111.': .... 32';' f 1d! 7. 1 cmgf2"'"
fLr _':s
FIn;".' 3SSen1'J! "?.=
!'SCV,I1,;:S fm:r':safucm I,:,)t:.S');:::E-"i '11""" r"?x!T -:S:;2H '1 p":}). VHSCI
... -e.,,\To :3pc:'!,:v, -:J:lSU1] c-t,}:e
F'o;J;,a..... '':'r;:-2\E'"C
9 Moorned embedded resourte:5 for assembly "f.le:II/ClMicrosoll S!udio
ffi Spea:hTex1 Semce un dssp 'tpJlmsrsl.5000Mexttospeech
lB SetvK:e URI
Figure 10-5
2. After the program has Hnished its execution, press the Stop button to dismiss the Run dialogo
If Your Computer Won't Talk
If you run the HelIo diagram and you aren't able to hear the computer speak the words,
check the connections to your speakers and the volurne. Select the Speech item in the
system control panel and verify that the speech engine is configured properly. If you still
cannot hear the computer speak, you can substitute the SmpleDialog activity for the
Text toSpeechTTS activity in your diagram to display the words in a dialog box instead.
The 2-Hello VPL project in the ChapterlD directory shows how this is done.
Let's take a look at exactly what happened when this basic little diagram in Figure 10-4 was executed
The Data activity has a ver)' simple jobo When it receives a message on its input pin, it sends a messa:
on its output pin containing the data specified. Where did the input message come from? Its input pu
"unconnected. It turns out that VPL automatical1y sends an input message to aH top-level Data activit
when the prograrn starts.
Up until now, we've been speaking about messages on wires in pretty general terms, but it's time to 1
more specifie. You can tlnk of a message much like a C# or C++ structure. It has one or more fields
476
Result
__Output Pin
---Notification
Output Pin
A
....
...
Commenl
A."""-"lh 'NO ccp;es o1lhe 0..<"", D.alog
ate shO'AA the-t refa- ro the same
act.-4y
DirectionDialog
Action
Input Pin -- lo
Figure 10-7
Figure 10-8
__ x
!ic..k:W

3
.Me.-qe
" Ir
, s..*h
! II'IlJsl
_1.JsIF=:tans
1:...c: .;
, <>a!og
12
1
, .;. D<<<t>::n [}.a'og
. .. Drrectoo [}.a'og (V8)
JIi:l Sm';le O<olog
1

!

Each activity can have one or more inputs shown as square pins on the left side of the activity icon and
one or more outputs shown as square pins on the right side of the cono When there are multiple inputs
or outputs, only a single pin is shown and the desired input or output is selected with the Connections
dialog when a connection is made.
Sorne activities have an additional output called a IlOtification. A single response output message is
generated on an output pin as the result of a single input message on an input pino Notification outputs can
also send a message as a result of an input message but they more typically send a message as the result of
a change in internal state. As an example, consider the DirectionDialog activity shown in Figure 10-7.
When a message is received on the Action Input Pin, a different message is sent on the Result Output Pin,
usualIy indicating success or failure. If the input message changes the interna! state of the activity, it typicall:
generates a notification message as well. Sometirnes an externa! action, such as a user input event, changes
the state of an activity and it spontaneously generates a notification without any input message at all.
The 3-Notifications diagram in the ChapterlO directory illustrates this behavior. It is shown in Figure 10-E
A...,n
Part 111: Visual Programming Language
Inputs, Outputs, and Notifications
Chapter 10: Microsoft Visual Programming Language Basics
In the top row of activities, a message is initially generated by the Data activity on the left, which is sent
to the Get input of the DirectionDialog activity. It semis a response message containing its state to the
second Data activity, which then sends an output message containing the string "Success Response!" to
the SimpleDialog activity, where it is displayed in an AlertDialog. So far you have used the Action
Input Pin and the Response Output Pin of the DirectionDialog activity.
On the second row of activities, another DirectionDialog activity is shown on the left. However, this
icon actually represents the same activity as the DirectionDialog in the top row. You can tell because
they have the same name. When you drag onto the diagram an activity that is already present, VPL asks
you whether you want a completely new activity or just another reference to the existing activity. If you
specify that you want a new activity, the new activity is given a different name than the original activity.
While this might initially seem confusing, it really makes the diagrarns simpler because it reduces the
rat's nest of connections coming from a single activity when multiple inputs and outputs are used.
The output from the DirectionDialog activity that is used in the second row is the notification output.
This output sends a message to the SimpleDialog activity whenever the internal state of the
DirectionDialog changes. Just like the DirectionDialog, the SimpleDialog on the second row is
really just another reference to the same DirectionDialog activity shown on the first row.
This diagram also shows the use of the Comment activity. This activity has no effect on the functionality
of the diagram but it provides a way to document what is going on in the diagram.
Run the diagram and notice that the response is irnmediately displayed as a result of the data input
message on the top row of the diagram. Click the buttons on the DirectionDialog and you will see
messages displayed as a result of the notifications generated by the DirectionDialog activity on the
second row.
Basic Activities
The following activities can be found in the Basic Activities toolbox. These basic activities are used to
build the data connections between the activity blocks that represent services. Unlike the service
activities, they do not have a unique name.
They are defined briefly in the following table and discussed in more detail in the following sections.
Activity
Dati
variable
Calculate
Description
This activity is used to get or set the value of
a state variable.
This activity is used to calcu1ate a value from
one or more input values.
This activity is used to define static data that
is used as an input to another activity.
(Contnued)
479
Part 111: Visual Programming Language
Jon
Merge
If
Activity
Lst
Functons
Swtch
Lst
Actvty
. Comment
Description
This activity waits to send an output
message until it has received a message on
a1l of its inputs.
This activity forwards a message to its
output from any of its inputs.
This activity forwards a message on the first
output that has an expression that evaluates
to true.
This activity forwards a message on the first
output that matches the input value.
This activity holds a list of data.
This activity perfonns various operations on
a list of data.
This activity displays a comment in the
diagram.
This activity can be used to define a custom
activity that, in tum, contains other activities.
VPL Variables
In a data flow diagram, the program state is mostly encapsulated in the messages passed betwee
activities. Sometimes jt is necessary to define state that belongs to the diagram. This state is analc
the state in a service. Activities can set or retrieve trus state. This is useful because activities do nc
default, pass the same data to their output that they receive on their input.
You use the Varable activity to define and set or get the value of a variable. When you drag a
Variable activity from the Basic Activities toolbox onto the diagram, it is initially blank. Click ti
ellipse on the bottom of the activity to bring up the Define Variables dialog box, which enables YI
add and delete variables. Any Var able activity in the diagram can represent any defined varial
Load the 4-Variables diagram in the ChapterlO directory. It is shmvn in Figure 1()"9.
480
Chapter 10: Microsoft Visual Prograrnming Language Basics

""'Jo. "
+ ",Dl3g 1 ,;ConI
:iL iJ
Proo " I
f


'FllIl::D'lO:w$"*...: ...

-..
.fJil_:Z*"C'.'I__III!_ .II.__ .__ .
....
..
'J
.. .;.
... .
x

<hlog

.;. Ooection lli3log
Ooection lli3log (VD)
lis....,.. DiaIog
fII PI< lIow llBIcI B1m I'P
. ruMa re
. x [),agnm x .
'SlcIcaaIa
1:0...
SJoin
eMerge
i1H
i1
.1JsI
LslFW1Ctionll
le.-
__ " ..
-
Figure lQ.9
A string variable called Previous is defined and initialized using the and variable activities in
the upper-Ieft comer. When a button is pressed in the a notification is sent to three
different activities. The first activity to take action is the variable activity, which gets the value of the
variable and sends it to the Join activity connected to its output.
This is the first time we've used a Join activity. Its function is very simple. It waits for an input message
:0
on both of its input pins and then combines the messages into a single message and sends it on its output
pino In Figure 10-9, when the Join activity receives the output from the Variable activity and the
notification from the it combines these two messages into one and sends it to the
Calculate activity, which performs arithmetic, logical, or string operations on its input vaIues
according to the expression entered in the activity. These operations are shown the following table:
Type of Operation Operation
Arithmetic +, -,', / and % for modulo
LogicaI &&, lI,and!
The plus operator (+) can aIso be used to concatenate strings. Parentheses can be used to group operations.
The operation defined in the Calculate activity in Figure 10-9 is Previous: + msgO. Previous +
New: + msg. Name. This builds a string that contains literaIs combined with the string values of msgO
. Previous and msg . Name. The message is displayed using the SimpleDialog activity.
481
Part 111: Visual Programming Language
AH that remains is to update the value of the Previous variable. This is done with the Join activity on
the bottom row. It waits until the string has been built and then combines this message with the original
notification message from the Direct ionDialog activity. The Calculate activity extracts the Narne
string from the original DirectionDialog notification and passes it to a variable activity to be stored.
The Join at the bottom of the diagram is necessary because you must be certain that the string has been
constructed before you change the value of the variable. Without this Join, there is a race condition
between constructing the string and updating the variable that can cause unpredictable results.
Run the diagram and notice that the message displayed contains both the current button press as well as
the previous button press.
Looping and Conditionals in VPL
No language is complete without the ability to make logical decisions and iterate through loops. In an
imperative language, you use an lE statement to make a decision and a For or a While statement to
iterate. In VPL, decisions are made with an rE activity, and iteration is done using a data flow loop.
You might expect to find a basic ForLoop activity in the Basic Activities toolbox, but it isn't there. That's
because a ForLoop cannot usually be implemented in VPL with r single activity box. As you will see in th
next few examples, you must take special care to ensure that the ForLoop executes in the proper order.
The diagram in Figure 10-10 shows how a simple ForLoop can be implemented in VPL. You can find it
in the ChapterlD directory under "5-Loops."
i
".' ; , " ; ~ ' '2" no;."'. f
i
I
~
J I
Figure 1.0-1.0
482
;
\. .J
Pnject "
~ ,-[kq3ms
. ~ CcY"I.-"qw-A--ns
Proponlos "
R"" HeIp
Serrices .. x
sp<o<h
Figure 10-11
9 Al Found
'.fol!owet
I .SR.Not30
"SRSAPl
, .SRSAPl_UI
SR Semanllc W1lh VI
.SRNe'30....,,VI
i ,(Toxt!Xl Speech (TTS)
l
~ AetMIle$
, .....ActMly
i lI!Vanable
I
' : ~ ' -
8""""
' .Me<9O
u
s",Ol:h
IIIII.JsI
L
A diagram is inactive until a message enters it. The message can originate from a notfication on an
activity or from a message that is injected into the inputs of a top-level Data activity. As long as a
message is actively propagating in the diagram, VPL continues its execution.
This diagrarn adds a Join activity after the Variable activity where the new Start variable value i:
saved. The Join activity will wait until the TexttoSpeechTTS activity has completed saying the
previous phrase before passing an output message to the Calculate activity in the lower-right coml
This keeps the rest of the loop executing at the same speed as the TexttoSpeechTTS activity and
prevents multiple SayText messages from being queued at the TexttoSpeechTTS input.
The 6-Loop (in order) diagram shown in Figure 10-11 provides a good opportunity to discuss the wa}
which VPL executes a diagram. lt helps to understand how VPL evaluates activities and propagates
messages when debugging a diagram.
You can see how VPL evaluates a diagram by manually tracing messages through the diagram. For fu
diagrarn shown in Figure 10-11, the diagram is inactive until VPL injects an input message into each o
the upper-left Data activities. Because two messages are no\\' active, VPL schedules a parallel thread (
execution to evaluate each of them. One message propagates through the topmost Da ta activity and i
output message propagates to the topmost Variable activity. It sets the value of the Start variable a
Part 111: Visual Programming Language
The VPL Execution Model
484
Part 111: Visual Programming Language
: Diagram Sta,.,
j fns1 cm-ce program.activity.Oiagrnm
St.ill't
=-"d
Figure 10-12
U Current Node: The next section is a graphical representation of the diagram, much lile the o'
shown in VPL. The difference is that this diagram is annotated to show the currently executiJ
activity, activities that have been scheduled for execution, and breakpoints. As shown in
Figure 10-13 (without the color), the currently executing activity is outlined with bright red,
while other activities that are scheduled for execution are outlined with dark red. A red circlf
shown next to activities that have a breakpoint seto
CUlTent Ilode
Node: p<ogram ac\l"lY Slart setO

..
Next Node lo Execule
Outlined in Red wilh Ihe
play icon displayed
This node has a
breakpoinl sel
indicaled by Ihe
! !
red circle.
l!!t!
-e
Tr;:oo

Figure 10-13
lf the button on the active activity is clicked, VPL will step to the next activity. This can al50
accomplished by pressing the 5tep button at the top of this section. The other two buttons c
used to ron the diagram at slO\'I;' speed or regular speed. The slow-speed execution is usefu]
Vtrace through large diagrams without having to continually press the 5tep button.
486
Chapter 10: Microsoft Visual Programming Language Basics
At the bottom of this section, the value of the message on the input pin of the CUITent activity is
shown.
o Breakpoints: The next section shows the currently set breakpoints, as shown in Figure 10-14. If a
breakpoint has been set on an activity, execution will stop when it becomes the active activity.
Breakpoints can be cleared, enabled, and disabled in this section.
Figure 10-14
o Pending Nodes: The fourth section shows alI activities scheduled to be executed, as shown in
Figure 10-15. As described in the previous section, multiple activities can be executing at the
same time on multiple threads. A breakpoint can be set on any of the scheduled activities by
pressing the corresponding SetBP button. .
.s
PendlngN_
vaiu. 72 Syst.m.fntJ2
Figure 10-15
The diagram can be terminated by pressing the Stop button on the Run dialog, just as when the
diagram is not running in debugger mode.
Creating Custom Activities
As shown in Figure 10-11, simple functions can be composed of many different activity blocks.
Real-world diagrams can quick1y become unmanageable. Fortunately, VPL enables custom activities to
be defined that are similar to subroutines in imperative languages.
The ForLoop function defined in Figure 10-11 is a good candidate to become a cu.stom activity because it
is a function that might be used multiple times in a diagram and it is self-eontained. This section starts
by showing you how to define a cu.stom activity to mplement a ForLoop. Later you will improve that
be
cu.stom activity to make the ForLoop execute in order.
mbe
to
487
.
Part 111: Visual Programming Language
Defining a ForLoop Custom Acfivity
Defining a custom activity is very similar to defining a diagram except that the input and output pins
must be defined and connected. The following steps show how to define a custom activity that
implements the ForLoop functionality. You can see the final result in the 7-CustomActivity project in
ChapterlO directory.
1. 5tart out with a new project by clicking File Q New.
2. Drag an Acti vi ty block from the Basic Activities toolbox.
3. Give the activity a name such as ForLoop by typing it in the Name: box in the Properties
toolbox. Give it a friendly name and a description as wel!.
4. Double-click the ForLoop activity to open its diagram. The diagram page looks similar to
top-level diagram except that now input and output pns are present.
5. Define the actions that this activity wiII support by clicking Edit Q Actions and Notifications.
The Actions and Notifications dialog is displayed.
6. Add a new action by pressing the Add button in the Actions column. Name the action by ty:
Initialize in the box. Add two input values by pressing the Add button in the Input values
column. Name the input values StartValue and EndValue and make them both of type in
A properly configured dialog is shown in Figure 1O-i,6.
. 'Gl
(

__
Qestnplion
fnita1lZe
IYI>e Iype
mI
11 1[Qelete) I 1!le!elc Add 11f)e!eI!)
... .. _--_...." .. _.. ....._.. _.. ....

Figure 10-16
488
Part 111: Visual Programming Language
1'__
- x orl.oopx,' , . I"r;>jo<;_ .x.

1"'-'
IlIISv..-
.:.1
,
I\<kn -- .. I) Confiy.r
IliIc.k<k4e



! ""Yo


.,_T.......

., Cornmon DSS T
';'!ln<"'" llGog
.. [}.nl<bQn o..:og (VE
oExlio<e<
OEx,>lwSm
"Ii1Tednr::Ac:telera

! ..HoTecIn<
-RoboeCre:aaoSc'

l!:L .. .,,,,'
Figure 1().18
10. Select the main diagrarn tab. Add actions to the diagrarn to match Figure 10-19. The two Data
activities arecombined into a single messagewith the Join activity and sent to the Initialize
action on the ForLoop activity. Copy and Paste the ForLoop activity to create another instance of
it and connct its CountNo ti ficat ion output to the SayText action of the TextoSpeechTTS acti
J.J.,,tjI2 f (1M (11" ..
I . x.f%I!!!L"
1u ...-.
,ilil"""""""
SCbb '
1
3
_ \1;
.Mse ......
:,' : 1- __ .. -.
! Sonbs x EmV_ I

i

, ... ....." S,nd=>on (?
lFcrlDop r ; TEX1bSpaechTTS'
, ., 80b lrads' ;
s !I
t! &::b Trac.ta Ca'b". r
o

,
! lPlkectlcn uao: (VI'





e,""""
- Crea Su
J -RoboS Su

-!. -
1Loa:!ed
.
1'
v Cortf9.1
1
;
ij!..
_
P:;',:: Xc '
Nom<

F",
-
CMt:rpt>:::n &

1

Figure 1().19
490
Part 111: Visual Programming Language
The new Initialize action in the ForLoop activity is shown in Figure 10-21.
8QIc AclMtIos .. le
..-Adrolj
BVanabie
IiCakulato
tllJat3
3_
eMge


f<Xloop' x" ;
.. . _..... ,.. ..
r---------=---------------------.------------------1 .. Con!igural>cns
1 i .....
f
-x
i
i
R..... Il!
";:1 !
IIlJsI
-- !
5erYices ... )( i i
i
-_!

ftl!
i
]1
I
I
". J'!!!t.
I"elemnl h.>s na ve""';
/ Ej
I

,,1
1
!
i
I

I
I
Figure 10-21
You can specify multiple actions in an activity by creating them in the Actions and Notification
dialog. You then specify inputs and outputs for each action. The Action: drop-down menu at the top
of the diagram enables you to select the action you are working with. Each action is independent from
aH the others except that the)' all refer to the same state variables.
In the Initialize action, the StartValue and EndValue parts of the input message are separdted and
stored in their respective state variables. When both values have been stored, a message is sent to the
result pin to indicate that the operation has completed. You may have noticed that the ForLoop activity
appears in its own action definition. This is caBed recursion. It is perfectly legal to pass a message from
one action to the input of another action by referring to the activty in this way. Simply use the Edit
menu to copy the ForLoop activity from the main diagram and then paste it into this diagram. The
output from the Join activty passes a message to the Count action on the ForLoop activity. The
definition for this action is shown in Figure 10-22.
492
Chapter 10: Microsoft Visual Programming Language Basics
fIo ll- lluId 8IID HoIP
Llgjtl-t-:* Q.11;-v; 4-
4
.1,t __ ,":I ... __ ._.< __ ..
f--] ------R.-,...-J
I I
al..isl :0.
..I !
,._Bunpet .. l
:::::. '. Cc"-,lifica_ 1 .
:eAlomSyrdcaDon <: Jemenl has rKI p:cpi'rt{
:.Alom SyrdcaDon G
,.BlobTracl<... l' ..
:.BlobT_e
,,-.ecoBASIC so.
I I
,"_ Genoric Mo
.. ==:::..=...::=.=....=....."' .. _"'.=_::=...::: .. ===,===========::.I
..
'
"
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 irnmediately 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 Li s t activities, the Lis t
Functions activities, and the Switch activities.
The swi tch activity is much Iike the 1 f activity. Instead oE conditions, the Swi tch activity expects data
values to be specified, Iike case statements associated with a switch statement in an imperative Ianguage.
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 Swi tch activity is usefuI 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 Swi tch activity represent
493
Part 111: Visual Programming Language
various possible states, and the action that the sta te 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 icono AH 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 desred
list type and use the Set and Get actions on the Variable action to set and retrieve the listo
The List Functions activity perforros one DE several possible operations on a listo lts inputs and
outputs depend on the function that is selected from the drop-down menu on the bottom of the List
Functions activity icono The possible functions are listed in the following table:
Function Inputs
Append
Concatenate
Reverse
Sort
Rernoveltem
InsertItem
Getlndex
List: A list
ltem: A data itero of the sarne type as the listo The item on the
ltem input is appended to the eng of the list and the
resulting list is present on the output pino
List!: A list
Listl: A list DE the same type
Listl is concatenated on the end of Listl and the resulting list
is present on the output pino
List: A listo A new list is constructed with the iteros in reverse
order from the input List. The new list is present on the
output pino
List: A listo A new list is constructed with the items froro the
input List sorted in ascending order.
List: A list
Index: An integer that represents the position of the item to
be removed. Index Orefers to the first itero in the list.
The resulting list is present on the output pino
List: A list
Item: A data itero DE the same type as the list
Index: An integer representing the position where the item is
to be inserted. Index Orefers to the first item in the list.
The resulting list is present on the output pino
List: A list
ltem: A data item of the same type as the listo lf the data itero
is present in the list an integer representing its position is
present on the output pino As with the other functions, index
Orefers to the frst item in the list.
494
Part 111: Visual Programming Language
where the val ue. Resul t string is placed on the input to the Swi tch activity. The Swi tch activity
checks whether the input string is either "adj," "pluralnoun," or "profession." If it matches any of those
cases, it replaces that \\'ord 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 Herge activity. If
none of these keywords is rnatched, the string is passed unmodified to the HERGE.
The updated pillase is passed to a Calculate activity that concatenates the current Resul t with a space
and the value of the pillase. The result is stored in the Resul t variable and a message is passed back to
the ForLoop activity telling it to generate another CountNotif ication.
After all of the pillases in the Phrases activity have been processed, the ForLoop sends an
EndNotification rnessage to the Variable activity at the bottorn of the diagram. The value of the
Resul t variable is retrieved and sent to an AlertDialog as well as the Textt.oSpeechTTS activity.
The source text was taken frorn 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 prograrnmers.
Sorne of the words in the text were replaced with one of the three keywords described aboye:
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 prograrnming 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 diagrarn is executed, a new paragraph is generated with different word substitutions. Co
ahead and run the diagrarn a few times to see and hear its output.
The PluralNouns Activity
The PluralNouns, Adject.ives, and Professions activities are essentially identical to each other
except that they rnaintain different lists. The Ini tiali ze action of the pluralNouns activity is shown
in Figure 10-24.
496
497
Al

1
1
1
I
J
._..
B A11'ound'
]
lIIAttos Con>
lIIAttosOrive
._5yncIution c:
._Syndi<atIon c:
BIob Trzker
BIob Trxker CaIiOC
... __BASlC Sla
'"lIoe-Bat Genenc C<
.A lIoe-Bat Genenc 1Jr
'"lIoe-Bat Genenc Mo
e..-oss Tes!
.Corcbat
Figure 10-24
...
. .. l'kriNouns x x_xPln<es)l Fulocp x
......1Mly lIdat .........
IIIIv_ '
liCa!wlalo
"Dato
S Jan
eMerge

iiSwil<h
IIIIUst
-"
Chapter 10: Microsoft Visual Programming Language Basics
The Lst activty in the upper right builds a new Iist and passes it to the first Lis t Functons activity
when a message is received on the input pino The first Data activity also generates a single string of data
and passes it to the first Lst Functons activity, which then adds it to the end of the list. Subsequent
Lst Functons and Data activities are then executed untillO plural nouns have been added to the listo
At that point, the list is stored to the Pl uralNouns variable associated with this activty and a response
message is sent to the output pino The In talize actions are nearly identical for the Adj ecti ves and
Professons activities.
The Phrases activity passes the number of items in its Iist as an output to be used by the main diagram.
Figure 10-25 shows the Ini talze action of the Phrases activity. Notice how the source text has been
broken up into dscrete phrases so that the keywords are isolated and can be replaced before the output
text is reconstructed.
The Phrases Activity
Part 111: Visual Programming Language
-';";':;"'c,*,i"C"'-0*",V::"":':%-'W,,",-,,-F"'''/W!ii'"i
Roo Edil \IIow _ !lID Holp
!
ijiii.i .. x.
,,",,' AcID1 fIrt
av"".,..

I!I:.: =OJ:b
3
.....-;.
!-s [_.__.
o
\ s-.
.
1m....'
, Serric:r.I
&:. _. __
- :3
1'Hc"'_

'1
l1li
""'" Con>
. - ... Ar-';:Q$ On...e
,
""""51--'<:
1 ",=s.--.<:
.
j... ERob Tr.Kter
[;- SiJ
l
'E"
. .
."' __Bol"""""'''
Ha

_
Figure 10-25
The GetRandom Action
The PluralNouns, Adj ectives, and Professions activities support a GetRandom action that chooses
a random element from each of their respective lists and places it on the output pino Figure 10-26 shows
the GetRandom action from the PluralNouns activity.
"':,'!W:
j .... Edil __ """" Ruo ......

I BaKA<flomjn
ivktNt( kton .... '"


-t
/a
l ....,..
ff
S-O
1Iln!
I s.n<o=

$


j i."':. 6oe-6cA. Gt1-er,o;:

t
l':'C<n<d>_ -- -_._

! '"o "'0
,
:l M.::J::s &..::7'.:;.Er
1l1li""'" Ca<
Figure 10-26
498
Part 111: Visual Programming Language
This diagram is guaranteed to produce endless hours of entertainment for you and your coworkersr 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

Das könnte Ihnen auch gefallen