Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
QueuedMessageHandlerTemplatedocumentation
PublishDate:Jan16,2017
Overview
TheQueuedMessageHandler(QMH)templatefacilitatesmultiplesectionsofcoderunninginparallelandsendingdata
betweenthem.Eachsectionofcoderepresentsatask,suchasacquiringdata,andisdesignedsimilarlytoastatemachine.
Becauseofthisdesign,youcandivideeachtaskintostates.
TableofContents
1.Example
2.DeveloperWalkthrough
3.SystemRequirements
4.UseCases
5.Overview
6.RunningThisTemplate
7.ModifyingthisTemplate
8.ImportantInformation
TheQMHtemplateisaversionoftheProducer/Consumerdesignpattern,wheretheuserinterface(producer)produces
messagesandthetasks(consumers)consumethem.However,intheQMHtemplate,youalsocanproducemessages
fromaconsumerloop.
Thistemplateincludesoneproducerloopandoneconsumerloop.Youcanaddconsumerloopsasneeded.
1.Example
RefertotheContinuousMeasurementandLoggingsampleproject(http://www.ni.com/whitepaper/14116/en),available
fromtheCreateProjectdialogbox,foranexampleofadaptingthistemplatetoameasurementapplication.
2.DeveloperWalkthrough
Seeadeveloperwalkthrough(http://zone.ni.com/wv/app/doc/p/id/wv3381)oftheQueuedMessageHandlertemplate.
3.SystemRequirements
LabVIEWBase,Full,orProfessionalDevelopmentSystem
4.UseCases
TheQMHtemplateisusefulforapplicationswheremultipletasksoccurinparallel,oftenatdifferentrates.Forexample,
consideranapplicationthatcontinuouslyacquires,logs,anddisplaystwosignals:anRS232signalandananalog
signal.Thesesignalsoccuratdifferentrates,sotheapplicationmusthavetwoloopsthatruninparallel.Inaddition,
eachloopisdividedintothefollowingstates:
Initializethedataacquisitionhardware
Acquiredata
Logtheacquireddatatodisk
Displaytheacquireddatainawaveformchart
Setthehardwaretoasafestate
Stopthedataacquisitionandshutdownthehardware
Theapplicationrequiresaresponsiveuserinterfacethatis,usersshouldbeabletoclickbuttonsevenwhilethe
applicationisexecutinganothercommand.Therefore,theapplicationrequiresathirdparallelloopthatcontinuously
monitorsthefrontpanelforevents,suchasthefollowingcommands:
StartRS232acquisition
StopRS232acquisition
EnableRS232logging
DisableRS232logging
Startanalogdataacquisition
Stopanalogdataacquisition
Enableanalogdatalogging
Disableanalogdatalogging
TheQMHtemplateprovidesastartingpointforwritingthiskindofapplication.
5.Overview
http://www.ni.com/tutorial/53391/en/ 1/7
5/4/2017 QueuedMessageHandlerTemplatedocumentationNationalInstruments
Thistemplaterepeatedlyexecutesthefollowingsteps:
1.Auserinteractswiththefrontpanel,causingtheEventstructureintheEventHandlingLoop(EHL)toproducea
message.LabVIEWstoresthemessageinaqueue.
2.TheMessageHandlingLoop(MHL)readsamessagefromthemessagequeue,removingthemessage.
3.ThemessageisastringthatmatchesoneofthesubdiagramsoftheCasestructureintheMHL.Therefore,reading
themessagecausesthecorrespondingsubdiagramoftheCasestructuretoexecute.Thissubdiagramiscalleda
messagediagrambecauseitcorrespondstoamessage.
4.Optionally,themessagediagramproducesanothermessage,storingitinthemessagequeue.
Notes:
TheEHListheproducerloop.TheMHListheconsumerloop.Theseloopsruninparallelandareconnectedbythe
messagequeue,whichfacilitatescommunicationbetweentheloops.
ThemessagequeueisaLabVIEWqueuethatstoresmessagesforconsumption.BecausetheEHLsendsmessages
tothisqueueandnotdirectlytotheMHL,theEHLcanproducemessageswhiletheMHLisnotconsumingthem.
EachmessagequeuebelongstoasingleMHL.
EveryiterationoftheMHLreadstheoldestmessageinthemessagequeueandthenexecutesthecorresponding
messagediagram.AlthoughtheMHLprimarilyconsumesmessages,italsocanproducethem.
YourapplicationcanhavemultipleMHLs.EachMHLcorrespondstoatasktheapplicationperforms,suchas
acquiringorloggingdata.
NoticetheUIDataclusterintheabovediagram.ThisclusterisdatathateachmessagediagraminanMHLcan
accessandmodify.Inthistemplate,theclusterisdefinedasatypedef,UIData.ctl.Eachtypedefbelongstoasingle
MHL.
6.RunningThisTemplate
1.IntheProjectExplorerwindow,openandrunMain.vi.
2.ClickthefrontpanelcontrolsandwatchtheDisplayindicatordisplaymessages.
7.ModifyingthisTemplate
DeterminingYourNeeds
Thefollowingtablesummarizesthedesigndecisionsyoumustmakewhenmodifyingthistemplate:
http://www.ni.com/tutorial/53391/en/ 2/7
5/4/2017 QueuedMessageHandlerTemplatedocumentationNationalInstruments
Youmustdeterminewhatdatathemessaged Eachmessagediagramofthedataacqui DefiningDatathataMessa
iagramsofanMHLneed. sitionMHLneedsaccesstoahardwarer geHandlingLoopNeeds
eference.TheInitializemessagediagra
mneedstoopenthisreference,theAcq
uireDatadiagramusesthisreferenceto
acquiredata,andtheExitmessagediagr
amclosesthereference.
LabVIEWlaunchestheControlEditorwindow.
3.ExpandtheborderoftheMessageQueuescluster.
4.DuplicatetheUIqueuerefnuminthecluster.
5.Namethenewqueuerefnum.Forexample:
6.SelectFileApplyChangesandclosetheControlEditorwindow.TheMessageQueuestypedefnowcontains
anadditionalmessagequeue.
2.ModifyCreateAllMessageQueues.vitoexecutethefollowingsteps:
Obtainthemessagequeuereference
BundlethisqueueintotheMessageQueuesoutcluster
(Optional)SendaninitialmessagetothenewMHL
Thefollowingscreenshotshowsanexampleofcodethataccomplishestheabovesteps:
http://www.ni.com/tutorial/53391/en/ 3/7
5/4/2017 QueuedMessageHandlerTemplatedocumentationNationalInstruments
3.(Optional)IftheMHLneedsaccesstodata,createatypedefthatrepresentsthisdata.
4.InMain.vi,createtheMessageHandlingLoopthatrepresentsthetask:
Notes:
1.Recallthatinstep2,youbundledtheNewTaskqueuerefnumintotheMessageQueuesoutcluster.Thecode
aboveshowswherethisclusterisunbundledandhowthewirebranchfortheNewTaskqueuegoestotheNew
TaskMHL.
2.Recallthatinstep2,youhadtheoptiontosendaninitialmessagetothemessagequeue.Thecodeinstep2
showstheinitialmessageInitialize.Thecodeaboveshowsthemessagediagram(Initialize)thatexecuteswhen
thismessageisreceived.
3.Recallthatinstep4,youhadtheoptiontocreateatypedef.Thecodeaboveshowshowyouwirethistypedef,
NewTaskData,sotheMHLcanuseit.
4.IfyouwantthenewtasktosendmessagestotheUIqueue,branchthewirefortheUIqueuerefnumintotheNew
Taskloop.
5.ThecodeaboveshowstheFALSEconstantwiredtotheconditionalterminaloftheWhileLoop.IneachMHL,only
onemessagediagramshouldbeabletostoptheMHL.Thisdesignpreventsaccidentalandpartialshutdownsby
guaranteeingthefollowingconditions:
ShutdowncoderunsonlyrightbeforetheMHLshutsdown.
Shutdowncodealwaysrunstocompletion.
6.TokeeptheblockdiagramofMain.vicompactandreadable,youcanencapsulateeachMHLintoasubVI.To
furtherorganizetheproject,youcanputeachsubVI,anysupportingVIs,anditsdatatypedefintoaprojectlibrary.
RefertotheContinuousMeasurementandLogging(http://www.ni.com/whitepaper/14116/en)sampleproject,
availablefromtheCreateProjectdialogbox,foranexampleofthisdesign.
7.TheMHLshownabovedoesnotneedaccesstotheStopEventwire.TheMHLinthetemplateusesthiswireto
executetheFireUserEventStopVI,whichshutsdowntheEventHandlingLoop.NootherMHLneedstodo
this.
5.AddmessagediagramstotheCasestructureintheMHL.Tominimizeerrorsandunexpectedbehavior,ensureeach
MHLhasthefollowingmessagediagrams:
1.Amessagediagramthatinitializesthetaskforexample,thisdiagramcouldconnecttoahardwaredevice,open
filesfordatalogging,andsoon.
2.Amessagediagramthathandlesunrecognizedmessages.
3.Amessagediagramthat,whenexecuted,releasesthemessagequeueandstopstheloop.Forexample:
Bydefault,themessagethattriggersthismessagediagramisExit,butyoucanchangethis.
4.(Optional)IftheapplicationrequiresthattheMHLstopperformingitstaskbutstayactive(topotentiallyrestartthe
task),createamessagediagramthatusestheFlushQueuefunctiontoremoveanypendingmessages.
Forexample,inacontinuousmeasurementapplication,youmayhaveStartMeasurementandStop
Measurementbuttons.ClickingStartMeasurementinitiatestheMHL,whichcontinuesexecutionbysending
itselfthesamemessagecontinually.Inthisapplication,clickingStopMeasurementshouldnotonlystopthe
measurementbutalsoflushthemessagequeuewithoutstoppingtheMHL.Ifyoudonotflushthemessage
queue,clickingStopMeasurementwillhavenoeffect.Themessagequeuecontainsmoremessagestocontinue
themeasurement,andeachofthesemessagescausesanothermessageofitskindtobeproduced.
6.AddcodetotheEHLthatinstructsthenewMHLtostopintheeventofanerrororwhentheapplicationstopsthatis,
executethemessagediagramyoucreatedinstep5c.AddthiscodetotheEventStructureandErrorcaseshownin
thefollowingfigure:
http://www.ni.com/tutorial/53391/en/ 4/7
5/4/2017 QueuedMessageHandlerTemplatedocumentationNationalInstruments
7.SendmessagestotheMHL.
CreatingaMessageDiagram
AmessagediagramisthesubdiagramofaCasestructure,locatedinaMessageHandlingLoop,thathandlesa
particularmessage.Itissimilartoastateinastatemachine.
AmessagediagramisasubdiagramofaCasestructurethatislabeledwithastring.ItexecuteswhentheMHLreceives
amessagethatmatchesthislabel.
Completethefollowingstepstocreateamessagediagram:
1.IntheMHLthatrepresentsthetask,addasubdiagramtotheCasestructure.
TipIfyouareaddingamessagediagramtotheMHLincludedinthetemplate,youcanautomaticallyincludethedat
aanderrorwiresinthenewmessagediagrambyduplicatingtheCopyThisFramecase.
2.Inthecaseselectorlabel,enterthetextofthemessagethatwilltriggerthismessagediagramtoexecute.For
example,thefollowingmessagediagramexecuteswhenLabVIEWreadsNewMessagefromthemessagequeue:
3.Addcodethatexecutesuponreceivingthismessage.Asyoudothis,payattentiontothefollowingguidelines:
Toaccessandmodifytaskdata,usetheUnbundleByNameandBundleByNamefunctions:
Toensurethatyoutrackallerrors,usetheMergeErrorsfunctiontomergeerrorscomingfromallnodesinthe
subdiagram.
Toaccessmessagedata,wiretheMessageDatainputtunneltoaVarianttoDatafunction:
Tosendamessagetoamessagequeue,usetheEnqueueMessageVI.
4.Toexecutethemessagediagram,sendamessagetotheMHL.Themessageyousendmustmatchthelabelofthe
messagediagramthatyouenteredinstep2.
DefiningDatathataMessageHandlingLoopNeeds
Inthetemplate,UIData.ctlisthetypdefthatdefinestheclusterofdatathattheMHLcanaccess:
Modifythistypedefaccordingtheneedsofyourapplication.Forexample,ifmorethanonemessagediagraminanMHL
needstomodifythesameBooleancontrol,addaBooleancontroltothistypdef.
IfyouhavemorethanoneMHL,createatypedefforeachone.ThisdesignpreventserrorsbyensuringoneMHLcannot
accessthedataofanother.
AddingaControlthatSendsaMessagetoaMessageHandlingLoop
1.Addacontroltothefrontpanel.
2.(Optional)Ifyouwantamessagediagramtoprogrammaticallymodifythiscontrol,bundlethecontrolrefnumintothe
typedefforthatMHL.
3.AddanEventcasetotheEventstructureintheEventHandlingLoop.
4.Configuretheeventtotriggerwhenthevalueofthisnewbuttonchanges:
5.ClickOK.LabVIEWcreatesaneventcaseintheEventstructure.
http://www.ni.com/tutorial/53391/en/ 5/7
5/4/2017 QueuedMessageHandlerTemplatedocumentationNationalInstruments
5.ClickOK.LabVIEWcreatesaneventcaseintheEventstructure.
6.Associatetheterminalwiththeeventbydraggingtheblockdiagramterminalforthenewcontrolinsidethisevent
case.
7.AddcodetothiseventcasethatsendsamessagetoanMHL.
SendingaMessagetoaMessageHandlingLoop
MessagesarestringsthatinstructanMHLtoexecuteoneofitsmessagediagrams.MessagesareproducedbytheEHL
andarestoredinthemessagequeue.EveryiterationoftheMHLreadstheoldestmessageinthemessagequeueand
executesthecorrespondingmessagediagram.
CompletethefollowingstepstosendamessagetoanMHL:
1.DecidewhatpartoftheapplicationwillsendthemessageandwhichMHLwillreceivethemessage.Youcansend
messagesfromtheEHLorfromamessagediagram.
2.DecidewhatmessagediagramwillexecutewhentheMHLreceivesthismessage.Ensurethemessagediagram
existsandhasthesamenameasthemessageyouwanttosend.Ifthemessagediagramdoesnotexist,createit.
3.InMain.vi,accessthewirethatrepresentsthemessagequeueofthereceivingMHL.Youaccessthiswireby
unbundlingitfromtheMessageQueuesoutclusterthatisreturnedfromtheCreateAllMessageQueuesVI.Main.vi
alreadycontainsthefollowingcodethatunbundlestheUIqueuerefnum:
ExpandthisUnbundlebyNamefunctiontoaccessthewiresofmessagequeuesforallMHLs.
4.Inthepartoftheapplicationthatwillsendthemessage,createthefollowingcode:
Inthecodeabove,Messageisthetextthatmatchesthemessagediagramyouidentifiedinstep2,andthemessage
queuerefnumisthewireyouidentifiedinstep3.
NoteAccesstheEnqueueMessageVIfromtheProjectExplorerwindowofthetemplateorbyusingQuickDro
p.
5.(Optional)Tospecifythatthismessagesupersedesothersalreadyinthequeue,wireTRUEtothePriority
Message?inputoftheEnqueueMessageVI:
Highprioritymessagesaretypicallyreservedforemergencystopsituations.Thesemessagesareplacedatthefront
ofthemessagequeue,guaranteeingthatthereceivingMHLwillconsumethatmessagenext.
6.(Optional)Tosenddatawiththemessage,wireavaluetotheMessageDatainputoftheEnqueueMessageVI.This
terminalcanacceptanydatatype.Forexample,thefollowingcodesendsadoubleprecisionfloatingpointnumber
alongwiththemessage:
LabVIEWdisplaysacoerciondotontheinputterminalbecausethedatatypeofthisterminalisvariant.
ChangingtheMessagethatStopsaMessageHandlingLoop
Messagesarestrings,meaningyoucancreateorchangeamessagewithoutmodifyingatypedef.However,this
templatedefinesonemessage:theExitmessageisdefinedinMessageQueue.lvlib:DequeueMessage.vi:
IfyouwantyourMHLstoshutdownonamessageotherthanExit,changethemessageinthisVI.
HandlingUnrecognizedMessages
EnsureallCasestructuresinanMHLhaveaDefaultmessagediagram.Thecodeinthismessagediagramexecutes
whentheMHLreadsamessagethatdoesnothaveacorrespondingmessagediagram.HavingaDefaultmessage
diagramisimportantbecausemessagesarestringsthatyouenterwhileprogramming,notvaluesyouselectfroman
enum.
IgnoringErrorswhenReadingfromtheMessageQueue
1.IntheProjectExplorerwindow,openMessageQueue.lvlib:DequeueMessage.vianddisplaytheblockdiagram.
2.FindtheCasestructurenestedinsidetheErrorcase:
http://www.ni.com/tutorial/53391/en/ 6/7
5/4/2017 QueuedMessageHandlerTemplatedocumentationNationalInstruments
Toignoreerrorswhenreadingfromthemessagequeue,adderrorcodestothecaseselectorlabelofthenestedCase
structure.Theerrorstoignoredependyourapplication.Forexample,ifyouarereadingthequeueoveranetwork,you
mightwanttoignoretimeouterrors.
EnablingaMessageHandlingLooptoProgrammaticallyModifyControlsandIndicators
ToenableanMHLtomodifyacontrolprogrammatically,createarefnumforthecontrolandbundleitintothetypedef
thatstoresdataforthatMHL.ThefollowingprocedureusesUIData.ctlasanexample.
1.CreatethecontrolrefnumandmoveitintotheInitializesubdiagramoftheMHL.
2.OpenUIData.ctlandaddspacefortherefnumtothecluster.
3.IntheInitializesubdiagram,expandthisnewterminalontheBundlebyNamefunctionandwirethecontrolrefnumto
it:
TherefnumforthiscontrolnowisavailabletoanymessagediagramthathasaccesstoUIData.ctl.Forexample,the
followingcodeshowstheDisableButtonmessagediagram,whichusesthecontrolrefnumtodisableandgrayoutthe
frontpanelbutton:
8.ImportantInformation
Copyright
2012NationalInstruments.Allrightsreserved.
Underthecopyrightlaws,thispublicationmaynotbereproducedortransmittedinanyform,electronicormechanical,
includingphotocopying,recording,storinginaninformationretrievalsystem,ortranslating,inwholeorinpart,without
thepriorwrittenconsentofNationalInstrumentsCorporation.
NationalInstrumentsrespectstheintellectualpropertyofothers,andweaskouruserstodothesame.NIsoftwareis
protectedbycopyrightandotherintellectualpropertylaws.WhereNIsoftwaremaybeusedtoreproducesoftwareor
othermaterialsbelongingtoothers,youmayuseNIsoftwareonlytoreproducematerialsthatyoumayreproducein
accordancewiththetermsofanyapplicablelicenseorotherlegalrestriction.
EndUserLicenseAgreementsandThirdPartyLegalNotices
Youcanfindenduserlicenseagreements(EULAs)andthirdpartylegalnoticesinthefollowinglocations:
Noticesarelocatedinthe<NationalInstruments>\_LegalInformationand<NationalInstruments>directories.
EULAsarelocatedinthe<NationalInstruments>\Shared\MDF\Legal\licensedirectory.
Review<NationalInstruments>\_LegalInformation.txtforinformationonincludinglegalinformationininstallersbuilt
withNIproducts.
Trademarks
LabVIEW,NationalInstruments,NI,ni.com,theNationalInstrumentscorporatelogo,andtheEaglelogoaretrademarks
ofNationalInstrumentsCorporation.RefertotheTrademarkInformationatni.com/trademarks
(http://www.ni.com/trademarks)forotherNationalInstrumentstrademarks.
Otherproductandcompanynamesmentionedhereinaretrademarksortradenamesoftheirrespectivecompanies.
Patents
ForpatentscoveringtheNationalInstrumentsproducts/technology,refertotheappropriatelocation:HelpPatentsin
yoursoftware,thepatents.txtfileonyourmedia,ortheNationalInstrumentsPatentNoticeatni.com/patents
(http://www.ni.com/patents).
http://www.ni.com/tutorial/53391/en/ 7/7