1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050 |
- 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). 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 -->==
- h2(#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 -->==
- h2(#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_tracing -->==
- h4. Tracing
- The *Tracing* feature allows to enable generation of tracing callback functions:
- # __enterState__ (Boolean, optional): whether to generate a callback that is used to notify about 'state enter' events.
- # __exitState__ (Boolean, optional): whether to generate a callback that is used to notify about 'state exit' events.
- Sample configuration:
- bc(prettyprint)..
- feature Tracing {
- enterState = true
- exitState = true
- }
- p. ==<!-- End sgen_feature_tracing -->==
- ==<!-- 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 -->==
- h2(#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.
- h3(#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].
- h3(#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 -->==
- h4(#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 -->==
- h3(#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 -->==
- h4(#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
- You will find the generated code in the _src-gen_ folder of the traffic light example.
- 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. Interface IStatemachine
- Each generated state machine implements the interface @IStatemachine@:
- 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. Timed 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 @ITimedStatemachine@, @ITimerService@ and the class @TimeEvent@ are generated.
- The @ITimedStatemachine@ interface extends the generated state machine by a @ITimerService@ attribute. The client code must provide an implementation of that interface. It may use the @TimerService@, an @ITimerService@ implementation that is also generated.
- @ITimedStatemachine@ also specifies the callback method @onTimeEventRaised(TimeEvent timeEvent)@, enabling the timer service to raise time events.
- bc(prettyprint)..
- package org.yakindu.sct.examples.trafficlight.cyclebased;
- /**
- * Interface for state machines which use timed event triggers.
- */
- public interface ITimedStatemachine {
- /**
- * Set the {@link ITimerService} for the state machine. It must be set
- * externally on a timed state machine before a run cycle can be correct
- * executed.
- *
- * @param timerService
- */
- public void setTimerService(ITimerService timerService);
- /**
- * Returns the currently used timer service.
- *
- * @return {@link ITimerService}
- */
- public ITimerService getTimerService();
- /**
- * Callback method if a {@link TimeEvent} occurred.
- *
- * @param timeEvent
- */
- public void onTimeEventRaised(TimeEvent timeEvent);
- }
- p. @ITimedStatemachine@ extends the generated state machine by a @ITimerService@ that can be set, and provides a callback method @onTimeEventRaised(TimeEvent timeEvent)@, enabling the timer service to raise @TimeEvents@.
- 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 @ITimerService@ interface has to be developed. Let's have a look at the @ITimerService@ interface:
- bc(prettyprint)..
- package org.yakindu.sct.examples.trafficlight.cyclebased;
- /**
- * Interface a timer service has to implement. Use to implement your own timer
- * service. A timer service has to be added to a timed state machine.
- *
- */
- public interface ITimerService {
- /**
- * Starts the timing for a given {@link TimeEvent}.
- *
- * @param event
- * : The TimeEvent the timer service should throw if timed out.
- * @param time
- * : Time in milliseconds after the given time event should be
- * triggered
- * @param cycleStartTime
- * : The absolute start time in milliseconds at which the last
- * run cycle was called. Can be used to produce a more accurate
- * timing behavior.
- */
- public void setTimer(TimeEvent event, long time, long cycleStartTime);
- /**
- * Unset the given {@link TimeEvent}. Use to unset cyclic repeated time
- * events.
- *
- * @param event
- */
- public void resetTimer(TimeEvent event);
- /**
- * Cancel timer service. Use this to end possible timing threads and free
- * memory resources.
- */
- public void cancel();
- /**
- * Returns the system time in milliseconds.
- *
- * @return the difference, measured in milliseconds, between the current
- * time and a defined point of time in the past.
- */
- public long getSystemTimeMillis();
- }
- p. The @ITimerService@ interface defines the following methods dealing with timing functionality:
- h5. Method setTimer
- p. A state machine calls the @public void setTimer(TimeEvent event, long time, long cycleStartTime)@ method 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()@ method and 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.
- The parameter @cycleStartTime@ holds the absolute start time of the last run cycle. It can be used to reduce or remove the time offset used by the state machine's runtime operations in order to achieve a more precise timing behavior.
- h5. Method resetTimer
- p. The state machine calls the method @resetTimer(TimeEvent event)@ to notify the timer service to reset the timer for the given event.
- h5. Method onTimeEventRaised
- p. In order to notify the state machine about the occurence of a @TimeEvent@ after a period of time has expired, the method @onTimeEventRaised(TimeEvent timeEvent)@ is called on the state machine. For this purpose, the state machine must implement the @ITimedStatemachine@ 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@ 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.
- h5. Class TimeEvent
- p. An important class used by timed state machines is @TimeEvent@:
- bc(prettyprint)..
- package org.yakindu.sct.examples.trafficlight.cyclebased;
- /**
- * Event that reflects a time event. It's internally used by
- * {@link ITimedStatemachine}.
- *
- * @author muehlbrandt
- *
- * @param <T>
- */
- public class TimeEvent {
- private boolean periodic;
- private ITimedStatemachine statemachine;
-
- int index;
- /**
- * Constructor for a time event.
- *
- * @param periodic
- * : Set to {@code true} if event should be repeated
- * periodically.
- *
- * @param index
- * : Index position within the state machine's timeEvent array.
- */
- public TimeEvent(boolean periodic, int index) {
- this.periodic = periodic;
- this.index = index;
- }
- /**
- * Returns the state machine reference of the event.
- *
- */
- public ITimedStatemachine getStatemachine() {
- return statemachine;
- }
- /**
- * Sets the state machine reference of the event.
- *
- * @param statemachine
- */
- public void setStatemachine(ITimedStatemachine statemachine) {
- this.statemachine = statemachine;
- }
- public boolean isPeriodic() {
- return periodic;
- }
- public int getIndex() {
- return index;
- }
- }
- p. A @TimeEvent@ holds a reference to the state machine it belongs to as well as a flag telling if the time event should be raised only once or periodically. The timer service implementation needs these information to properly raise the time event on the associated state machine. The _index_ attribute is used by the timed state machine internally.
- h4. Default implementation of ITimerService
- The Java code generator generates a default implementation of the @ITimerService@ interface if the _TimerService_ feature in the SGen model is set to _true_. This implementation is based on @java.util.Timer@ and @java.util.TimerTask@ and should be compatible with the Oracle JVM or the OpenJDK JVM.
- bc(prettyprint)..
- package org.yakindu.sct.examples.trafficlight.cyclebased;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Timer;
- import java.util.TimerTask;
- /**
- * Default timer service implementation.
- *
- */
- public class TimerService implements ITimerService {
- private final Timer timer = new Timer();
- private final Map<TimeEvent, TimerTask> timerTaskMap = new HashMap<TimeEvent, TimerTask>();
- public void setTimer(final TimeEvent event, long time,
- long cycleStartTime) {
- // Reset existing TimerTask for event. This step isn't necessary if
- // timer tasks are properly reset by sexec model.
- if (timerTaskMap.containsKey(event)) {
- resetTimer(event);
- }
- // Create a new TimerTask for given event.
- timerTaskMap.put(event, new TimerTask() {
- @Override
- public void run() {
- event.getStatemachine().onTimeEventRaised(event);
- }
- });
- // start scheduling the timer
- if (event.isPeriodic()) {
- timer.scheduleAtFixedRate(timerTaskMap.get(event),
- time - (System.currentTimeMillis() - cycleStartTime), time);
- } else {
- timer.schedule(timerTaskMap.get(event),
- time - (System.currentTimeMillis() - cycleStartTime));
- }
- }
- public void resetTimer(TimeEvent event) {
- if (timerTaskMap.containsKey(event) && timerTaskMap.get(event) != null) {
- timerTaskMap.get(event).cancel();
- timer.purge();
- }
- timerTaskMap.remove(event);
- }
- public void cancel() {
- timer.cancel();
- timer.purge();
- }
- public long getSystemTimeMillis() {
- return System.currentTimeMillis();
- }
- }
- h4(#RuntimeService). Runtime service
- The runtime service class can be used by client implementations to execute a run-to-completion step of a state machine periodically.
- ==<!-- FIXME: Information seems to be missing here. Where and how could/should I use a runtime service class? -->==
- h4(#JavaInterVar). Interfaces, Variable and Event access
- ==<!-- FIXME: It should be made clear what a statechart interface is, in contrast to e. g. am interface in a programming language. -->==
- In a YAKINDU statechart, variables and events are contained in *interfaces*. There can be a single default, unnamed interface plus zero or more named interfaces. In the generated Java code, these interfaces are defined as internal Java interfaces inside of an interface which has the same name as the state machine. Let's have a look at the following sample statechart interface declaration:
- bc(prettyprint)..
- interface:
- var a:boolean
- in event evA:boolean
- out event evB:integer
- p. The generated interface code looks like this:
- bc(prettyprint)..
- public interface IDefaultSMStatemachine extends IStatemachine {
- public interface SCInterface {
- public void raiseEvA(boolean value);
- public boolean isRaisedEvB();
- public int getEvBValue();
- public boolean getA();
- public void setA(boolean value);
- }
- p. The anonymous interface in a statechart is generated as the Java interface @SCInterface@. An incoming event _evA_ 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_ the methods @isRaisedEvB()@ and @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 boolean value of the event. For variables, the code generator creates getter and setter methods. Additionally, the enclosing interface contains getter methods to acquire nested interfaces.
- The nesting interface is implemented by the state machine itself. Each nested interface is implemented as an internal class. The nesting class holds an instance of each nested interface implementation and provides them via getter methods. Have a look at the code snipped generated from the unnamed default interface implementation:
- bc(prettyprint)..
- public class DefaultSMStatemachine implements IDefaultSMStatemachine {
- private final class SCInterfaceImpl implements SCInterface {
-
- private boolean evA;
-
- private boolean evAValue;
-
- public void raiseEvA(boolean value) {
- evA = true;
- evAValue = value;
- }
-
- private boolean getEvAValue() {
- if (!evA)
- throw new IllegalStateException(
- "Illegal event value acces. Event EvA is not raised!");
- return evAValue;
- }
-
- private boolean evB;
-
- private int evBValue;
-
- public boolean isRaisedEvB() {
- return evB;
- }
-
- private void raiseEvB(int value) {
- evB = true;
- evBValue = value;
- }
-
- public int 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;
- }
-
- public void clearEvents() {
- evA = false;
- }
-
- public void clearOutEvents() {
- evB = false;
- }
- }
-
- private SCInterfaceImpl sCInterface;
-
- public DefaultSMStatemachine() {
- sCInterface = new SCInterfaceImpl();
- }
-
- public SCInterface getSCInterface() {
- return sCInterface;
- }
- }
- p. The name of the default, unnamed statechart interface is generated as @SCInterface@. If a statechart interface has a dedicated name, e. g. _MyInterface_, then the Java interface name will be the statechart interface's name, prepended with string @SCI@, e. g. @SCIMyInterface@.
- 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:
- bc(prettyprint)..
- public interface IDefaultSMStatemachine extends IStatemachine {
- public interface SCInterface {
- public void raiseEvA(boolean value);
- public boolean isRaisedEvB();
- public int getEvBValue();
- public boolean getA();
- public void setA(boolean value);
- public List<SCInterfaceListener> getListeners();
- }
- public interface SCInterfaceListener {
- public void onEvBRaised(int value);
- }
- public SCInterface getSCInterface();
- }
- p. An additional interface @SCInterfaceListener@ is generated. This interface has to be implemented by the developer and contains a callback method for each outgoing event. The listener gets notified whenever the state machine internally raises an outgoing event. To add or remove a listener from an interface, use the @getListeners()@ method of the associated interface. This method returns a @java.util.List@ which is parameterized with the appropriate listener type. The callback method 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 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)..
- public interface IDefaultSMStatemachine extends IStatemachine {
- public interface SCInterface {
- public void raiseEvA(boolean value);
- public boolean isRaisedEvB();
- public int getEvBValue();
- public boolean getA();
- public void setA(boolean value);
- public void setSCInterfaceOperationCallback(
- SCInterfaceOperationCallback operationCallback);
- }
- public interface SCInterfaceOperationCallback {
- public int myOperation(int param1, boolean param2);
- }
- public SCInterface getSCInterface();
- }
- p. An additional interface @SCInterfaceOperationCallback@ specifying the method @myOperation(int param1, boolean param2)@ 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 @setSCInterfaceOperationCallback(SCInterfaceOperationCallback operationCallback)@ method, so that the state machine can use it.
- bc(prettyprint)..
- public static void main(String[] args) {
- DefaultSMStatemachine statemachine = new DefaultSMStatemachine();
-
- SCInterfaceOperationCallback callback = new SCInterfaceOperationCallback() {
-
- @Override
- public int myOperation(int param1, boolean param2) {
- // Your operation code should be placed here;
- return 0;
- }
- };
-
- statemachine.getSCInterface().setSCInterfaceOperationCallback(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>
-
- 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 char* sc_string;
- typedef void* sc_eventid;
- #ifdef __cplusplus
- }
- #endif
- #define sc_boolean bool
- #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_StreetPrepared ,
- 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_time_event_0_raised;
- sc_boolean TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOn_time_event_0_raised;
- sc_boolean TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOff_time_event_0_raised;
- sc_boolean TrafficLightWaiting_main_region_on_r1_StreetAttention_time_event_0_raised;
- sc_boolean TrafficLightWaiting_main_region_on_r1_StreetRed_time_event_0_raised;
- sc_boolean _main_region_on_r1_PedestrianGreen_time_event_0_raised;
- sc_boolean TrafficLightWaiting_main_region_on_r1_PedestrianRed_time_event_0_raised;
- sc_boolean TrafficLightWaiting_main_region_on_r1_StreetPrepared_time_event_0_raised;
- sc_boolean TrafficLightWaiting_main_region_off_r1_YellowOn_time_event_0_raised;
- sc_boolean TrafficLightWaiting_main_region_off_r1_YellowOff_time_event_0_raised;
- } TrafficLightWaitingTimeEvents;
- //! the maximum number of orthogonal states defines the dimension of the state configuration vector.
- #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(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(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(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(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(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(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(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 specified state is active. */
- extern sc_boolean trafficLightWaiting_isActive(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_exitTrafficLightWaiting* 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. Variable and event access
- 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. Timed 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)..
- 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(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(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 reset it. The 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. @trafficLightWaiting_setTimer(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_unsetTimer(const sc_eventid evid)@ 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(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 DEFAULTREQUIRED_H_
- #define DEFAULTREQUIRED_H_
- #include "sc_types.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:
- - defaultIface_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 defaultIface_myOperation(const sc_integer param1, const sc_boolean param2);
- #ifdef __cplusplus
- }
- #endif
- #endif /* DEFAULTREQUIRED_H_ */
- p. An additional method @sc_integer defaultIface_myOperation(const sc_integer param1, const sc_boolean param2)@ 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. Abstract class StatemachineInterface
- Each generated state machine implements the interface @StatemachineInterface@:
- bc(prettyprint)..
- package org.yakindu.sct.examples.trafficlight.cyclebased;
- #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;
- };
- 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 value. 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.
- ==<!-- 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. Timed 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. ==<!-- Java: It may use the @TimerService@, an @ITimerService@ implementation that is also generated. -->==
- @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 state machines.
- */
- 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 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)@ is 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). Interfaces, Variable and Event access
- ==<!-- FIXME: It should be made clear what a statechart interface is, in contrast to e. g. am interface in a programming language. -->==
- In a YAKINDU statechart, variables and events are contained in *interfaces*. There can be a single default, unnamed interface plus zero or more named interfaces. In the generated C++ code, these interfaces are defined as internal subclasses inside of the main state machine class. Let's have a look at the following sample statechart interface declaration:
- bc(prettyprint)..
- interface:
- var a:boolean
- in event evA:boolean
- out event evB:integer
- p. The generated interface code looks like following:
- bc(prettyprint)..
- //! Inner class for SCInterface interface scope.
- class SCInterface {
-
- public:
- /*! Gets the value of the variable 'a' that is defined in the default interface scope. */
- sc_boolean get_a();
-
- /*! Sets the value of the variable 'a' that is defined in the default interface scope. */
- void set_a(sc_boolean value);
-
- /*! Raises the in event 'evA' that is defined in the default interface scope. */
- void raise_evA(sc_boolean value);
-
- /*! Checks if the out event 'evB' that is defined in the default interface scope has been raised. */
- sc_boolean isRaised_evB();
-
- /*! Gets the value of the out event 'evB' that is defined in the default interface scope. */
- sc_integer get_evB_value();
-
-
- private:
- friend class Default;
- sc_boolean a;
- sc_boolean evA_raised;
- sc_boolean evA_value;
- sc_boolean evB_raised;
- sc_integer evB_value;
- };
- p. The anonymous interface in a statechart is generated as the C++ class @SCInterface@. An incoming event _evA_ 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_ 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 boolean value of the event. For variables, the code generator creates getter and setter methods. Additionally, the enclosing interface contains getter methods to acquire nested interfaces.
- The nesting interface is implemented by the state machine itself. Each nested interface is implemented as an internal class. The nesting class holds an instance of each nested interface class implementation and provides them via getter methods. Have a look at the code snipped generated from the unnamed default interface implementation:
- bc(prettyprint)..
- void Default::SCInterface::raise_evA(sc_boolean value) {
- evA_value = value;
- evA_raised = true;
- }
- sc_boolean Default::SCInterface::isRaised_evB() {
- return evB_raised;
- }
- sc_integer Default::SCInterface::get_evB_value() {
- return evB_value;
- }
- sc_boolean Default::SCInterface::get_a() {
- return a;
- }
- void Default::SCInterface::set_a(sc_boolean value) {
- a = value;
- }
- p. The name of the default, unnamed statechart interface class is generated as @SCInterface@. If a statechart interface has a dedicated name, e. g. _MyInterface_, then the C++ class name will be the statechart interface's name, prepended with string @SCI@, e. g. @SCIMyInterface@.
- 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 _default.h_ header file:
- bc(prettyprint)..
- //! Inner class for default interface scope operation callbacks.
- class DefaultSCI_OCB {
- public:
- virtual sc_integer myOp(sc_integer param1, sc_boolean param2) = 0;
- };
- /*! Set the working instance of the operation callback interface 'DefaultSCI_OCB'. */
- void setDefaultSCI_OCB(DefaultSCI_OCB* operationCallback);
- p. An additional interface @DefaultSCI_OCB@ with the pure virtual function @myOp(sc_integer param1, sc_boolean param2)@ 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 @setDefaultSCI_OCB(DefaultSCI_OCB* operationCallback)@ function, so that the state machine can use it.
- bc(prettyprint)..
- #include "default.h"
- sc_integer Default::DefaultSCI_OCB::myOp(sc_integer param1, sc_boolean param2) {
- // Your operation code should be placed here;
- return 0;
- }
- int main(int argc, char *argv[]) {
- Default *defaultSM = new Default();
- DefaultSCI_OCB *defaultSCI_OCB = new DefaultSCI_OCB();
- defaultSM->setDefaultSCI_OCB(defaultSCI_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++. -->==
|