12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102 |
- h1(#YAKINDUStatechartToolsReference). YAKINDU Statechart Tools Reference
- h2. Statechart elements
- This chapter describes the state chart elements of the YAKINDU SCT 2 editor. The meta model of the YAKINDU SCT 2 is the model of finite state machines. It is based on the view of a system that is defined by a finite number of states. The behavior of such a system is based on its active states. These states are determined by the history of the state machine. Very important are the theoretical models for state machines by Mealy and Moore. Mealy state machines associate actions with transitions. Moore machines associate actions with states (entry, exit). YAKINDU SCT 2 can model both these types.
- The YAKINDU SCT 2 meta model is designed similar to the UML statechart meta model with the following differences:
- * SCT statecharts are self-contained with interfaces defined by events and variables.
- * Core execution semantics are cycle-driven, not event-driven.
- ** This allows to process concurrent events.
- ** Event-driven behavior can be defined on top.
- * Time is an abstract concept for statecharts.
- * Time control is delegated to the environment.
- The model interpreter and different flavors of generated code are following these same core semantics.
- Please refer to the Wikipedia article "UML state machine":http://en.wikipedia.org/wiki/UML_state_machine for more details.
- h3(#Regions). Regions
- As already mentioned, the YAKINDU statecharts are self-contained. They are organized in regions. Due to this it is possible to organize multiple state machines in different regions and to run them concurrently.
- !images/parallelRegions.jpg(Parallel regions)!
- h3(#States). States
- States are the central elements of a state machine. A state has to be placed inside a region and must have a name that is unique inside this region. During simulation, each state can be active or passive. An active state has actions that are accomplished. Either an action is carried out on entering a state, during active state, or on exit.
- h3(#Transitions). Transitions
- A transition is the transfer of one state to another. Transitions are diagrammed as arrows. They can have events and actions, but don't need to.
- The syntax of events and actions is defined by a "textual description language":#Statechartdescriptionlanguage. Please refer to section "Events":#Events of this documentation for more details! For more details on actions please see chapter "Actions":#ReactionTriggers.
- If a state has more than a single outgoing transition without event, then among those transitions the one that has been modeled first will be carried out.
- h3(#Initialstateandfinalstate). Initial state and final state
- Initial and final states are pseudo states, because the statechart does not rely on them. Pseudo states express characteristics that are impossible to express by simple states.
- The initial state is always the first state that becomes active during interpretation or simulation of the state machine. An initial state can have only one outgoing transition and has no incoming ones. Its outgoing transition has no events or actions.
- Within a region, only a single initial state is allowed, but each region may have its own initial state.
- h3(#Choice). Choice
- A choice is also a pseudo state. It can be used to model a conditional path. A choice node divides a transition into multiple parts.
- Usually the first transition points towards the choice node. One of the choice's outgoing transitions can carry a condition.
- h3(#CompositeState). Composite states
- A composite state is a state comprising one or more state machines. These state machines are also organized in regions within the composite state.
- Besides the simple composite state YAKINDU SCT knows about two kinds of composite states: orthogonal states and submachine states.
- Composite states contain other state machine branches.
- h4(#Orthogonalstates). Orthogonal states
- In the context of state machines orthogonal states are states that are independent of each other. The presumably most famous example is the keyboard example:
- !images/orthogonalState_example.jpg(Orthogonal states)!
- h4(#Submachinestates). Subdiagrams
- When using composite states, a statechart model often becomes too big to give a comprehensive overview of the whole diagram. Although it is possible to collapse and expand a state's figure compartment, these actions would spoil the diagram layout each time they are executed. Subdiagrams come as a solution.
- !images/extract_subdiagram.png(Composite state)!
- When the _Extract Subdiagram_ refactoring is executed on a composite state, all containing regions are extracted into a separate diagram. A small decorator in the lower-right corner of the state indicates the existence of such a subdiagram. When you hover with the mouse cursor over this decorator, you'll see a small preview of the subdiagram's content. The refactoring also creates the required entry and exit points for you.
- !images/extract_subdiagram2.png(Subdiagram popup window)!
- A click on the decorator opens the subdiagram in a separate editor tab. The breadcrumb at the top allows easy navigation throughout the hierachy levels.
- !images/extract_subdiagram3.png(Subdiagram editor)!
- h3(#ShallowHistory). Shallow history
- The shallow history state is a pseudo state that is placed inside regions of composite states. It is used to remember the last active state inside a composite state. This makes it possible to jump back to the remembered state instead of starting at the inner initial state again.
- The following example, showing the answering of a questionaire, explains this:
- !images/shallowHistory01.jpg(Shallow history [1])!
- Particularly interesting in this statechart are the events _checkProgress_ and _goon_. The event _checkProgress_ jumps back to the *init* state while assigning the current progress count to the variable _temp_. The event _goon_ jumps to the shallow history state that was placed inside the composite state.
- !images/shallowHistory02.jpg(Shallow history [2])!
- !images/shallowHistory03.jpg(Shallow history [3])!
- When the _goon_ event is triggered, the most recent active state inside of the composite state *answeringQuestions* is activated again.
- h3(#DeepHistory). Deep history
- Deep history is similar to shallow history, but more complex. With a deep history the latest state of multiple nested states is remembered.
- h2(#Statechartdescriptionlanguage). Statechart description language
- A textual description language is used to declare and describe behaviors in a state machine. It is case sensitive.
- h3(#Typesystem). Type system
- The language has a small integrated type system consisting of the following simple types:
- * integer
- * real
- * boolean
- * string
- * void
- Events and variables can be declared using types:
- bc(prettyprint)..
- var intVar : integer
- var realVar : real
- var boolVar : boolean
- var stringVar : string
- event addInt : integer
- event addReal : real
- event checkValidity : boolean
- event stringEvent : string
- event voidEvent : void
- h3(#Expressions). Expressions
- Expressions in SCT are similar to expressions in other programming languages. The language provides operators for logical expressions, number arithmetic, bitwise arithmetic, and bit shifting.
- The type of a logical expression is *boolean*.
- h4(#LogicalAND). Logical AND
- bc(prettyprint)..
- var1 && var2
- h4(#LogicalOR). Logical OR
- bc(prettyprint)..
- var1 || var2
- h4(#LogicalNOT). Logical NOT
- bc(prettyprint)..
- !var1
- h4(#Conditionalexpression). Conditional expression
- bc(prettyprint)..
- var1 ? var2 : 23
- h4(#BitwiseXOR). Bitwise XOR
- bc(prettyprint)..
- var1 ^ var2
- h4(#BitwiseOR). Bitwise OR
- bc(prettyprint)..
- var1 | var2
- h4(#BitwiseAND). Bitwise AND
- bc(prettyprint)..
- var1 & var2
- h4(#LogicalRelationsandShiftOperators). Logical Relations and Shift Operators
- |less than | @<@ |
- |equal or less than | @<=@ |
- |greater than | @>@ |
- |equal or greater than | @>=@ |
- |equal | @==@ |
- |not equal | @!=@ |
- |shift left | @<<@ |
- |shift right | @>>@ |
- h4(#Binaryarithmeticoperators). Binary arithmetic operators
- |plus | @+@ |
- |minus | @-@ |
- |multiply | @*@ |
- |divide | @/@ |
- |modulo | @%@ |
- h4(#Unaryarithmeticoperators). Unary arithmetic operators
- |positive | @+@ |
- |negative | @-@ |
- |complement | @~@ |
- h3(#Statements). Statements
- A statement is one of three kinds:
- * assignment
- * event raising
- * operation call
- The language has the following assignment operators:
- </p><table><tr><td>simple assignment</td><td><code>=</code></td></tr><tr><td>multiply and assign</td><td><code>*=</code></td></tr><tr><td>divide and assign</td><td><code>/=</code></td></tr><tr><td>calculate modulo and assign</td><td><code>%=</code></td></tr><tr><td>add and assign</td><td><code>+=</code></td></tr><tr><td>subtract and assign</td><td><code>-=</code></td></tr><tr><td>bitshift left and assign</td><td><code><<=</code></td></tr><tr><td>bitshift right and assign</td><td><code>>>=</code></td></tr><tr><td>bitwise AND and assign</td><td><code>&=</code></td></tr><tr><td>bitwise XOR and assign</td><td><code>^=</code></td></tr><tr><td>bitwise OR and assign</td><td><code>|=</code></td></tr></table><p>
- ==<!-- FIXME: The following sentences are broken somehow. -->==
- An event is raised by calling a method whose name consists of the word _raise_ followed by the event name, e. g. _raiseIncoming_call()_, and if it is an interface event the name of the interface.
- An operation is called similar to other programming languages with the operation name and passing concrete parameters. The parameters can be expressions.
- h3(#Scopes). Scopes
- ==<!-- Start stext_keyword_namespace -->==
- h4(#Namespace). Namespace
- The language allows to define unique namespaces which can be used to qualify references to the statechart.
- bc(prettyprint)..
- namespace trafficlights
- p. ==<!-- End stext_keyword_namespace -->==
- ==<!-- Start stext_keyword_interface -->==
- h4(#interfacescope). Interface scope
- Declarations in the interface scope are externally visible. They can be shared within the environment.
- bc(prettyprint)..
- interface NamedInterface:
- in event event1
- out event event3 : integer
- var variable1 : integer
- p. ==<!-- End stext_keyword_interface -->==
- ==<!-- Start stext_keyword_internal -->==
- h4('internalscope). Internal scope
- Declarations made in an internal scope are visible to contained states only.
- bc(prettyprint)..
- internal:
- var localVariable1: integer
- event localEvent: integer
- local event localEvent2
- operation localOperation (int1 : integer, int2 : integer): integer
- localEvent2 / raise NamedInterface.event3 :
- localOperation(valueof(localEvent) , NamedInterface.variable1)
- p. ==<!-- End stext_keyword_internal -->==
- h3(#Declarations). Declarations
- Within scopes events, variables, operations, and local reactions can be declared.
- ==<!-- Start stext_keyword_event -->==
- h3(#Events). Events
- An event in an interface scope has a direction. It is either ingoing or outgoing:
- bc(prettyprint)..
- interface NamedInterface:
- in event event1
- out event event2
- p. An event in the local scope can carry variables:
- bc(prettyprint)..
- internal:
- event localEvent1 : integer
- p. A local event can have a value assignment:
- bc(prettyprint)..
- internal:
- event localEvent1: integer = 25
- p. ==<!-- End stext_keyword_event -->==
- ==<!-- Start stext_keyword_var -->==
- h3(#Variables). Variables
- Variables can have different visibilities. They can be visible for the environment:
- bc(prettyprint)..
- var variable1: real
- p. Variables can be *readonly* (constants):
- bc(prettyprint)..
- var readonly pi: real = 3.1415
- p. Variables can be referenced by the environment.
- bc(prettyprint)..
- var external variable3: integer = 34
- p. ==<!-- End stext_keyword_var -->==
- ==<!-- Start stext_keyword_const -->==
- h3(#Constants). Constants
- Variables can be immutable. For this special variable the keyword @const@ is used:
- bc(prettyprint)..
- const variable1: real
- p. ==<!-- End stext_keyword_const -->==
- h3(#ReactionTriggers). Reaction Triggers
- Actions are key constructs in state machines to model behavior. YAKINDU SCT 2 knows about the following kinds of actions.
- ==<!-- Start stext_keyword_after -->==
- h4(#after). after
- The _after_ trigger specifies a one-shot time event.
- After the specified time the reaction is triggered. An _after_ trigger can be used in transitions of states as well as in local reactions of states and statecharts. The specified time starts when the state or statechart is entered.
- bc(prettyprint). after 20 s
- Structure:
- @after@ _@time@_ _@unit@_
- The time value may be a literal or an expression that returns an integer value.
- The time unit can be:
- * ==<!-- Start stext_keyword_s -->== s - seconds ==<!-- End stext_keyword_s -->==
- * ==<!-- Start stext_keyword_ms -->== ms - milliseconds ==<!-- End stext_keyword_ms -->==
- * ==<!-- Start stext_keyword_us -->== us - microseconds ==<!-- End stext_keyword_us -->==
- * ==<!-- Start stext_keyword_ns -->== ns - nanoseconds ==<!-- End stext_keyword_ns -->==
- p. ==<!-- End stext_keyword_after -->==
- ==<!-- Start stext_keyword_every -->==
- h4(#every). every
- The _every_ trigger specifies periodic time events.
- The reaction is triggered recurrently after each passing of the specified period of time. An _every_ trigger can be used in transitions as well as in local reactions of states and statecharts. The specified period of time starts when the state or statechart is entered and repeats periodically.
- bc(prettyprint). every 200 ms
- Structure:
- @every@ _@time@_ _@unit@_
- The time value may be a literal or an expression that returns an integer value.
- The time unit can be:
- * s - seconds
- * ms - milliseconds
- * us - microseconds
- * ns - nanoseconds
- ==<!-- End stext_keyword_every -->==
- ==<!-- Start stext_keyword_always -->==
- h4(#always). always
- This trigger is always true and enables a reaction to be executed in every run-to-completion step (RTC). It is equivalent to _oncycle_.
- ==<!-- End stext_keyword_always -->==
- ==<!-- Start stext_keyword_default -->==
- ==<!-- Start stext_keyword_else -->==
- h4(#defaultelse). default, else
- The _default_ trigger is equivalent to the _else_ trigger. It is intended to be used for the outgoing transitions of _choice_ pseudo states to make sure that there is always an outgoing transition that can be taken. The _default_ trigger can only be be used in transitions and implies the lowest evaluation priority for that transition.
- ==<!-- End stext_keyword_else -->==
- ==<!-- End stext_keyword_default -->==
- ==<!-- Start stext_keyword_entry -->==
- h4(#entry). entry
- An _entry_ trigger marks actions that are carried out on entering a state or state machine.
- ==<!-- End stext_keyword_entry -->==
- ==<!-- Start stext_keyword_exit -->==
- h4(#exit). exit
- An _exit_ trigger marks actions that are carried out on exiting a state or state machine.
- ==<!-- End stext_keyword_exit -->==
- ==<!-- Start stext_keyword_oncycle -->==
- h4(#oncycle). oncycle
- The _oncycle_ trigger is always true and enables a reaction to be executed in every run-to-completion step (RTC). It is equivalent to _always_.
- ==<!-- End stext_keyword_oncycle -->==
- ==<!-- Start stext_keyword_operation -->==
- h3(#Operations). Operations
- Operations can have none, one or multiple parameters. A parameter is declared with a name and a type. An operation may have a single return type similar to Java.
- bc(prettyprint)..
- operation localOperation (xValue : integer, yValue : integer):integer
- p.
- ==<!-- End stext_keyword_operation -->==
- h3(#BuildInFunctions). Build-in functions
- ==<!-- Start stext_keyword_valueof -->==
- h4(#valueofevent). valueof(event)
- ==<!-- FIXME: Clarify/elaborate the meaning of the following sentence: -->==
- Returns the value of an valued event that it passed to the function as parameter.
- bc(prettyprint)..
- myVar = valueof(myEvent)
- p.
- ==<!-- End stext_keyword_valueof -->==
- ==<!-- Start stext_keyword_as -->==
- h4(#as). as
- Casts a variable. The following example casts a literal from integer to real.
- bc(prettyprint)..
- myReal = 12 as real
- p.
- ==<!-- End stext_keyword_as -->==
- ==<!-- Start stext_keyword_active -->==
- h4(#activestate). active(state)
- Returns _true_ if a state is active and _false_ otherwise.
- bc(prettyprint)..
- myBool = active(StateA)
- p.
- ==<!-- End stext_keyword_active -->==
- h3(#LocalReactions). Local reactions
- Local reactions describe the internal behavior of a state. So they have internal scope. A local reaction is declared as follows:
- bc(prettyprint)..
- LocalReaction: ReactionTrigger '/' ReactionEffect ('#' ReactionProperties)?
- ReactionTrigger: (Event ("," Event )* (=> '[' Expression ']')?) | '[' Expression ']'
- ReactionEffect: Statement (';' Statement )* (';')?
- Statement: Assignment | EventRaising | OperationCall
- ReactionProperties: (EntryPoint | ExitPoint)*
- p. Within a local reaction an interface event can be raised:
- bc(prettyprint)..
- internal:
- localEvent1 / raise NamedInterface.event3 : localOperation (valueof(localEvent), NamedInterface.variable1);
- p. A local reaction can have a priority value. The latter is defined by appending the character @#@ and the numeric priority value to the local reaction's definition. Examples:
- ==<!-- FIXME: Describe the meaning of priorities! -->==
- bc(prettyprint#GeneratorFeatures)..
- localEvent2 / NamedInterface.variable2 += 3; #1
- localEvent3 / NamedInterface.variable4 += 2.0; #2
- h2(#Codegeneration). Code generation
- h3. SGen generator features
- All generators can be customized by a generator model. This is a textual model in a file, specifying generator features, i.e. the outlet path. The following screenshot shows an sample configuration for the Java code generator.
- To get started with the generator model, YAKINDU Statechart Tools includes a wizard that creates a basic configuration file with default values.
- !images/sGenEditor.png(SGen generator model with default values)!
- ==<!-- FIXME: Explain what a "builder" is! -->==
- The generator model is associated with the builder. If _Project → Build Automatically_ is checked, the generator automatically creates its output files for each modification the user makes to the statechart model. Below the specific customizing features of the generator models are explained.
- The following section describes the *Core Features* which are available for all code generators:
- ==<!-- Start sgen_feature_outlet -->==
- h4(#Outlet). Outlet
- The *Outlet* feature specifies target project and target folder for the generated artifacts. It is a _required_ feature and has the following parameters:
- # __targetProject__ (String, required): The project to store the generated artifacts to.
- # __targetFolder__ (String, required): The folder to store the generated artifacts to. If a library folder is given, only the dynamic (i.e. model dependent artifacts) are generated into the target folder, if not all generated artifacts will be generated into it. All artifacts in this folder will be overwritten during re-generation.
- # __libraryTargetFolder__ (String, optional): The folder to store the static (i.e. model independent artifacts) to. In case this is not specified, all artifacts will be generated into the target folder. All artifacts in this folder will be preserved during re-generation.
- Sample configuration:
- bc(prettyprint)..
- feature Outlet {
- targetProject = "SampleProject"
- targetFolder = "src-gen"
- libraryTargetFolder = "src"
- }
- p. ==<!-- End sgen_feature_outlet -->==
- ==<!-- Start sgen_feature_licenseheader -->==
- h4(#LicenseHeader). LicenseHeader
- The *LicenseHeader* feature specifies the license text that is to be added as a header to the generated artifacts. It is an *optional* feature and has the following parameters:
- # __licenseText__ (String, required): License text to be added as a file header
- Sample configuration:
- bc(prettyprint)..
- feature LicenseHeader {
- licenseText = "Copyright (c) 2012 committers of YAKINDU and others."
- }
- p. ==<!-- End sgen_feature_licenseheader -->==
- ==<!-- Start sgen_feature_functioninlining -->==
- h4(#FunctionInlining). FunctionInlining
- The *FunctionInlining* feature enables the inlining of expressions instead of generating separate functions or methods. This might reduce the readability of the generated code, but increases performance, because less operation calls are necessary.
- It is an *optional* feature and has the following parameters:
- # __inlineReactions__ (Boolean, optional): inlines the expression for reactions
- # __inlineEntryActions__ (Boolean, optional): inlines the expression for entry actions
- # __inlineExitActions__ (Boolean, optional): inlines the expression for exit actions
- # __inlineEnterSequences__ (Boolean, optional): inlines the expression for enter sequences
- # __inlineExitSequences__ (Boolean, optional): inlines the expression for exit sequences
- # __inlineChoices__ (Boolean, optional): inlines the expression for choices
- # __inlineEnterRegion__ (Boolean, optional): inlines the expression for enter regions
- # __inlineExitRegion__ (Boolean, optional): inlines the expression for exit regions
- # __inlineEntries__ (Boolean, optional): inlines the expression for entries
- Sample configuration:
- bc(prettyprint)..
- feature FunctionInlining {
- inlineChoices = false
- inlineEnterRegion = true
- inlineEntries = true
- }
- p. ==<!-- End sgen_feature_functioninlining -->==
- ==<!-- Start sgen_feature_debug -->==
- h4(#Debug). Debug
- The *Debug* feature dumps the execution model to the target folder as an XMI model. It is an *optional* feature and has the following parameter:
- # __dumpSexec__ (Boolean, required): dumps the execution model as XMI model
- Sample configuration:
- bc(prettyprint)..
- feature Debug {
- dumpSexec = true
- }
- p. ==<!-- End sgen_feature_debug -->==
- h3(#JavaGeneratorFeatures). Java generator features
- ==<!-- Start sgen_feature_naming -->==
- h4. Naming feature
- The *Naming* feature allows the configuration of package names as well as class name prefix / suffix.
- It is an *optional* feature and has the following parameters:
- # __basePackage__ (Boolean, required): The package to create for the generated java classes
- # __implementationSuffix__ (Boolean, optional): The suffix for the implementing classes
- Sample configuration:
- bc(prettyprint)..
- feature Naming {
- basePackage = "org.yakindu.sct"
- implementationSuffix = "Impl"
- }
- p. ==<!-- End sgen_feature_naming -->==
- ==<!-- Start sgen_feature_runnablewrapper -->==
- h4. RunnableWrapper
- Generates a runnable wrapper for the state machine. This feature generates an additional Java class providing a thread-safe wrapper for the generated state machine implementation. In addition to the specific state machine interface it implements the __Runnable__ interface and can be executed in a thread. It implements an event queue and event-driven execution semantics. As the wrapper adds thread safety any number of client threads may call the state machine.
- It is an *optional* feature and has the following parameters:
- # __namePrefix__ (String, optional): prefix of the implementing class' name
- # __nameSuffix__ (String, optional): suffix of the implementing class' name
- Sample configuration:
- ==<!-- FIXME: The namePrefix in the example below does not have a trailing dot. Is this correct? -->==
- bc(prettyprint)..
- feature RunnableWrapper {
- namePrefix = "org.yakindu.sct"
- nameSuffix = "Impl"
- }
- p. ==<!-- End sgen_feature_runnablewrapper -->==
- ==<!-- Start sgen_feature_generalfeatures -->==
- h4(#GeneralFeatures). GeneralFeatures
- The *GeneralFeatures* feature allows to configure additional services to be generated along with the state machine. Per default, all parameters are __false__. It is an *optional* feature and has the following parameters:
- ==<!-- # __EventBasedStatemachine__ (Boolean, optional): enables/disables the generation of a cycle based state machine implementation -->==
- # __InterfaceObserverSupport__ (Boolean, optional): enables/disables the generation of listener interfaces for the state machine
- # __RuntimeService__ (Boolean, optional): enables/disables the generation of a runtime service that triggers the run cycle of a cycle-based state machine
- # __TimerService__ (Boolean, optional): enables/disables the generation of a timer service implementation using __java.util.Timer__
- ==<!-- # __GenericInterfaceSupport__ (Boolean, optional): enables/disables the generation of generic interfaces -->==
- ==<!-- # __StatemachineFactorySupport__ (Boolean, optional): enables/disables the generation of a factory class -->==
- Sample configuration:
- bc(prettyprint)..
- feature GeneralFeatures {
- InterfaceObserverSupport = true
- RuntimeService = true
- TimerService = true
- }
- p. ==<!-- End sgen_feature_generalfeatures -->==
- h3(#CGeneratorFeatures). C/C++ generator features
- ==<!-- Start sgen_feature_identifiersettings -->==
- h4. IdentifierSettings
- The *IdentifierSettings* feature allows the configuration of module names and identifier character length:
- # __moduleName__ (String, optional): name for header and implementation, default: statechart name
- # __statemachinePrefix__ (Boolean, optional): prefix which is prepended to function, state, and type names.
- # __maxIdentifierLength__ (Integer, optional): maximum number of characters of an identifier, default: 31 characters, which is complying with the ANSI C99 standard.
- # __separator__ (String, optional): character to replace whitespace and otherwise illegal characters in manes.
- Sample configuration:
- bc(prettyprint)..
- feature IdentifierSettings {
- moduleName = "MyStatechart"
- statemachinePrefix = "myStatechart"
- maxIdentifierLength = 31
- separator = "_"
- }
- p. ==<!-- End sgen_feature_identifiersettings -->==
- ==<!-- Start sgen_feature_generatoroptions -->==
- h4. GeneratorOptions
- The *GeneratorOptions* feature allows change the behavior of the C++ generator:
- # __innerFunctionVisibility__ (String, optional): This parameter is used to change the visibility of inner functions and variables. By default @private@ visibility is used. It can be changed to @protected@ to allow function overriding for a class which inherits from the generated state machine base class.
- # __staticOperationCallback__ (Boolean, optional): If this parameter is set to _true_, the callback function declaration for statechart operations is static and the functions are called statically by the state machine code.
- Sample configuration:
- bc(prettyprint)..
- feature GeneratorOptions {
- innerFunctionVisibility = "protected"
- staticOperationCallback = true
- }
- p. ==<!-- End sgen_feature_generatoroptions -->==
- ==<!-- Start sgen_feature_junitwrapper -->==
- h4. JUnitWrapper
- Using the *JUnitWrapper* feature it is possible to create JUnit tests that will run the generated gtests.
- # __WrapToJUnit__ (Boolean): This parameter determines whether a JUnit wrapper test is to be generated __(true)__ or not __(false)__.
- Sample configuration:
- bc(prettyprint)..
- feature JUnitWrapper {
- WrapToJUnit = "false"
- }
- p. ==<!-- End sgen_feature_junitwrapper -->==
- h3. Custom code generators
- h4(#CreatingCustomCodeGenerators). Creating custom code generators
- YAKINDU Statechart Tools provide a rich feature set to support custom code generators out of the box. These code generators can be either written in Java, "Xtend":http://www.eclipse.org/xtend/, or "Xpand":http://www.eclipse.org/modeling/m2t/?project=xpand.
- h5(#WritingacustomcodegeneratorwithXtend2Java). Writing a custom code generator with Xtend2/Java
- First, you have to create a new Xtend2 generator project. Click __File → New → Other... → YAKINDU → YAKINDU Xtend2/Java Generator Project__ to create a new Xtend2 generator project.
- !images/xtendGenerator.png(Creating an Xtend2 generator project)!
- The wizard asks for a *Project name* and the name of the *Generator class*, which has to be the fully-qualified class name. If you check the *Use Xtend* checkbox, the generator class will initially be created as an "Xtend":http://www.eclipse.org/xtend/ class. Otherwise, Java will be used for the generator.
- The check box *Configure for Plugin Export* adds all required extension point registrations to the new project for exporting it as a plugin. The generator model can refer to the new generator plugin via its unique *Generator ID*. If you want to contribute custom generator features for your code generator, check the *Create Feature Library* check box.
- After clicking on *Finish* a new project is created in your workspace. All required plugin dependencies and extension points are registered and you can start to write your code generator based on the ExecutionFlow meta model [Link].
- h4(#ExecutingacustomXtend2Javacodegenerator). Executing a custom Xtend2/Java code generator
- YAKINDU Statechart Tools provide a convenient way to execute your generator while you are developing it.
- For this, you have to create a new *generator model* with the generator ID *yakindu::generic*, either by using the *New Statechart Generator Model* wizard or by simply creating a new text file with the file extension @.sgen@. The feature described below allows to configure your code generator.
- ==<!-- Start sgen_feature_generator -->==
- h5(#Generator). Generator
- The *Generator* feature allows to configure a custom code generator located in the workspace and written in Java or in another JVM language. It is a *required* feature and has the following parameters:
- # __generatorProject__ (String, required): the name of the generator project
- # __generatorClass__ (String, required): the fully-qualified name of the code generator class
- # __configurationModule__ (String, optional): the fully-qualified class name of a Guice module to configure the code generator
- Sample configuration:
- bc(prettyprint)..
- feature Generator {
- generatorProject = "org.yakindu.sct.mygenerator"
- generatorClass = "org.yakindu.sct.MyGenerator"
- }
- p. ==<!-- End sgen_feature_generator -->==
- h4(#ExecutingacustomXpandcodegenerator). Executing a custom Xpand code generator
- In order to execute an Xpand-based custom code generator, you have to create a new *Generator Model* with the generator ID *yakindu::xpand*, either by using the *New Statechart Generator Model* wizard or by simply creating a new text file with the file extension *.sgen*. The following feature allows to configure your code generator.
- ==<!-- Start sgen_feature_template -->==
- h5(#Template). Template
- The *Generator* feature allows to configure a custom code generator located in the workspace and written in Java or in another JVM language. It is a *required* feature and has the following parameters:
- # __templateProject__ (String, required): the name of the generator project
- # __templatePath__ (String, required): the fully-qualified template path of the main template
- Sample configuration:
- bc(prettyprint)..
- feature Template {
- templateProject = "ExampleProject"
- templatePath = "org::yakindu::sct::generator::xpand::Main::main"
- }
- p. ==<!-- End sgen_feature_template -->==
- h2(#APISpecification). API specifications of the generated code
- The explanations below are using the _TrafficLight_ sample state machine to describe the API specifications of the code generated by the YAKINDU C and Java code generators. The image below is showing the statechart. It models a pedestrian crossing with push-button operated traffic lights ("pelican crossing").
- !(img-rounded shadowed#SpecJava)images/TrafficLight.png(The traffic light model)!
- h3(#JavaSpec). Specifications of Java code
- You can checkout the Java sample project _"org.yakindusct.examples.trafficlight":https://github.com/Yakindu/statecharts/tree/master/examples/org.yakindu.sct.examples.trafficlight_ from the "YAKINDU Statechart Tools GitHub repository":https://github.com/Yakindu/statecharts. The Java example contains statechart, SGen model, graphical widgets, and some glue code to connect the generated code with the widgets. The graphical widgets are based on SWT.
- To execute the Java example, run the file _CrossingDemoCycleBased.java_ as "Java Application" from the Eclipse _Run As_ context menu.
- h4(#JavaGeneratedCode). Generated code files
- Generally you will find generated code at the places specified in the SGen model, see <a href="#Outlet">section "Outlet"</a> for details.
- In the case of the traffic light example, you will find the generated code in the _src-gen_ folder.
- The package _org.yakindu.sct.examples.trafficlight.cyclebased_ contains the general state machine interfaces and classes. They are needed by each particular state machine and are independend from concrete ones.
- h4. The state machine interface
- Each generated state machine implements the @IStatemachine@ interface:
- bc(prettyprint)..
- package org.yakindu.sct.examples.trafficlight.cyclebased;
- /**
- * Basic interface for state machines.
- */
- public interface IStatemachine {
- /**
- * Initializes the state machine. Use to init internal variables etc.
- */
- public void init();
- /**
- * Enters the state machine. Sets the state machine in a defined state.
- */
- public void enter();
- /**
- * Exits the state machine. Leaves the state machine with a defined state.
- */
- public void exit();
- /**
- * Start a run-to-completion cycle.
- */
- public void runCycle();
- }
- h5. Fundamental statechart methods
- The generated code contains fundamental methods to initialize, enter, and exit a state machine, as well as a method to start a run-to-completion step.
- The @IStatemachine@ interface specifies the four methods @init()@, @enter()@, @exit()@, and @runCycle()@.
- * The @init()@ method is used to initialize the internal objects of the state machine right after its instantiation. Variables are initialized to their respective default values. If the statechart defines initialized variables, these initializations are also done in the @init()@ method.
- * The @enter()@ method must be called to enter the state machine. It brings the state machine to a well-defined state.
- * The @exit()@ method is used to leave a state machine statefully. If for example a history state is used in one of the top regions, the last active state is stored and the state machine is left via @exit()@. Re-entering it via @enter()@ continues to work with the saved state.
- * The @runCycle()@ method is used to trigger a run-to-completion step in which the state machine evaluates arising events and computes possible state changes. Somewhat simplified, a run-to-completion cycle consists of the following steps:
- # Clear list of outgoing events.
- # Check whether events have occurred which are leading to a state change.
- # If a state change has to be done:
- ## Execute exit actions of the present state.
- ## Save history state, if necessary.
- ## Make the new state active. ==<!-- FIXME: We should also make the old state inactive, shouldn't we? -->==
- ## Execute entry actions of the new state.
- # Clear list of incoming events.
- ==<!-- h5. Variable and event access -->==
- ==<!-- Do we need some equivalent to the C section here? Here's the C text: -->==
- ==<!-- The getters and setters for each variable and event are also contained in the header file. The method names are matching the following pattern: _statechart_name_<code>Iface</code>_interface_name_@_@[ <code>set</code> | <code>get</code> | <code>raise</code> ]@_@[ _variable_name_ | _event_name_ ]. For example, the getter of the variable _red_ of the _pedestrian_ interface is named @trafficLightWaitingIfacePedestrian_get_red(TrafficLightWaiting* handle)@. -->==
- h4. Time-controlled state machines
- If a statechart uses timing functionality, additional classes are generated.
- The traffic light example uses timing funtionality, namely _after_ clauses. To support time-controlled behavior, the interfaces @ITimerCallback@ and @ITimer@ are generated. Like @IStatemachine@, they are independend of any particular state machine and are generated in the _libraryTargetFolder_ directory, if specified. See <a href="#Outlet">section "Outlet"</a> for details.
- The generated state machine class implements the @ITimerCallback@ and has a property _timer_ of type @ITimer@. The client code must provide an @ITimer@ implementation to the state machine by calling the latter's @setTimer()@ method.
- Here's an example showing how to create a new instance of the state machine (here: class @MyTimedStatemachine@), create a new instance of a timer (here: class @MyTimer@), set the latter on the former, and start the state machine by entering it:
- bc(prettyprint)..
- MyTimedStatemachine sm = new MyTimedStatemachine();
- sm.setTimer(new MyTimer());
- sm.enter(); // Enter the state machine
- p. Timer functions generally depend on the hardware target used, therefore the proper time handling has to be implemented by the developer. In principle, for each hardware target a dedicated timer service class implementing the @ITimer@ interface has to be developed.
- h4. Default timer implementation
- However, upon request the Java code generator can create a default implementation of the @ITimer@ interface, and in many cases it will be sufficient. This implementation is based on @java.util.Timer@ and @java.util.TimerTask@ and should be compatible with the Oracle JVM or the OpenJDK JVM.
- To generate the default timer service class, set the _TimerService_ feature in the SGen model to _true_. Example:
- bc(prettyprint)..
- GeneratorModel for yakindu::java {
- statechart MyStateMachine {
- /* … */
- feature GeneralFeatures {
- TimerService = true
- }
-
- }
- }
- p. The generated class is named @TimerService@ and looks like this:
- bc(prettyprint)..
- package org.yakindu.scr;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Timer;
- import java.util.TimerTask;
- /**
- * Default timer service implementation.
- *
- */
- public class TimerService implements ITimer {
- private final Timer timer = new Timer();
-
- private final List<TimeEventTask> timerTaskList = new ArrayList<TimeEventTask>();
-
- /**
- * Timer task that reflects a time event. It's internally used by
- * {@link TimerService}.
- *
- */
- private class TimeEventTask extends TimerTask {
-
- private ITimerCallback callback;
-
- int eventID;
-
- /**
- * Constructor for a time event.
- *
- * @param callback
- * : Set to {@code true} if event should be repeated
- * periodically.
- *
- * @param eventID
- * : Index position within the state machine's timeEvent
- * array.
- */
- public TimeEventTask(ITimerCallback callback, int eventID) {
- this.callback = callback;
- this.eventID = eventID;
- }
-
- public void run() {
- callback.timeElapsed(eventID);
- }
-
- public boolean equals(Object obj) {
- if (obj instanceof TimeEventTask) {
- return ((TimeEventTask) obj).callback.equals(callback)
- && ((TimeEventTask) obj).eventID == eventID;
- }
- return super.equals(obj);
- }
- }
-
- public void setTimer(final ITimerCallback callback, final int eventID,
- long time, boolean isPeriodic) {
-
- // Create a new TimerTask for given event and store it.
- TimeEventTask timerTask = new TimeEventTask(callback, eventID);
- timerTaskList.add(timerTask);
-
- // start scheduling the timer
- if (isPeriodic) {
- timer.scheduleAtFixedRate(timerTask, time, time);
- } else {
- timer.schedule(timerTask, time);
- }
- }
-
- public void unsetTimer(ITimerCallback callback, int eventID) {
- int index = timerTaskList.indexOf(new TimeEventTask(callback, eventID));
- if (index != -1) {
- timerTaskList.get(index).cancel();
- timer.purge();
- timerTaskList.remove(index);
- }
- }
-
- /**
- * Cancel timer service. Use this to end possible timing threads and free
- * memory resources.
- */
- public void cancel() {
- timer.cancel();
- timer.purge();
- }
- }
- h4. Timer service
- A timer service must implement the @ITimer@ interface and must be able to maintain a number of time events and the timers associated with them. A time event is identified by a numeric ID.
- If suitable, an application can use the default timer service class @TimerService@, see <a href="#Defaulttimerimplementation">"Default timer implementation"</a> for details.
- The @ITimer@ interface looks like this:
- bc(prettyprint)..
- package org.yakindu.scr;
- /**
- * Interface a timer has to implement. Use to implement your own timer
- * service.
- *
- */
- public interface ITimer {
- /**
- * Starts the timing for a given time event id.
- *
- * @param callback
- * : The target callback where the time event has to be raised.
- *
- * @param eventID
- * : The eventID the timer should use if timed out.
- *
- * @param time
- * : Time in milliseconds after the given time event should be
- * triggered
- *
- * @param isPeriodic
- * : Set to true if the time event should be triggered periodically
- */
- public void setTimer(ITimerCallback callback, int eventID, long time, boolean isPeriodic);
- /**
- * Unset a time event.
- *
- * @param callback
- * : The target callback for which the time event has to be unset.
- *
- * @param eventID
- * : The time event id.
- */
- public void unsetTimer(ITimerCallback callback, int eventID);
- }
- h5. Method setTimer
- p. A state machine calls the @setTimer(ITimerCallback callback, int eventID, long time, boolean isPeriodic)@ method to tell the timer service that it has to start a timer for the given _eventID_. The _time_ parameter specifies the number of milliseconds until the timer expires. When this period of time has elapsed, the timer service must raise the time event by calling the method @public void timeElapsed(int eventID)@ on the @ITimerCallback@ specified by the _callback_ parameter, i. e. usually the state machine.
- It is important to keep the execution of the @setTimer()@ method short and use it only to start a timer thread, a hardware timer interrupt, or the like. Avoid any time-consuming operations like extensive computations, @Thread.sleep(…)@, waiting, etc. Otherwise the state machine execution might hang within the timer service or might not show the expected runtime behavior.
- If the parameter _isPeriodic_ is _false_, the timer service raises the time event only once. If _isPeriodic_ is _true_, the timer service raises the time event every _time_ milliseconds.
- h5. Method unsetTimer
- If the state machine calls the @unsetTimer(ITimerCallback callback, int eventID)@ method the timer service must unset the timer for the given _eventID_, i. e. the time event will not be raised.
- h4. Raising time events on a state machine
- If a statechart is using time events, the generated Java state machine class not only implements the @IStatemachine@ interface, but it also implements the @ITimerCallback@ interface. @ITimerCallback@ is defined as follows. It specifies a single method: @public void timeElapsed(int eventID)@.
- bc(prettyprint)..
- package org.yakindu.scr;
- /**
- * Interface for state machines which use timed event triggers.
- */
- public interface ITimerCallback {
-
- /**
- * Callback method if a time event occurred.
- *
- * @param eventID
- * :The id of the occurred event.
- */
- public void timeElapsed(int eventID);
- }
- h5. Method timeElapsed
- It is the timer service's responsibility to actually raise a time event on a state machine. To do so, the timer service calls the state machine's @timeElapsed()@ method and supplies the time event's _eventID_ as a parameter. The state machine recognizes the time event and will process it during the next run cycle.
- You can conclude that in order to process time events without too much latency, the runtime environment has to call the state machine's @runCycle()@ method as frequently as needed. Consider for example a time event which is raised by the timer service after 500 ms. However, if the runtime environment calls the state machine's @runCycle()@ method with a frequency of once per 1000 ms only, the event will quite likely not be processed at the correct points in time.
- h4(#RuntimeService). Runtime service
- The @RuntimeService@ class maintains all state machines that are expected to execute run-to-completion steps periodically. A client application can retrieve the @RuntimeService@ singleton using @RuntimeService.getInstance()@. It can then pause, resume or cancel all state machines that are poised to run at a specified intervall.
- h4(#JavaInterVar). Accessing interfaces, variables and events
- In a YAKINDU statechart, variables and events are contained in so-called *interfaces*. There can be at most one default, unnamed interface plus zero or more named interfaces. In the generated Java code, these interfaces can be found as inner interface of the interface specifying the state machine. The outer interface's name is derived from the statechart's name while the inner interfaces' names are derived from the respective names of the statechart interfaces.
- Let's have a look at the following sample statechart interface declaration:
- bc(prettyprint)..
- interface Sample:
- var a:boolean
- in event evA:boolean
- out event evB:integer
- p. The generated interface code looks like this:
- bc(prettyprint)..
- import org.yakindu.scr.IStatemachine;
- import org.yakindu.scr.ITimerCallback;
- public interface IDefaultSMStatemachine extends ITimerCallback, IStatemachine {
- public interface SCISample {
- public void raiseEvA(boolean value);
- public boolean isRaisedEvB();
- public long getEvBValue();
- public boolean getA();
- public void setA(boolean value);
- }
- public SCISample getSCISample();
- }
- p. A statechart interface is generated as an inner Java interface within the state machine interface. The Java interface's name is derived from the statechart interface's name by prepending the string @SCI@.
- A special case is the unnamed statechart interface: It is generated as the Java interface @SCInterface@.
- An incoming event _evA:boolean_ is generated as the raise method @raiseEvA(boolean value)@. Since the event is of type _boolean_ the method has a _boolean_ parameter.
- For an outgoing event _evB:integer_ the methods @boolean isRaisedEvB()@ and @long getEvBValue()@ are generated. The former can be used to determine whether the event has already been raised by the state machine or not. The latter serves to query the value of the event.
- For variables, the code generator creates getter and setter methods, here @boolean getA()@ and @void setA(boolean value)@.
- The code generator also creates appropriately named getter methods in the enclosing interface which can be used to acquire the nested interfaces, here: @SCISample getSCISample()@.
- The nesting interface is implemented by the generated state machine source code. Each nested interface is implemented as an internal class of the state machine class. The latter holds instances of the nested interface implementations and provides them via getter methods. Have a look at (some snippets of) the source code generated for the _Sample_ interface:
- bc(prettyprint)..
- import org.yakindu.scr.ITimer;
- public class DefaultSMStatemachine implements IDefaultSMStatemachine {
- protected class SCISampleImpl implements SCISample {
- private boolean evA;
- private boolean evAValue;
- public void raiseEvA(boolean value) {
- evA = true;
- evAValue = value;
- }
- protected boolean getEvAValue() {
- if (!evA)
- throw new IllegalStateException("Illegal event value acces. Event EvA is not raised!");
- return evAValue;
- }
- private boolean evB;
- private long evBValue;
- public boolean isRaisedEvB() {
- return evB;
- }
- protected void raiseEvB(long value) {
- evB = true;
- evBValue = value;
- }
- public long getEvBValue() {
- if (!evB)
- throw new IllegalStateException("Illegal event value acces. Event EvB is not raised!");
- return evBValue;
- }
- private boolean a;
- public boolean getA() {
- return a;
- }
- public void setA(boolean value) {
- this.a = value;
- }
- protected void clearEvents() {
- evA = false;
- }
- protected void clearOutEvents() {
- evB = false;
- }
- }
- protected SCISampleImpl sCISample;
- public SCISample getSCISample() {
- return sCISample;
- }
-
- /* … */
- }
- p. The value of an event can be accessed only if the event has been processed in a run-to-completion step. Otherwise an @IllegalStateException@ will be thrown.
- h4(#JavaInterfaceObservers). Interface observers
- If the general feature _InterfaceObserverSupport_ is enabled in the SGen model, the generated interfaces will support the registration of observers.
- Enabling the _InterfaceObserverSupport_ feature looks like this in the _.sgen_ file:
- bc(prettyprint)..
- feature GeneralFeatures {
- InterfaceObserverSupport = true
- }
- p. Now the generated code has additional features:
- bc(prettyprint)..
- package org.yakindu.scr.defaultsm;
- import java.util.List;
- import org.yakindu.scr.IStatemachine;
- import org.yakindu.scr.ITimerCallback;
- public interface IDefaultSMStatemachine extends ITimerCallback, IStatemachine {
- public interface SCISample {
- public void raiseEvA(boolean value);
- public boolean isRaisedEvB();
- public long getEvBValue();
- public boolean getA();
- public void setA(boolean value);
- public List<SCISampleListener> getListeners();
- }
- public interface SCISampleListener {
- public void onEvBRaised(long value);
- }
- public SCISample getSCISample();
- }
- p. An additional listener interface is generated, here @SCISampleListener@. It contains a callback method for each outgoing event. Here it is a single one: @void onEvBRaised(long value)@.
- The client code has to provide an implementation of the listener interface. A listener method gets called by the state machine when it raises an outgoing event.
- To register or unregister a listener, use the @getListeners()@ method of the nesting interface. This method returns a @java.util.List@ parameterized with the appropriate listener type. Initially this list is empty. Add or remove listeners as needed.
- A callback method specified by the listener interface should complete its operations quickly, because otherwise the state machine execution might be delayed for too long, potentially leading to unexpected runtime behavior.
- h4(#JavaOperationCallbacks). Operation callbacks
- YAKINDU Statechart Tools support *operations* that are executed by a state machine as actions, but are implemented by client-side code. The figure below shows a sample statechart using an operation:
- !images/operationExample.png(Specifying an operation callback in the model)!
- Let's have a look at the generated code:
- bc(prettyprint)..
- import java.util.List;
- import org.yakindu.scr.IStatemachine;
- public interface IDefaultSMStatemachine extends IStatemachine {
- public interface SCISample {
- public void raiseEvA(boolean value);
- public boolean isRaisedEvB();
- public long getEvBValue();
- public boolean getA();
- public void setA(boolean value);
- public List<SCISampleListener> getListeners();
- public void setSCISampleOperationCallback(SCISampleOperationCallback operationCallback);
- }
- public interface SCISampleListener {
- public void onEvBRaised(long value);
- }
- public interface SCISampleOperationCallback {
- public long myOperation(long p1, boolean p2);
- }
- public SCISample getSCISample();
- }
- p. An additional interface @SCISampleOperationCallback@ specifying the method @public long myOperation(long p1, boolean p2)@ has been generated. The client code has to
- * provide an implementation of this interface and
- * pass an instance of it to the state machine via the @setSCISampleOperationCallback(SCISampleOperationCallback operationCallback)@ method.
- Here's some sample code that passes an implementation of the operation to a state machine, and then executes the latter:
- bc(prettyprint)..
- public static void main(String[] args) {
- DefaultSMStatemachine statemachine = new DefaultSMStatemachine();
- SCISampleOperationCallback callback = new SCISampleOperationCallback() {
- @Override
- public long myOperation(long p1, boolean p2) {
- // Your operation code should be placed here;
- return 0;
- }
- };
- statemachine.getSCISample().setSCISampleOperationCallback(callback);
- statemachine.init();
- statemachine.enter();
- statemachine.runCycle();
- }
- h4(#JavaIntegratingGeneratedCode). Integrating generated code
- To get a clue how to integrate a generated Java state machine with your project have a look at the @CrossingDemoCycleBased@ class and its abstract superclass @CrossingDemoBase@. The @main()@ method is in @CrossingDemoCycleBased@:
- bc(prettyprint)..
- public static void main(String[] args) {
- new CrossingDemoCycleBased().runTrafficLight();
- }
- p. A new instance of the class is created and the method @runTrafficLight()@ is called. This method can be found in the superclass:
- bc(prettyprint)..
- public void runTrafficLight() {
- setUpAndRunStatemachine();
- createUIContent();
- shell.open();
- while (!shell.isDisposed()) {
- // update traffic lights
- readStatemachineOutput();
- crossing.repaint();
- if (!display.readAndDispatch()) {
- display.sleep();
- }
- }
- tearDownStatemachine();
- }
- p. This method sets up the state machine and creates the GUI content. In a while loop it reads the content of the state machine and repaints the GUI. If the user exits the GUI shell, the loop terminates and the state machine is torn down. The really interesting methods are @setUpAndRunStatemachine()@, @readStatemachineOutput@ and @tearDownStatemachine()@:
- bc(prettyprint)..
- protected void setUpAndRunStatemachine() {
- statemachine = new TrafficLightWaitingStatemachine();
- statemachine.setTimerService(new TimerService());
- statemachine.init();
- statemachine.enter();
- RuntimeService.getInstance().registerStatemachine(statemachine, 100);
- }
- p. First a new instance of the generated state machine is created. Since the traffic light statechart uses timing clauses, it is provided with a timer service, here with the default implementation of the @ITimerService@ interface. In the next steps the state machine is initialized and entered. After the @enter()@ method has been executed, the machine is in a defined state.
- Finally the state machine is passed to the runtime service. This service executes the @runCycle()@ method of the state machine every 100 ms, that is the state machine executes a run-to-completion step every 100 ms.
- bc(prettyprint)..
- protected void readStatemachineOutput() {
- trafficLightFigure.setRed(statemachine.getSCITrafficLight()
- .getRed());
- trafficLightFigure.setYellow(statemachine.getSCITrafficLight()
- .getYellow());
- trafficLightFigure.setGreen(statemachine.getSCITrafficLight()
- .getGreen());
- pedestrianLightFigure.setWhite(statemachine.getSCIPedestrian()
- .getRequest());
- pedestrianLightFigure.setRed(statemachine.getSCIPedestrian()
- .getRed());
- pedestrianLightFigure.setGreen(statemachine.getSCIPedestrian()
- .getGreen());
- }
- p. The generated code contains getters and setters for each variable and event. So it's easy to read values from or write values to a state machine, raise events, or ask the state machine whether outgoing events have been raised during the last run-to-completion step. Within the @readStatemachineOutput()@ method, these methods are used to get the lights values from the state machine and set them to the UI elements. The methods @pedestrianRequestButtonClicked()@ and @onOffButtonClicked()@ raise some events.
- Hint: When outgoing events are raised within the state machine, they remain active until the next run-to-completion step is started.
- bc(prettyprint)..
- @Override
- protected void tearDownStatemachine() {
- // End TimerHandler and RuntimeService.
- statemachine.getTimerService().cancel();
- RuntimeService.getInstance().cancelTimer();
- }
- p. If the UI thread has been terminated by the user, the state machine will be shut down. It is necessary to explicitly end the timer service. Finally the runtime service is cancelled.
- h3(#SpecC). Specifications of C code
- You can checkout the C sample project _"org.yakindu.sct.examples.c.trafficlight":https://github.com/Yakindu/statecharts/tree/master/examples/org.yakindu.sct.examples.c.trafficlight_ from the "YAKINDU Statechart Tools GitHub repository":https://github.com/Yakindu/statecharts. The C example contains statechart, SGen model, graphical widgets, and some glue code to connect the generated code with the widgets. The graphical widgets are based on Qt.
- To execute the C example, run the file _org_yakindu_sct_examples_c_trafficlight_ as _Local C/C++ application_ from the Eclipse _Run As_ context menu.
- h4(#CGeneratedCode). Generated code files
- You will find the generated code in the _src-gen_ folder of the traffic light example.
- The C code generator generates three header files. The first one is _sc_types.h_:
- bc(prettyprint)..
- #ifndef SC_TYPES_H_
- #define SC_TYPES_H_
- #ifdef __cplusplus
- extern "C" {
- #endif
- #include <stdint.h>
- #include <stdbool.h>
- #define sc_string char*
-
- typedef bool sc_boolean;
- typedef int_fast16_t sc_short;
- typedef uint_fast16_t sc_ushort;
- typedef int32_t sc_integer;
- typedef uint32_t sc_uinteger;
- typedef double sc_real;
- typedef void* sc_eventid;
- #ifdef __cplusplus
- }
- #endif
- #ifndef null
- #ifdef __cplusplus
- #define null 0
- #else
- #define null ((void *)0)
- #endif
- #endif
- #define bool_true true
- #define bool_false false
- #endif /* SC_TYPES_H_ */
- p. The header file contains some basic definitions for C++ compiler compatibility and typedefs to map the YAKINDU statechart types to C types. The next header file is named after the statechart. In case of the traffic light example it is called _TrafficLightWaiting.h_:
- bc(prettyprint)..
- #ifndef TRAFFICLIGHTWAITING_H_
- #define TRAFFICLIGHTWAITING_H_
- #include "sc_types.h"
- #ifdef __cplusplus
- extern "C" {
- #endif
- /*! \file Header of the state machine 'TrafficLightWaiting'.
- */
- /*! Enumeration of all states */
- typedef enum {
- TrafficLightWaiting_main_region_on,
- TrafficLightWaiting_main_region_on_r1_StreetGreen,
- TrafficLightWaiting_main_region_on_r1_PedWaiting,
- TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOn,
- TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOff,
- TrafficLightWaiting_main_region_on_r1_StreetAttention,
- TrafficLightWaiting_main_region_on_r1_StreetRed,
- TrafficLightWaiting_main_region_on_r1_PedestrianGreen,
- TrafficLightWaiting_main_region_on_r1_PedestrianRed,
- TrafficLightWaiting_main_region_on_r1_StreetPrepare,
- TrafficLightWaiting_main_region_off,
- TrafficLightWaiting_main_region_off_r1_YellowOn,
- TrafficLightWaiting_main_region_off_r1_YellowOff,
- TrafficLightWaiting_last_state
- } TrafficLightWaitingStates;
- /*! Type definition of the data structure for the TrafficLightWaitingIfaceTrafficLight interface scope. */
- typedef struct {
- sc_boolean red;
- sc_boolean yellow;
- sc_boolean green;
- } TrafficLightWaitingIfaceTrafficLight;
- /*! Type definition of the data structure for the TrafficLightWaitingIfacePedestrian interface scope. */
- typedef struct {
- sc_boolean request;
- sc_boolean red;
- sc_boolean green;
- } TrafficLightWaitingIfacePedestrian;
- /*! Type definition of the data structure for the TrafficLightWaitingIface interface scope. */
- typedef struct {
- sc_boolean pedestrianRequest_raised;
- sc_boolean onOff_raised;
- } TrafficLightWaitingIface;
- /*! Type definition of the data structure for the TrafficLightWaitingTimeEvents interface scope. */
- typedef struct {
- sc_boolean trafficLightWaiting_main_region_on_r1_PedWaiting_tev0_raised;
- sc_boolean trafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOn_tev0_raised;
- sc_boolean trafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOff_tev0_raised;
- sc_boolean trafficLightWaiting_main_region_on_r1_StreetAttention_tev0_raised;
- sc_boolean trafficLightWaiting_main_region_on_r1_StreetRed_tev0_raised;
- sc_boolean trafficLightWaiting_main_region_on_r1_PedestrianGreen_tev0_raised;
- sc_boolean trafficLightWaiting_main_region_on_r1_PedestrianRed_tev0_raised;
- sc_boolean trafficLightWaiting_main_region_on_r1_StreetPrepare_tev0_raised;
- sc_boolean trafficLightWaiting_main_region_off_r1_YellowOn_tev0_raised;
- sc_boolean trafficLightWaiting_main_region_off_r1_YellowOff_tev0_raised;
- } TrafficLightWaitingTimeEvents;
- /*! Define dimension of the state configuration vector for orthogonal states. */
- #define TRAFFICLIGHTWAITING_MAX_ORTHOGONAL_STATES 1
- /*!
- * Type definition of the data structure for the TrafficLightWaiting state machine.
- * This data structure has to be allocated by the client code.
- */
- typedef struct {
- TrafficLightWaitingStates stateConfVector[TRAFFICLIGHTWAITING_MAX_ORTHOGONAL_STATES];
- sc_ushort stateConfVectorPosition;
-
- TrafficLightWaitingIfaceTrafficLight ifaceTrafficLight;
- TrafficLightWaitingIfacePedestrian ifacePedestrian;
- TrafficLightWaitingIface iface;
- TrafficLightWaitingTimeEvents timeEvents;
- } TrafficLightWaiting;
- /*! Initializes the TrafficLightWaiting state machine data structures. Must be called before first usage.*/
- extern void trafficLightWaiting_init(TrafficLightWaiting* handle);
- /*! Activates the state machine */
- extern void trafficLightWaiting_enter(TrafficLightWaiting* handle);
- /*! Deactivates the state machine */
- extern void trafficLightWaiting_exit(TrafficLightWaiting* handle);
- /*! Performs a 'run to completion' step. */
- extern void trafficLightWaiting_runCycle(TrafficLightWaiting* handle);
- /*! Raises a time event. */
- extern void trafficLightWaiting_raiseTimeEvent(const TrafficLightWaiting* handle, sc_eventid evid);
- /*! Gets the value of the variable 'red' that is defined in the interface scope 'TrafficLight'. */
- extern sc_boolean trafficLightWaitingIfaceTrafficLight_get_red(const TrafficLightWaiting* handle);
- /*! Sets the value of the variable 'red' that is defined in the interface scope 'TrafficLight'. */
- extern void trafficLightWaitingIfaceTrafficLight_set_red(TrafficLightWaiting* handle, sc_boolean value);
- /*! Gets the value of the variable 'yellow' that is defined in the interface scope 'TrafficLight'. */
- extern sc_boolean trafficLightWaitingIfaceTrafficLight_get_yellow(const TrafficLightWaiting* handle);
- /*! Sets the value of the variable 'yellow' that is defined in the interface scope 'TrafficLight'. */
- extern void trafficLightWaitingIfaceTrafficLight_set_yellow(TrafficLightWaiting* handle, sc_boolean value);
- /*! Gets the value of the variable 'green' that is defined in the interface scope 'TrafficLight'. */
- extern sc_boolean trafficLightWaitingIfaceTrafficLight_get_green(const TrafficLightWaiting* handle);
- /*! Sets the value of the variable 'green' that is defined in the interface scope 'TrafficLight'. */
- extern void trafficLightWaitingIfaceTrafficLight_set_green(TrafficLightWaiting* handle, sc_boolean value);
- /*! Gets the value of the variable 'request' that is defined in the interface scope 'Pedestrian'. */
- extern sc_boolean trafficLightWaitingIfacePedestrian_get_request(const TrafficLightWaiting* handle);
- /*! Sets the value of the variable 'request' that is defined in the interface scope 'Pedestrian'. */
- extern void trafficLightWaitingIfacePedestrian_set_request(TrafficLightWaiting* handle, sc_boolean value);
- /*! Gets the value of the variable 'red' that is defined in the interface scope 'Pedestrian'. */
- extern sc_boolean trafficLightWaitingIfacePedestrian_get_red(const TrafficLightWaiting* handle);
- /*! Sets the value of the variable 'red' that is defined in the interface scope 'Pedestrian'. */
- extern void trafficLightWaitingIfacePedestrian_set_red(TrafficLightWaiting* handle, sc_boolean value);
- /*! Gets the value of the variable 'green' that is defined in the interface scope 'Pedestrian'. */
- extern sc_boolean trafficLightWaitingIfacePedestrian_get_green(const TrafficLightWaiting* handle);
- /*! Sets the value of the variable 'green' that is defined in the interface scope 'Pedestrian'. */
- extern void trafficLightWaitingIfacePedestrian_set_green(TrafficLightWaiting* handle, sc_boolean value);
- /*! Raises the in event 'pedestrianRequest' that is defined in the default interface scope. */
- extern void trafficLightWaitingIface_raise_pedestrianRequest(TrafficLightWaiting* handle);
- /*! Raises the in event 'onOff' that is defined in the default interface scope. */
- extern void trafficLightWaitingIface_raise_onOff(TrafficLightWaiting* handle);
- /*!
- * Checks if the statemachine is active (until 2.4.1 this method was used for states).
- * A statemachine is active if it was entered. It is inactive if it has not been entered at all or if it was exited.
- */
- extern sc_boolean trafficLightWaiting_isActive(const TrafficLightWaiting* handle);
- /*!
- * Checks if all active states are final.
- * If there are no active states then the statemachine is considered as inactive and this method returns false.
- */
- extern sc_boolean trafficLightWaiting_isFinal(const TrafficLightWaiting* handle);
- /*! Checks if the specified state is active (until 2.4.1 the used method for states was calles isActive()). */
- extern sc_boolean trafficLightWaiting_isStateActive(const TrafficLightWaiting* handle, TrafficLightWaitingStates state);
- #ifdef __cplusplus
- }
- #endif
- #endif /* TRAFFICLIGHTWAITING_H_ */
- p. Within this header file an @enum@ containing the state names is defined as well as data structures for each of the statechart's interfaces. Additionally a structure for the statechart's time events is defined. The interfaces' and time events' data structures are nested into the parent structure @TrafficLightWaiting@. The client has to allocate this structure. It is a common parameter of most methods the statechart defines. Below this structure is called the _statechart data structure_.
- h5. Fundamental statechart methods
- The generated code contains fundamental methods to initialize, enter, and exit a state machine, as well as a method to start a run-to-completion step.
- In the header file the method names are made up of the statechart name followed by the name of the respective functionality. For example, the methods of the traffic light example are generated as follows:
- bc(prettyprint)..
- extern void trafficLightWaiting_init(TrafficLightWaiting* handle);
- extern void trafficLightWaiting_enter(TrafficLightWaiting* handle);
- extern void trafficLightWaiting_exit(TrafficLightWaiting* handle);
- extern void trafficLightWaiting_runCycle(TrafficLightWaiting* handle);
- p.
- * The @init()@ method is used to initialize the statechart data structure right after its instantiation. Variables are initialized to their respective default values. If the statechart defines initialized variables, these initializations are also done in the @init()@ method.
- * The @enter()@ method must be called to enter the state machine. It brings the state machine to a well-defined state.
- * The @exit()@ method is used to leave a state machine statefully. If for example a history state is used in one of the top regions, the last active state is stored and the state machine is left via @exit()@. Re-entering it via @enter()@ continues to work with the saved state.
- * The @runCycle()@ method is used to trigger a run-to-completion step in which the state machine evaluates arising events and computes possible state changes. Somewhat simplified, a run-to-completion cycle consists of the following steps:
- # Clear list of outgoing events.
- # Check whether events have occurred which are leading to a state change.
- # If a state change has to be done:
- ## Execute exit actions of the present state.
- ## Save history state, if necessary.
- ## Make the new state active. ==<!-- FIXME: We should also make the old state inactive, shouldn't we? -->==
- ## Execute entry actions of the new state.
- # Clear list of incoming events.
- h5. Accessing variables and events
- The getters and setters for each variable and event are also contained in the header file. The method names are matching the following pattern: _statechart_name_<code>Iface</code>_interface_name_@_@[ <code>set</code> | <code>get</code> | <code>raise</code> ]@_@[ _variable_name_ | _event_name_ ]. For example, the getter of the _red_ variable of the _pedestrian_ interface is named @trafficLightWaitingIfacePedestrian_get_red(TrafficLightWaiting* handle)@.
- h4. Time-controlled state machines
- If a statechart uses timing functionality or external operations, an additional header file is generated. Its name matches the pattern _statechart_name_@Required.h@. This header file defines method hooks the client code has to implement externally.
- The traffic light example uses timing funtionality, namely _after_ clauses. To support time-controlled behavior, such an additional header file is generated.
- bc(prettyprint)..
- #ifndef TRAFFICLIGHTWAITINGREQUIRED_H_
- #define TRAFFICLIGHTWAITINGREQUIRED_H_
- #include "sc_types.h"
- #include "TrafficLightWaiting.h"
- #ifdef __cplusplus
- extern "C" {
- #endif
- /*! \file This header defines prototypes for all functions that are required by the state machine implementation.
- This is a state machine uses time events which require access to a timing service. Thus the function prototypes:
- - trafficLightWaiting_setTimer and
- - trafficLightWaiting_unsetTimer
- are defined.
- These functions will be called during a 'run to completion step' (runCycle) of the statechart.
- There are some constraints that have to be considered for the implementation of these functions:
- - never call the statechart API functions from within these functions.
- - make sure that the execution time is as short as possible.
-
- */
- /*!
- * This is a timed state machine that requires timer services
- */
- /*! This function has to set up timers for the time events that are required by the state machine. */
- /*!
- This function will be called for each time event that is relevant for a state when a state will be entered.
- \param evid An unique identifier of the event.
- \time_ms The time in milli seconds
- \periodic Indicates the the time event must be raised periodically until the timer is unset
- */
- extern void trafficLightWaiting_setTimer(TrafficLightWaiting* handle, const sc_eventid evid, const sc_integer time_ms, const sc_boolean periodic);
- /*! This function has to unset timers for the time events that are required by the state machine. */
- /*!
- This function will be called for each time event taht is relevant for a state when a state will be left.
- \param evid An unique identifier of the event.
- */
- extern void trafficLightWaiting_unsetTimer(TrafficLightWaiting* handle, const sc_eventid evid);
- #ifdef __cplusplus
- }
- #endif
- #endif /* TRAFFICLIGHTWAITINGREQUIRED_H_ */
- p. Basically the proper time handling has to be implemented by the developer, because timer functions generally depend on the hardware target used. So for each hardware target the client code must provide a method to set a timer and another method to unset it. These methods have to be implemented externally and linked to the generated code.
- p. The following methods are dealing with timing functionality:
- h5. Method setTimer
- p. A state machine calls the @setTimer()@ method – short for the method's full name like e. g. @void trafficLightWaiting_setTimer(TrafficLightWaiting* handle, const sc_eventid evid, const sc_integer time_ms, const sc_boolean periodic)@ – to tell the timer service that it has to start a timer for the given time event identifier and raise it after the period of time specified by the _time_ms_ parameter has expired. It is important to only start a timer thread or a hardware timer interrupt within the @setTimer()@ method and avoid any time-consuming operations like extensive computations, sleeping or waiting. Never call the statechart API functions from within these functions! Otherwise the state machine execution might hang within the timer service or might not show the expected runtime behavior.
- In order to have the timer service raise the time event periodically, the parameter _periodic_ must be _true_.
- h5. Method unsetTimer
- p. The state machine calls the method @trafficLightWaiting_setTimer(TrafficLightWaiting* handle, const sc_eventid evid, const sc_integer time_ms, const sc_boolean periodic)@ to notify the timer service to unset the timer for the given event ID.
- h5. Method raiseTimeEvent
- p. In order to notify the state machine about the occurence of a time event after a period of time has expired, the @raiseTimeEvent()@ method – defined in the header file of the state machine – is called on the state machine. In the case of the traffic light example it is named @trafficLightWaiting_raiseTimeEvent(const TrafficLightWaiting* handle, sc_eventid evid)@ (in file _TrafficLightWaiting.h_).
- The time event is recognized by the state machine and will be processed during the next run cycle.
- You can conclude that in order to process the time events raised by the timing service without too much latency, the runtime environment has to call the state machine's @runCycle()@ method as frequently as needed. Consider for example a time event which is raised by the timer service after 500 ms. However, if the runtime environment calls the state machine's @runCycle()@ method with a frequency of once per 1000 ms only, the event will quite likely not be processed at the correct points in time.
- h4(#COperationCallbacks). Operation callbacks
- YAKINDU Statechart Tools support client code operations that can be used by a state machine and are executed as as actions. These operations have to be implemented in order to make a statechart executable. The figure below shows a sample statechart using an operation:
- !images/operationExample.png(Specifying an operation callback in the model)!
- Let's have a look at the generated code:
- bc(prettyprint)..
- #ifndef DEFAULTSMREQUIRED_H_
- #define DEFAULTSMREQUIRED_H_
- #include "sc_types.h"
- #include "DefaultSM.h"
- #ifdef __cplusplus
- extern "C" {
- #endif
- /*! \file This header defines prototypes for all functions that are required by the state machine implementation.
- This state machine makes use of operations declared in the state machines interface or internal scopes. Thus the function prototypes:
- - defaultSMIfaceSample_myOperation
- are defined.
- These functions will be called during a 'run to completion step' (runCycle) of the statechart.
- There are some constraints that have to be considered for the implementation of these functions:
- - never call the statechart API functions from within these functions.
- - make sure that the execution time is as short as possible.
-
- */
- extern sc_integer defaultSMIfaceSample_myOperation(DefaultSM* handle, const sc_integer p1, const sc_boolean p2);
- #ifdef __cplusplus
- }
- #endif
- #endif /* DEFAULTSMREQUIRED_H_ */
- p. An additional method @sc_integer defaultSMIfaceSample_myOperation(DefaultSM* handle, const sc_integer p1, const sc_boolean p2)@ has been generated. This method has to be implemented and linked with the generated code, so that the state machine can use it.
- h4(#CIntegratingGeneratedCode). Integrating generated code
- To get a clue how to integrate a generated C state machines with your project have a look at the @main.cpp@ file and its @main()@ method:
- bc(prettyprint)..
- #include "org_yakindu_sct_examples_c_trafficlight.h"
- #include <QtGui>
- #include <QApplication>
- #include "src-gen/sc_types.h"
- #include "src-gen/TrafficLightWaiting.h"
- #include "statemachine/TrafficLightTimer.h"
- #include "statemachine/TrafficLightRunner.h"
- TrafficLightTimer *timer;
- int main(int argc, char *argv[]) {
- TrafficLightWaiting handle;
- trafficLightWaiting_init(&handle);
- timer = new TrafficLightTimer(&handle);
- trafficLightWaiting_enter(&handle);
- QApplication a(argc, argv);
- TrafficLightRunner *runner = new TrafficLightRunner(&handle, 100);
- org_yakindu_sct_examples_c_trafficlight w(0, runner);
- w.show();
- int ret = a.exec();
- return ret;
- }
- void trafficLightWaiting_setTimer(const sc_eventid evid,
- const sc_integer time_ms, const sc_boolean periodic) {
- timer->setTimer(evid, time_ms, periodic);
- }
- void trafficLightWaiting_unsetTimer(const sc_eventid evid) {
- timer->unsetTimer(evid);
- }
- p. First an instance of the statechart data structure is created and initialized by the @trafficLightWaiting_init(&handle)@ method. The next step instantiates the timer. The class @TrafficLightTimer@ represents an implementation of a timer service and uses the timer fuctionality of the Qt framework. The @TrafficLightRunner@ is a runtime service which executes a run-to-completion step of the state machine every 100 ms. The runner class and the GUI are wired in the class @org_yakindu_sct_examples_c_trafficlight@:
- bc(prettyprint)..
- #include "org_yakindu_sct_examples_c_trafficlight.h"
- org_yakindu_sct_examples_c_trafficlight::org_yakindu_sct_examples_c_trafficlight(
- QWidget *parent, TrafficLightRunner *runner) :
- QMainWindow(parent) {
- ui.setupUi(this);
- crossing = new CrossingWidget(this);
- trafficLight = new TrafficLightWidget(crossing);
- trafficLight->setGeometry(275, 75, 30, 90);
- pedestrianLight = new PedestrianLightWidget(crossing);
- pedestrianLight->setGeometry(50, 10, 70, 20);
- connect(runner, SIGNAL(cycleDone(TrafficLightWaiting*)), this, SLOT(update(TrafficLightWaiting*)));
- pedestrianReq = new QPushButton("pedestrian request", this);
- pedestrianReq->setGeometry(1, 365, 150, 30);
- connect(pedestrianReq, SIGNAL(released()), runner, SLOT(raisePedestrianRequest()));
- off = new QPushButton("off / on", this);
- off->setGeometry(249, 365, 150, 30);
- connect(off, SIGNAL(released()), runner, SLOT(raiseOnOff()));
- }
- void org_yakindu_sct_examples_c_trafficlight::update(
- TrafficLightWaiting *handle) {
- trafficLight->setSignals(handle->ifaceTrafficLight.red,
- handle->ifaceTrafficLight.yellow, handle->ifaceTrafficLight.green);
- pedestrianLight->setSignals(handle->ifacePedestrian.request,
- handle->ifacePedestrian.red, handle->ifacePedestrian.green);
- QMainWindow::update();
- }
- org_yakindu_sct_examples_c_trafficlight::~org_yakindu_sct_examples_c_trafficlight() {
- }
- h3(#CppSpec). Specifications of C++ code
- You can checkout the C++ sample project _"QtTrafficLightCpp":http://svn.codespot.com/a/eclipselabs.org/yakindu/SCT2/trunk/examples_ from the "YAKINDU Google Code repository":http://svn.codespot.com/a/eclipselabs.org/yakindu/SCT2/trunk. The C++ example contains statechart, SGen model, graphical widgets, and some glue code to connect the generated code with the widgets. The graphical widgets are based on Qt.
- ==<!-- FIXME: C: To execute the C example, run the file _org_yakindu_sct_examples_c_trafficlight_ as "Local C/C++ application" from the Eclipse _Run As_ context menu. -->==
- h4(#CppGeneratedCode). Generated code files
- You will find the generated code in the _src-gen_ folder of the traffic light example.
- The _StatemachineInterface.h_ header file defines the fundamental state machine interface methods. This file also contains the definition of the abstract class @StatemachineInterface@ which contains pure virtual functions only. It is needed by each particular state machine and is independend from concrete ones.
- h4. Statemachine class
- The state machine source code is generated as a C++ class with the same name as the statechart. For example, if the statechart is named _DefaultSM_ the C++ class will also be called _DefaultSM_ and will be generated as the source code file _DefaultSM.cpp_.
- h4. Abstract class StatemachineInterface
- Each generated state machine implements the interface @StatemachineInterface@:
- bc(prettyprint)..
- #ifndef STATEMACHINEINTERFACE_H_
- #define STATEMACHINEINTERFACE_H_
- /*
- * Basic interface for statemachines.
- */
- class StatemachineInterface {
- public:
-
- virtual ~StatemachineInterface() = 0;
-
- /*
- * Initializes the statemachine. Use to init internal variables etc.
- */
- virtual void init() = 0;
-
- /*
- * Enters the statemachine. Sets the statemachine in a defined state.
- */
- virtual void enter() = 0;
-
- /*
- * Exits the statemachine. Leaves the statemachine with a defined state.
- */
- virtual void exit() = 0;
-
- /*
- * Start a run-to-completion cycle.
- */
- virtual void runCycle() = 0;
-
- /*
- * Checks if the statemachine is active.
- * A statemachine is active if it was entered. It is inactive if it has not been entered at all or if it was exited.
- */
- virtual sc_boolean isActive() = 0;
-
- /*
- * Checks if all active states are final.
- * If there are no active states then the statemachine is considered as inactive and this method returns false.
- */
- virtual sc_boolean isFinal() = 0;
- };
- inline StatemachineInterface::~StatemachineInterface() {}
- #endif /* STATEMACHINEINTERFACE_H_ */
- h5. Fundamental statechart methods
- The generated code contains fundamental methods to initialize, enter, and exit a state machine, as well as a method to start a run-to-completion step.
- The @StatemachineInterface@ interface specifies the four functions @init()@, @enter()@, @exit()@ and @runCycle()@.
- * The @init()@ function is used to initialize the internal objects of the state machine right after its instantiation. Variables are initialized to their respective default values. If the statechart defines initialized variables, these initializations are also done in the @init()@ function.
- * The @enter()@ function must be called to enter the state machine. It brings the state machine to a well-defined state.
- * The @exit()@ function is used to leave a state machine statefully. If for example a history state is used in one of the top regions, the last active state is stored and the state machine is left via @exit()@. Re-entering it via @enter()@ continues to work with the saved state.
- * The @runCycle()@ function is used to trigger a run-to-completion step in which the state machine evaluates arising events and computes possible state changes. Somewhat simplified, a run-to-completion cycle consists of the following steps:
- # Clear list of outgoing events.
- # Check whether events have occurred which are leading to a state change.
- # If a state change has to be done:
- ## Execute exit actions of the present state.
- ## Save history state, if necessary.
- ## Make the new state active. ==<!-- FIXME: We should also make the old state inactive, shouldn't we? -->==
- ## Execute entry actions of the new state.
- # Clear list of incoming events.
- h4. Time-controlled state machines
- If a statechart uses timing functionality, additional classes are generated.
- The traffic light example uses timing funtionality, namely _after_ clauses. To support time-controlled behavior, the abstract classes @TimedStatemachineInterface@ and @TimerInterface@ are generated.
- The @TimedStatemachineInterface@ interface extends the generated state machine by a @TimerInterface@ data member. The client code must provide an implementation of that interface.
- @TimedStatemachineInterface@ also specifies the callback function @raiseTimeEvent(sc_eventid event)@, enabling the timer service to raise time events.
- bc(prettyprint)..
- #ifndef TIMEDSTATEMACHINEINTERFACE_H_
- #define TIMEDSTATEMACHINEINTERFACE_H_
- #include "sc_types.h"
- #include "TimerInterface.h"
- /*
- * Interface for state machines which use timed event triggers.
- */
- class TimedStatemachineInterface {
- public:
-
- virtual ~TimedStatemachineInterface() = 0;
-
- /*
- * Set the ITimerService for the state machine. It must be set
- * externally on a timed state machine before a run cycle can be correct
- * executed.
- */
- virtual void setTimer(TimerInterface* timer) = 0;
-
- /*
- * Returns the currently used timer service.
- */
- virtual TimerInterface* getTimer() = 0;
-
- /*
- * Callback method if a time event occurred.
- */
- virtual void raiseTimeEvent(sc_eventid event) = 0;
- };
- inline TimedStatemachineInterface::~TimedStatemachineInterface() {}
- #endif /* TIMEDSTATEMACHINEINTERFACE_H_ */
- p. Basically the proper time handling has to be implemented by the developer, because timer functions generally depend on the hardware target used. So for each hardware target a timer service class implementing the @TimerInterface@ interface has to be developed.
- Let's have a look at the @TimerInterface@ interface:
- bc(prettyprint)..
- #ifndef TIMERINTERFACE_H_
- #define TIMERINTERFACE_H_
- #include "sc_types.h"
- //forward declaration of TimedStatemachineInterface to avoid cyclic dependency
- class TimedStatemachineInterface;
- /*
- * Basic interface for statemachines.
- */
- class TimerInterface {
- public:
-
- virtual ~TimerInterface() = 0;
-
- /*
- * Starts the timing for a time event.
- */
- virtual void setTimer(TimedStatemachineInterface* statemachine, sc_eventid event, sc_integer time, sc_boolean isPeriodic) = 0;
-
- /*
- * Unsets the given time event.
- */
- virtual void unsetTimer(TimedStatemachineInterface* statemachine, sc_eventid event) = 0;
-
- /*
- * Cancel timer service. Use this to end possible timing threads and free
- * memory resources.
- */
- virtual void cancel() = 0;
- };
- inline TimerInterface::~TimerInterface() {}
- #endif /* TIMERINTERFACE_H_ */
- p. The @TimerInterface@ interface defines the following functions dealing with timing functionality:
- h5. Function setTimer
- p. A state machine calls the @setTimer(TimedStatemachineInterface* statemachine, sc_eventid event, sc_integer time, sc_boolean isPeriodic)@ function to tell the timer service that it has to start a timer for the given time event and raise it after the period of time specified by the _time_ parameter has expired. It is important to only start a timer thread or a hardware timer interrupt within the @setTimer()@ function and to avoid any time-consuming operations like extensive computations, @Thread.sleep(…)@ or waiting. Otherwise the state machine execution might hang within the timer service or might not show the expected runtime behavior.
- In order to have the timer service raise the time event periodically, the parameter _isPeriodic_ must be _true_.
- h5. Function unsetTimer
- p. The state machine calls the function @unsetTimer(TimedStatemachineInterface* statemachine, sc_eventid event)@ to notify the timer service to unset the timer for the given event ID.
- h5. Function raiseTimeEvent
- p. In order to notify the state machine about the occurence of a time event after a period of time has expired, the function @raiseTimeEvent(sc_eventid event)@ must be called on the state machine. For this purpose, the state machine must implement the @TimedStatemachineInterface@) interface.
- The time event is recognized by the state machine and will be processed during the next run cycle.
- You can conclude that in order to process the time events raised by the timing service without too much latency, the runtime environment has to call the state machine's @runCycle()@ function as frequently as needed. Consider for example a time event which is raised by the timer service after 500 ms. However, if the runtime environment calls the state machine's @runCycle()@ function with a frequency of once per 1000 ms only, the event will quite likely not be processed at the correct points in time.
- h4(#CppInterVar). Accessing interfaces, variables and events
- In a YAKINDU statechart, variables and events are contained in so-called *interfaces*. There can be at most one default, unnamed interface plus zero or more named interfaces. In the generated C++ code, these interfaces can be found as internal subclasses of the main state machine class. This outer class' name is derived from the statechart's name while the internal subclasses' names are derived from the respective names of the statechart interfaces.
- Let's have a look at the following sample statechart interface declaration of a statechart named _DefaultSM_:
- bc(prettyprint)..
- interface Sample:
- var a:boolean
- in event evA:boolean
- out event evB:integer
- p. The generated interface code is shown below. Since the statechart's name is _DefaultSM_ the state machine class' name is also _DefaultSM_, to be found in the _DefaultSM.h_ file. The following is a snippet from that file.
- bc(prettyprint)..
- //! Inner class for Sample interface scope.
- class SCI_Sample {
-
- public:
- /*! Gets the value of the variable 'a' that is defined in the interface scope 'Sample'. */
- sc_boolean get_a();
-
- /*! Sets the value of the variable 'a' that is defined in the interface scope 'Sample'. */
- void set_a(sc_boolean value);
-
- /*! Raises the in event 'evA' that is defined in the interface scope 'Sample'. */
- void raise_evA(sc_boolean value);
-
- /*! Checks if the out event 'evB' that is defined in the interface scope 'Sample' has been raised. */
- sc_boolean isRaised_evB();
-
- /*! Gets the value of the out event 'evB' that is defined in the interface scope 'Sample'. */
- sc_integer get_evB_value();
-
-
- private:
- friend class DefaultSM;
- sc_boolean a;
- sc_boolean evA_raised;
- sc_boolean evA_value;
- sc_boolean evB_raised;
- sc_integer evB_value;
- };
- p. A statechart interface is generated as an internal subclass within the state machine class. The subclass' name is derived from the statechart interface's name by prepending the string @SCI_@.
- A special case is the unnamed statechart interface: It is generated as the C++ subclass @SCInterface@.
- An incoming event _evA:boolean_ is generated as the raise function @raise_evA(boolean value)@. Since the event is of type _boolean_ the function has a _boolean_ parameter.
- For an outgoing event _evB:integer_ the functions @isRaised_evB()@ and @get_evB_value()@ are generated. The former can be used to determine whether the event has already been raised by the state machine or not. The latter serves to query the value of the event.
- For variables, the code generator creates getter and setter functions, here @sc_boolean get_a()@ and @void set_a(sc_boolean value)@.
- The code generator also creates appropriately named getter functions in the enclosing class which can be used to acquire the inner classes, here: @SCI_Sample* getSCI_Sample()@.
- The nesting class is the generated state machine source code. It holds instances of the nested interface class implementations and provides them via getter functions. Have a look at (some snippets of) the source code generated for the _Sample_ statechart interface:
- bc(prettyprint)..
- void DefaultSM::SCI_Sample::raise_evA(sc_boolean value) {
- evA_value = value;
- evA_raised = true;
- }
- sc_boolean DefaultSM::SCI_Sample::isRaised_evB() {
- return evB_raised;
- }
- sc_integer DefaultSM::SCI_Sample::get_evB_value() {
- return evB_value;
- }
- sc_boolean DefaultSM::SCI_Sample::get_a() {
- return a;
- }
- void DefaultSM::SCI_Sample::set_a(sc_boolean value) {
- a = value;
- }
- p. The value of an event can be accessed only if the event has been processed in a run-to-completion step. Otherwise the event could contain an illegal value.
- ==<!-- h4(#CppInterfaceObservers). Interface observers -->==
- ==<!-- In Java we have such a chapter. What about a C++ equivalent? -->==
- h4(#CppOperationCallbacks). Operation callbacks
- YAKINDU Statechart Tools support client code operations that can be used by a state machine and are executed as as actions. These operations have to be implemented in order to make a statechart executable. The figure below shows a sample statechart using an operation:
- !images/operationExample.png(Specifying an operation callback in the model)!
- Let's have a look at the additionally generated code for operation support in the _DefaultSM.h_ header file:
- bc(prettyprint)..
- //! Inner class for Sample interface scope operation callbacks.
- class SCI_Sample_OCB {
- public:
- virtual ~SCI_Sample_OCB() = 0;
-
- virtual sc_integer myOperation(sc_integer p1, sc_boolean p2) = 0;
- };
-
- /*! Set the working instance of the operation callback interface 'SCI_Sample_OCB'. */
- void setSCI_Sample_OCB(SCI_Sample_OCB* operationCallback);
- p. An additional interface @SCI_Sample_OCB@ with the pure virtual function @sc_integer myOperation(sc_integer p1, sc_boolean p2)@ has been generated. This interface has to be implemented, and an instance of the implementing class has to be provided to the state machine via the @setSCI_Sample_OCB(SCI_Sample_OCB* operationCallback)@ function, so that the state machine can use it.
- bc(prettyprint)..
- #include "DefaultSM.h"
- sc_integer DefaultSM::SCI_Sample_OCB::myOperation(sc_integer p1, sc_boolean p2) {
- // Your operation code should be placed here;
- return 0;
- }
- int main(int argc, char *argv[]) {
- DefaultSM *defaultSM = new DefaultSM();
- SCI_Sample_OCB *sci_Sample_OCB = new SCI_Sample_OCB();
- defaultSM->setSCI_Sample_OCB(sci_Sample_OCB);
- defaultSM->init();
- defaultSM->enter();
- defaultSM->runCycle();
- }
- p.
- ==<!-- h4(#CppIntegratingGeneratedCode). Integrating generated code -->==
- ==<!-- This chapter is available for Java and C, but missing for C++. -->==
|