reference.textile 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  1. h1(#YAKINDUStatechartToolsReference). YAKINDU Statechart Tools Reference
  2. h2. Statechart elements
  3. 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.
  4. The YAKINDU SCT 2 meta model is designed similar to the UML statechart meta model with the following differences:
  5. * SCT statecharts are self-contained with interfaces defined by events and variables.
  6. * Core execution semantics are cycle-driven, not event-driven.
  7. ** This allows to process concurrent events.
  8. ** Event-driven behavior can be defined on top.
  9. * Time is an abstract concept for statecharts.
  10. * Time control is delegated to the environment.
  11. The model interpreter and different flavors of generated code are following these same core semantics.
  12. Please refer to the Wikipedia article "UML state machine":http://en.wikipedia.org/wiki/UML_state_machine for more details.
  13. h3(#Regions). Regions
  14. 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.
  15. !images/parallelRegions.jpg(Parallel regions)!
  16. h3(#States). States
  17. 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.
  18. h3(#Transitions). Transitions
  19. 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.
  20. 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.
  21. 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.
  22. h3(#Initialstateandfinalstate). Initial state and final state
  23. 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.
  24. 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.
  25. Within a region, only a single initial state is allowed, but each region may have its own initial state.
  26. h3(#Choice). Choice
  27. 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.
  28. Usually the first transition points towards the choice node. One of the choice's outgoing transitions can carry a condition.
  29. h3(#CompositeState). Composite states
  30. A composite state is a state comprising one or more state machines. These state machines are also organized in regions within the composite state.
  31. Besides the simple composite state YAKINDU SCT knows about two kinds of composite states: orthogonal states and submachine states.
  32. Composite states contain other state machine branches.
  33. h4(#Orthogonalstates). Orthogonal states
  34. 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:
  35. !images/orthogonalState_example.jpg(Orthogonal states)!
  36. h4(#Submachinestates). Subdiagrams
  37. 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.
  38. !images/extract_subdiagram.png(Composite state)!
  39. 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.
  40. !images/extract_subdiagram2.png(Subdiagram popup window)!
  41. 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.
  42. !images/extract_subdiagram3.png(Subdiagram editor)!
  43. h3(#ShallowHistory). Shallow history
  44. 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.
  45. The following example, showing the answering of a questionaire, explains this:
  46. !images/shallowHistory01.jpg(Shallow history [1])!
  47. 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.
  48. !images/shallowHistory02.jpg(Shallow history [2])!
  49. !images/shallowHistory03.jpg(Shallow history [3])!
  50. When the _goon_ event is triggered, the most recent active state inside of the composite state *answeringQuestions* is activated again.
  51. h3(#DeepHistory). Deep history
  52. Deep history is similar to shallow history, but more complex. With a deep history the latest state of multiple nested states is remembered.
  53. h2(#Statechartdescriptionlanguage). Statechart description language
  54. A textual description language is used to declare and describe behaviors in a state machine. It is case sensitive.
  55. h3(#Typesystem). Type system
  56. The language has a small integrated type system consisting of the following simple types:
  57. * integer
  58. * real
  59. * boolean
  60. * string
  61. * void
  62. Events and variables can be declared using types:
  63. bc(prettyprint)..
  64. var intVar : integer
  65. var realVar : real
  66. var boolVar : boolean
  67. var stringVar : string
  68. event addInt : integer
  69. event addReal : real
  70. event checkValidity : boolean
  71. event stringEvent : string
  72. event voidEvent : void
  73. h3(#Expressions). Expressions
  74. 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.
  75. The type of a logical expression is *boolean*.
  76. h4(#LogicalAND). Logical AND
  77. bc(prettyprint)..
  78. var1 && var2
  79. h4(#LogicalOR). Logical OR
  80. bc(prettyprint)..
  81. var1 || var2
  82. h4(#LogicalNOT). Logical NOT
  83. bc(prettyprint)..
  84. !var1
  85. h4(#Conditionalexpression). Conditional expression
  86. bc(prettyprint)..
  87. var1 ? var2 : 23
  88. h4(#BitwiseXOR). Bitwise XOR
  89. bc(prettyprint)..
  90. var1 ^ var2
  91. h4(#BitwiseOR). Bitwise OR
  92. bc(prettyprint)..
  93. var1 | var2
  94. h4(#BitwiseAND). Bitwise AND
  95. bc(prettyprint)..
  96. var1 & var2
  97. h4(#LogicalRelationsandShiftOperators). Logical Relations and Shift Operators
  98. |less than | @<@ |
  99. |equal or less than | @<=@ |
  100. |greater than | @>@ |
  101. |equal or greater than | @>=@ |
  102. |equal | @==@ |
  103. |not equal | @!=@ |
  104. |shift left | @<<@ |
  105. |shift right | @>>@ |
  106. h4(#Binaryarithmeticoperators). Binary arithmetic operators
  107. |plus | @+@ |
  108. |minus | @-@ |
  109. |multiply | @*@ |
  110. |divide | @/@ |
  111. |modulo | @%@ |
  112. h4(#Unaryarithmeticoperators). Unary arithmetic operators
  113. |positive | @+@ |
  114. |negative | @-@ |
  115. |complement | @~@ |
  116. h3(#Statements). Statements
  117. A statement is one of three kinds:
  118. * assignment
  119. * event raising
  120. * operation call
  121. The language has the following assignment operators:
  122. </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>
  123. ==<!-- FIXME: The following sentences are broken somehow. -->==
  124. An event is raised by calling a method whose name consists of the word _raise_ followed by the event name, e.&nbsp;g. _raiseIncoming_call()_, and if it is an interface event the name of the interface.
  125. An operation is called similar to other programming languages with the operation name and passing concrete parameters. The parameters can be expressions.
  126. h3(#Scopes). Scopes
  127. ==<!-- Start stext_keyword_namespace -->==
  128. h4(#Namespace). Namespace
  129. The language allows to define unique namespaces which can be used to qualify references to the statechart.
  130. bc(prettyprint)..
  131. namespace trafficlights
  132. p. ==<!-- End stext_keyword_namespace -->==
  133. ==<!-- Start stext_keyword_interface -->==
  134. h4(#interfacescope). Interface scope
  135. Declarations in the interface scope are externally visible. They can be shared within the environment.
  136. bc(prettyprint)..
  137. interface NamedInterface:
  138. in event event1
  139. out event event3 : integer
  140. var variable1 : integer
  141. p. ==<!-- End stext_keyword_interface -->==
  142. ==<!-- Start stext_keyword_internal -->==
  143. h4('internalscope). Internal scope
  144. Declarations made in an internal scope are visible to contained states only.
  145. bc(prettyprint)..
  146. internal:
  147. var localVariable1: integer
  148. event localEvent: integer
  149. local event localEvent2
  150. operation localOperation (int1 : integer, int2 : integer): integer
  151. localEvent2 / raise NamedInterface.event3 :
  152. localOperation(valueof(localEvent) , NamedInterface.variable1)
  153. p. ==<!-- End stext_keyword_internal -->==
  154. h3(#Declarations). Declarations
  155. Within scopes events, variables, operations, and local reactions can be declared.
  156. ==<!-- Start stext_keyword_event -->==
  157. h3(#Events). Events
  158. An event in an interface scope has a direction. It is either ingoing or outgoing:
  159. bc(prettyprint)..
  160. interface NamedInterface:
  161. in event event1
  162. out event event2
  163. p. An event in the local scope can carry variables:
  164. bc(prettyprint)..
  165. internal:
  166. event localEvent1 : integer
  167. p. A local event can have a value assignment:
  168. bc(prettyprint)..
  169. internal:
  170. event localEvent1: integer = 25
  171. p. ==<!-- End stext_keyword_event -->==
  172. ==<!-- Start stext_keyword_var -->==
  173. h3(#Variables). Variables
  174. Variables can have different visibilities. They can be visible for the environment:
  175. bc(prettyprint)..
  176. var variable1: real
  177. p. Variables can be *readonly* (constants):
  178. bc(prettyprint)..
  179. var readonly pi: real = 3.1415
  180. p. Variables can be referenced by the environment.
  181. bc(prettyprint)..
  182. var external variable3: integer = 34
  183. p. ==<!-- End stext_keyword_var -->==
  184. ==<!-- Start stext_keyword_const -->==
  185. h3(#Constants). Constants
  186. Variables can be immutable. For this special variable the keyword @const@ is used:
  187. bc(prettyprint)..
  188. const variable1: real
  189. p. ==<!-- End stext_keyword_const -->==
  190. h3(#ReactionTriggers). Reaction Triggers
  191. Actions are key constructs in state machines to model behavior. YAKINDU SCT 2 knows about the following kinds of actions.
  192. ==<!-- Start stext_keyword_after -->==
  193. h4(#after). after
  194. The _after_ trigger specifies a one-shot time event.
  195. 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.
  196. bc(prettyprint). after 20 s
  197. Structure:
  198. @after@ _@time@_ _@unit@_
  199. The time value may be a literal or an expression that returns an integer value.
  200. The time unit can be:
  201. * ==<!-- Start stext_keyword_s -->== s - seconds ==<!-- End stext_keyword_s -->==
  202. * ==<!-- Start stext_keyword_ms -->== ms - milliseconds ==<!-- End stext_keyword_ms -->==
  203. * ==<!-- Start stext_keyword_us -->== us - microseconds ==<!-- End stext_keyword_us -->==
  204. * ==<!-- Start stext_keyword_ns -->== ns - nanoseconds ==<!-- End stext_keyword_ns -->==
  205. p. ==<!-- End stext_keyword_after -->==
  206. ==<!-- Start stext_keyword_every -->==
  207. h4(#every). every
  208. The _every_ trigger specifies periodic time events.
  209. 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.
  210. bc(prettyprint). every 200 ms
  211. Structure:
  212. @every@ _@time@_ _@unit@_
  213. The time value may be a literal or an expression that returns an integer value.
  214. The time unit can be:
  215. * s - seconds
  216. * ms - milliseconds
  217. * us - microseconds
  218. * ns - nanoseconds
  219. ==<!-- End stext_keyword_every -->==
  220. ==<!-- Start stext_keyword_always -->==
  221. h4(#always). always
  222. This trigger is always true and enables a reaction to be executed in every run-to-completion step (RTC). It is equivalent to _oncycle_.
  223. ==<!-- End stext_keyword_always -->==
  224. ==<!-- Start stext_keyword_default -->==
  225. ==<!-- Start stext_keyword_else -->==
  226. h4(#defaultelse). default, else
  227. 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.
  228. ==<!-- End stext_keyword_else -->==
  229. ==<!-- End stext_keyword_default -->==
  230. ==<!-- Start stext_keyword_entry -->==
  231. h4(#entry). entry
  232. An _entry_ trigger marks actions that are carried out on entering a state or state machine.
  233. ==<!-- End stext_keyword_entry -->==
  234. ==<!-- Start stext_keyword_exit -->==
  235. h4(#exit). exit
  236. An _exit_ trigger marks actions that are carried out on exiting a state or state machine.
  237. ==<!-- End stext_keyword_exit -->==
  238. ==<!-- Start stext_keyword_oncycle -->==
  239. h4(#oncycle). oncycle
  240. 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_.
  241. ==<!-- End stext_keyword_oncycle -->==
  242. ==<!-- Start stext_keyword_operation -->==
  243. h3(#Operations). Operations
  244. 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.
  245. bc(prettyprint)..
  246. operation localOperation (xValue : integer, yValue : integer):integer
  247. p.
  248. ==<!-- End stext_keyword_operation -->==
  249. h3(#BuildInFunctions). Build-in functions
  250. ==<!-- Start stext_keyword_valueof -->==
  251. h4(#valueofevent). valueof(event)
  252. ==<!-- FIXME: Clarify/elaborate the meaning of the following sentence: -->==
  253. Returns the value of an valued event that it passed to the function as parameter.
  254. bc(prettyprint)..
  255. myVar = valueof(myEvent)
  256. p.
  257. ==<!-- End stext_keyword_valueof -->==
  258. ==<!-- Start stext_keyword_as -->==
  259. h4(#as). as
  260. Casts a variable. The following example casts a literal from integer to real.
  261. bc(prettyprint)..
  262. myReal = 12 as real
  263. p.
  264. ==<!-- End stext_keyword_as -->==
  265. ==<!-- Start stext_keyword_active -->==
  266. h4(#activestate). active(state)
  267. Returns _true_ if a state is active and _false_ otherwise.
  268. bc(prettyprint)..
  269. myBool = active(StateA)
  270. p.
  271. ==<!-- End stext_keyword_active -->==
  272. h3(#LocalReactions). Local reactions
  273. Local reactions describe the internal behavior of a state. So they have internal scope. A local reaction is declared as follows:
  274. bc(prettyprint)..
  275. LocalReaction: ReactionTrigger '/' ReactionEffect ('#' ReactionProperties)?
  276. ReactionTrigger: (Event ("," Event )* (=> '[' Expression ']')?) | '[' Expression ']'
  277. ReactionEffect: Statement (';' Statement )* (';')?
  278. Statement: Assignment | EventRaising | OperationCall
  279. ReactionProperties: (EntryPoint | ExitPoint)*
  280. p. Within a local reaction an interface event can be raised:
  281. bc(prettyprint)..
  282. internal:
  283. localEvent1 / raise NamedInterface.event3 : localOperation (valueof(localEvent), NamedInterface.variable1);
  284. 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:
  285. ==<!-- FIXME: Describe the meaning of priorities! -->==
  286. bc(prettyprint#GeneratorFeatures)..
  287. localEvent2 / NamedInterface.variable2 += 3; #1
  288. localEvent3 / NamedInterface.variable4 += 2.0; #2
  289. h2(#Codegeneration). SGen generator features
  290. 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.
  291. To get started with the generator model, YAKINDU Statechart Tools includes a wizard that creates a basic configuration file with default values.
  292. !images/sGenEditor.png(SGen generator model with default values)!
  293. ==<!-- FIXME: Explain what a "builder" is! -->==
  294. 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.
  295. The following section describes the *Core Features* which are available for all code generators:
  296. ==<!-- Start sgen_feature_outlet -->==
  297. h4(#Outlet). Outlet
  298. The *Outlet* feature specifies target project and target folder for the generated artifacts. It is a _required_ feature and has the following parameters:
  299. # __targetProject__ (String, required): The project to store the generated artifacts to.
  300. # __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.
  301. # __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.
  302. Sample configuration:
  303. bc(prettyprint)..
  304. feature Outlet {
  305. targetProject = "SampleProject"
  306. targetFolder = "src-gen"
  307. libraryTargetFolder = "src"
  308. }
  309. p. ==<!-- End sgen_feature_outlet -->==
  310. ==<!-- Start sgen_feature_licenseheader -->==
  311. h4(#LicenseHeader). LicenseHeader
  312. 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:
  313. # __licenseText__ (String, required): License text to be added as a file header
  314. Sample configuration:
  315. bc(prettyprint)..
  316. feature LicenseHeader {
  317. licenseText = "Copyright (c) 2012 committers of YAKINDU and others."
  318. }
  319. p. ==<!-- End sgen_feature_licenseheader -->==
  320. ==<!-- Start sgen_feature_functioninlining -->==
  321. h4(#FunctionInlining). FunctionInlining
  322. 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.
  323. It is an *optional* feature and has the following parameters:
  324. # __inlineReactions__ (Boolean, optional): inlines the expression for reactions
  325. # __inlineEntryActions__ (Boolean, optional): inlines the expression for entry actions
  326. # __inlineExitActions__ (Boolean, optional): inlines the expression for exit actions
  327. # __inlineEnterSequences__ (Boolean, optional): inlines the expression for enter sequences
  328. # __inlineExitSequences__ (Boolean, optional): inlines the expression for exit sequences
  329. # __inlineChoices__ (Boolean, optional): inlines the expression for choices
  330. # __inlineEnterRegion__ (Boolean, optional): inlines the expression for enter regions
  331. # __inlineExitRegion__ (Boolean, optional): inlines the expression for exit regions
  332. # __inlineEntries__ (Boolean, optional): inlines the expression for entries
  333. Sample configuration:
  334. bc(prettyprint)..
  335. feature FunctionInlining {
  336. inlineChoices = false
  337. inlineEnterRegion = true
  338. inlineEntries = true
  339. }
  340. p. ==<!-- End sgen_feature_functioninlining -->==
  341. ==<!-- Start sgen_feature_debug -->==
  342. h4(#Debug). Debug
  343. 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:
  344. # __dumpSexec__ (Boolean, required): dumps the execution model as XMI model
  345. Sample configuration:
  346. bc(prettyprint)..
  347. feature Debug {
  348. dumpSexec = true
  349. }
  350. p. ==<!-- End sgen_feature_debug -->==
  351. h2(#JavaGeneratorFeatures). Java generator features
  352. ==<!-- Start sgen_feature_naming -->==
  353. h4. Naming feature
  354. The *Naming* feature allows the configuration of package names as well as class name prefix / suffix.
  355. It is an *optional* feature and has the following parameters:
  356. # __basePackage__ (Boolean, required): The package to create for the generated java classes
  357. # __implementationSuffix__ (Boolean, optional): The suffix for the implementing classes
  358. Sample configuration:
  359. bc(prettyprint)..
  360. feature Naming {
  361. basePackage = "org.yakindu.sct"
  362. implementationSuffix = "Impl"
  363. }
  364. p. ==<!-- End sgen_feature_naming -->==
  365. ==<!-- Start sgen_feature_runnablewrapper -->==
  366. h4. RunnableWrapper
  367. 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.
  368. It is an *optional* feature and has the following parameters:
  369. # __namePrefix__ (String, optional): prefix of the implementing class' name
  370. # __nameSuffix__ (String, optional): suffix of the implementing class' name
  371. Sample configuration:
  372. ==<!-- FIXME: The namePrefix in the example below does not have a trailing dot. Is this correct? -->==
  373. bc(prettyprint)..
  374. feature RunnableWrapper {
  375. namePrefix = "org.yakindu.sct"
  376. nameSuffix = "Impl"
  377. }
  378. p. ==<!-- End sgen_feature_runnablewrapper -->==
  379. ==<!-- Start sgen_feature_generalfeatures -->==
  380. h4(#GeneralFeatures). GeneralFeatures
  381. 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:
  382. ==<!-- # __EventBasedStatemachine__ (Boolean, optional): enables/disables the generation of a cycle based state machine implementation -->==
  383. # __InterfaceObserverSupport__ (Boolean, optional): enables/disables the generation of listener interfaces for the state machine
  384. # __RuntimeService__ (Boolean, optional): enables/disables the generation of a runtime service that triggers the run cycle of a cycle-based state machine
  385. # __TimerService__ (Boolean, optional): enables/disables the generation of a timer service implementation using __java.util.Timer__
  386. ==<!-- # __GenericInterfaceSupport__ (Boolean, optional): enables/disables the generation of generic interfaces -->==
  387. ==<!-- # __StatemachineFactorySupport__ (Boolean, optional): enables/disables the generation of a factory class -->==
  388. Sample configuration:
  389. bc(prettyprint)..
  390. feature GeneralFeatures {
  391. InterfaceObserverSupport = true
  392. RuntimeService = true
  393. TimerService = true
  394. }
  395. p. ==<!-- End sgen_feature_generalfeatures -->==
  396. h2(#CGeneratorFeatures). C/C++ generator features
  397. ==<!-- Start sgen_feature_identifiersettings -->==
  398. h4. IdentifierSettings
  399. The *IdentifierSettings* feature allows the configuration of module names and identifier character length:
  400. # __moduleName__ (String, optional): name for header and implementation, default: statechart name
  401. # __statemachinePrefix__ (Boolean, optional): prefix which is prepended to function, state, and type names.
  402. # __maxIdentifierLength__ (Integer, optional): maximum number of characters of an identifier, default: 31 characters, which is complying with the ANSI C99 standard.
  403. # __separator__ (String, optional): character to replace whitespace and otherwise illegal characters in manes.
  404. Sample configuration:
  405. bc(prettyprint)..
  406. feature IdentifierSettings {
  407. moduleName = "MyStatechart"
  408. statemachinePrefix = "myStatechart"
  409. maxIdentifierLength = 31
  410. separator = "_"
  411. }
  412. p. ==<!-- End sgen_feature_identifiersettings -->==
  413. ==<!-- Start sgen_feature_tracing -->==
  414. h4. Tracing
  415. The *Tracing* feature allows to enable generation of tracing callback functions:
  416. # __enterState__ (Boolean, optional): whether to generate a callback that is used to notify about 'state enter' events.
  417. # __exitState__ (Boolean, optional): whether to generate a callback that is used to notify about 'state exit' events.
  418. Sample configuration:
  419. bc(prettyprint)..
  420. feature Tracing {
  421. enterState = true
  422. exitState = true
  423. }
  424. p. ==<!-- End sgen_feature_tracing -->==
  425. ==<!-- Start sgen_feature_generatoroptions -->==
  426. h4. GeneratorOptions
  427. The *GeneratorOptions* feature allows change the behavior of the C++ generator:
  428. # __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.
  429. # __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.
  430. Sample configuration:
  431. bc(prettyprint)..
  432. feature GeneratorOptions {
  433. innerFunctionVisibility = "protected"
  434. staticOperationCallback = true
  435. }
  436. p. ==<!-- End sgen_feature_generatoroptions -->==
  437. ==<!-- Start sgen_feature_junitwrapper -->==
  438. h4. JUnitWrapper
  439. Using the *JUnitWrapper* feature it is possible to create JUnit tests that will run the generated gtests.
  440. # __WrapToJUnit__ (Boolean): This parameter determines whether a JUnit wrapper test is to be generated __(true)__ or not __(false)__.
  441. Sample configuration:
  442. bc(prettyprint)..
  443. feature JUnitWrapper {
  444. WrapToJUnit = "false"
  445. }
  446. p. ==<!-- End sgen_feature_junitwrapper -->==
  447. h2(#CreatingCustomCodeGenerators). Creating custom code generators
  448. 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.
  449. h3(#WritingacustomcodegeneratorwithXtend2Java). Writing a custom code generator with Xtend2/Java
  450. 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.
  451. !images/xtendGenerator.png(Creating an Xtend2 generator project)!
  452. 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.
  453. 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.
  454. 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].
  455. h3(#ExecutingacustomXtend2Javacodegenerator). Executing a custom Xtend2/Java code generator
  456. YAKINDU Statechart Tools provide a convenient way to execute your generator while you are developing it.
  457. 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.
  458. ==<!-- Start sgen_feature_generator -->==
  459. h4(#Generator). Generator
  460. 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:
  461. # __generatorProject__ (String, required): the name of the generator project
  462. # __generatorClass__ (String, required): the fully-qualified name of the code generator class
  463. # __configurationModule__ (String, optional): the fully-qualified class name of a Guice module to configure the code generator
  464. Sample configuration:
  465. bc(prettyprint)..
  466. feature Generator {
  467. generatorProject = "org.yakindu.sct.mygenerator"
  468. generatorClass = "org.yakindu.sct.MyGenerator"
  469. }
  470. p. ==<!-- End sgen_feature_generator -->==
  471. h3(#ExecutingacustomXpandcodegenerator). Executing a custom Xpand code generator
  472. 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.
  473. ==<!-- Start sgen_feature_template -->==
  474. h4(#Template). Template
  475. 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:
  476. # __templateProject__ (String, required): the name of the generator project
  477. # __templatePath__ (String, required): the fully-qualified template path of the main template
  478. Sample configuration:
  479. bc(prettyprint)..
  480. feature Template {
  481. templateProject = "ExampleProject"
  482. templatePath = "org::yakindu::sct::generator::xpand::Main::main"
  483. }
  484. p. ==<!-- End sgen_feature_template -->==
  485. h2(#APISpecification). API specifications of the generated code
  486. 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").
  487. !(img-rounded shadowed#SpecJava)images/TrafficLight.png(The traffic light model)!
  488. h3(#JavaSpec). Specifications of Java code
  489. 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.
  490. To execute the Java example, run the file _CrossingDemoCycleBased.java_ as "Java Application" from the Eclipse _Run As_ context menu.
  491. h4(#JavaGeneratedCode). Generated code files
  492. You will find the generated code in the _src-gen_ folder of the traffic light example.
  493. 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.
  494. h4. Interface IStatemachine
  495. Each generated state machine implements the interface @IStatemachine@:
  496. bc(prettyprint)..
  497. package org.yakindu.sct.examples.trafficlight.cyclebased;
  498. /**
  499. * Basic interface for state machines.
  500. *
  501. *
  502. */
  503. public interface IStatemachine {
  504. /**
  505. * Initializes the state machine. Use to init internal variables etc.
  506. */
  507. public void init();
  508. /**
  509. * Enters the state machine. Sets the state machine in a defined state.
  510. */
  511. public void enter();
  512. /**
  513. * Exits the state machine. Leaves the state machine with a defined state.
  514. */
  515. public void exit();
  516. /**
  517. * Start a run-to-completion cycle.
  518. */
  519. public void runCycle();
  520. }
  521. h5. Fundamental statechart methods
  522. 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.
  523. The @IStatemachine@ interface specifies the four methods @init()@, @enter()@, @exit()@ and @runCycle()@.
  524. * 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.
  525. * The @enter()@ method must be called to enter the state machine. It brings the state machine to a well-defined state.
  526. * 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.
  527. * 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:
  528. # Clear list of outgoing events.
  529. # Check whether events have occurred which are leading to a state change.
  530. # If a state change has to be done:
  531. ## Execute exit actions of the present state.
  532. ## Save history state, if necessary.
  533. ## Make the new state active. ==<!-- FIXME: We should also make the old state inactive, shouldn't we? -->==
  534. ## Execute entry actions of the new state.
  535. # Clear list of incoming events.
  536. ==<!-- h5. Variable and event access -->==
  537. ==<!-- Do we need some equivalent to the C section here? Here's the C text: -->==
  538. ==<!-- 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)@. -->==
  539. h4. Timed state machines
  540. If a statechart uses timing functionality, additional classes are generated.
  541. 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.
  542. 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.
  543. @ITimedStatemachine@ also specifies the callback method @onTimeEventRaised(TimeEvent timeEvent)@, enabling the timer service to raise time events.
  544. bc(prettyprint)..
  545. package org.yakindu.sct.examples.trafficlight.cyclebased;
  546. /**
  547. * Interface for state machines which use timed event triggers.
  548. */
  549. public interface ITimedStatemachine {
  550. /**
  551. * Set the {@link ITimerService} for the state machine. It must be set
  552. * externally on a timed state machine before a run cycle can be correct
  553. * executed.
  554. *
  555. * @param timerService
  556. */
  557. public void setTimerService(ITimerService timerService);
  558. /**
  559. * Returns the currently used timer service.
  560. *
  561. * @return {@link ITimerService}
  562. */
  563. public ITimerService getTimerService();
  564. /**
  565. * Callback method if a {@link TimeEvent} occurred.
  566. *
  567. * @param timeEvent
  568. */
  569. public void onTimeEventRaised(TimeEvent timeEvent);
  570. }
  571. 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@.
  572. 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:
  573. bc(prettyprint)..
  574. package org.yakindu.sct.examples.trafficlight.cyclebased;
  575. /**
  576. * Interface a timer service has to implement. Use to implement your own timer
  577. * service. A timer service has to be added to a timed state machine.
  578. *
  579. */
  580. public interface ITimerService {
  581. /**
  582. * Starts the timing for a given {@link TimeEvent}.
  583. *
  584. * @param event
  585. * : The TimeEvent the timer service should throw if timed out.
  586. * @param time
  587. * : Time in milliseconds after the given time event should be
  588. * triggered
  589. * @param cycleStartTime
  590. * : The absolute start time in milliseconds at which the last
  591. * run cycle was called. Can be used to produce a more accurate
  592. * timing behavior.
  593. */
  594. public void setTimer(TimeEvent event, long time, long cycleStartTime);
  595. /**
  596. * Unset the given {@link TimeEvent}. Use to unset cyclic repeated time
  597. * events.
  598. *
  599. * @param event
  600. */
  601. public void resetTimer(TimeEvent event);
  602. /**
  603. * Cancel timer service. Use this to end possible timing threads and free
  604. * memory resources.
  605. */
  606. public void cancel();
  607. /**
  608. * Returns the system time in milliseconds.
  609. *
  610. * @return the difference, measured in milliseconds, between the current
  611. * time and a defined point of time in the past.
  612. */
  613. public long getSystemTimeMillis();
  614. }
  615. p. The @ITimerService@ interface defines the following methods dealing with timing functionality:
  616. h5. Method setTimer
  617. 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.
  618. 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.
  619. h5. Method resetTimer
  620. p. The state machine calls the method @resetTimer(TimeEvent event)@ to notify the timer service to reset the timer for the given event.
  621. h5. Method onTimeEventRaised
  622. 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.
  623. The time event is recognized by the state machine and will be processed during the next run cycle.
  624. 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.
  625. h5. Class TimeEvent
  626. p. An important class used by timed state machines is @TimeEvent@:
  627. bc(prettyprint)..
  628. package org.yakindu.sct.examples.trafficlight.cyclebased;
  629. /**
  630. * Event that reflects a time event. It's internally used by
  631. * {@link ITimedStatemachine}.
  632. *
  633. * @author muehlbrandt
  634. *
  635. * @param <T>
  636. */
  637. public class TimeEvent {
  638. private boolean periodic;
  639. private ITimedStatemachine statemachine;
  640. int index;
  641. /**
  642. * Constructor for a time event.
  643. *
  644. * @param periodic
  645. * : Set to {@code true} if event should be repeated
  646. * periodically.
  647. *
  648. * @param index
  649. * : Index position within the state machine's timeEvent array.
  650. */
  651. public TimeEvent(boolean periodic, int index) {
  652. this.periodic = periodic;
  653. this.index = index;
  654. }
  655. /**
  656. * Returns the state machine reference of the event.
  657. *
  658. */
  659. public ITimedStatemachine getStatemachine() {
  660. return statemachine;
  661. }
  662. /**
  663. * Sets the state machine reference of the event.
  664. *
  665. * @param statemachine
  666. */
  667. public void setStatemachine(ITimedStatemachine statemachine) {
  668. this.statemachine = statemachine;
  669. }
  670. public boolean isPeriodic() {
  671. return periodic;
  672. }
  673. public int getIndex() {
  674. return index;
  675. }
  676. }
  677. 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.
  678. h4. Default implementation of ITimerService
  679. 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.
  680. bc(prettyprint)..
  681. package org.yakindu.sct.examples.trafficlight.cyclebased;
  682. import java.util.HashMap;
  683. import java.util.Map;
  684. import java.util.Timer;
  685. import java.util.TimerTask;
  686. /**
  687. * Default timer service implementation.
  688. *
  689. */
  690. public class TimerService implements ITimerService {
  691. private final Timer timer = new Timer();
  692. private final Map<TimeEvent, TimerTask> timerTaskMap = new HashMap<TimeEvent, TimerTask>();
  693. public void setTimer(final TimeEvent event, long time,
  694. long cycleStartTime) {
  695. // Reset existing TimerTask for event. This step isn't necessary if
  696. // timer tasks are properly reset by sexec model.
  697. if (timerTaskMap.containsKey(event)) {
  698. resetTimer(event);
  699. }
  700. // Create a new TimerTask for given event.
  701. timerTaskMap.put(event, new TimerTask() {
  702. @Override
  703. public void run() {
  704. event.getStatemachine().onTimeEventRaised(event);
  705. }
  706. });
  707. // start scheduling the timer
  708. if (event.isPeriodic()) {
  709. timer.scheduleAtFixedRate(timerTaskMap.get(event),
  710. time - (System.currentTimeMillis() - cycleStartTime), time);
  711. } else {
  712. timer.schedule(timerTaskMap.get(event),
  713. time - (System.currentTimeMillis() - cycleStartTime));
  714. }
  715. }
  716. public void resetTimer(TimeEvent event) {
  717. if (timerTaskMap.containsKey(event) && timerTaskMap.get(event) != null) {
  718. timerTaskMap.get(event).cancel();
  719. timer.purge();
  720. }
  721. timerTaskMap.remove(event);
  722. }
  723. public void cancel() {
  724. timer.cancel();
  725. timer.purge();
  726. }
  727. public long getSystemTimeMillis() {
  728. return System.currentTimeMillis();
  729. }
  730. }
  731. h4(#RuntimeService). Runtime service
  732. The runtime service class can be used by client implementations to execute a run-to-completion step of a state machine periodically.
  733. ==<!-- FIXME: Information seems to be missing here. Where and how could/should I use a runtime service class? -->==
  734. h4(#JavaInterVar). Interfaces, Variable and Event access
  735. ==<!-- FIXME: It should be made clear what a statechart interface is, in contrast to e. g. am interface in a programming language. -->==
  736. 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:
  737. bc(prettyprint)..
  738. interface:
  739. var a:boolean
  740. in event evA:boolean
  741. out event evB:integer
  742. p. The generated interface code looks like this:
  743. bc(prettyprint)..
  744. public interface IDefaultSMStatemachine extends IStatemachine {
  745. public interface SCInterface {
  746. public void raiseEvA(boolean value);
  747. public boolean isRaisedEvB();
  748. public int getEvBValue();
  749. public boolean getA();
  750. public void setA(boolean value);
  751. }
  752. 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.
  753. 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:
  754. bc(prettyprint)..
  755. public class DefaultSMStatemachine implements IDefaultSMStatemachine {
  756. private final class SCInterfaceImpl implements SCInterface {
  757. private boolean evA;
  758. private boolean evAValue;
  759. public void raiseEvA(boolean value) {
  760. evA = true;
  761. evAValue = value;
  762. }
  763. private boolean getEvAValue() {
  764. if (!evA)
  765. throw new IllegalStateException(
  766. "Illegal event value acces. Event EvA is not raised!");
  767. return evAValue;
  768. }
  769. private boolean evB;
  770. private int evBValue;
  771. public boolean isRaisedEvB() {
  772. return evB;
  773. }
  774. private void raiseEvB(int value) {
  775. evB = true;
  776. evBValue = value;
  777. }
  778. public int getEvBValue() {
  779. if (!evB)
  780. throw new IllegalStateException(
  781. "Illegal event value acces. Event EvB is not raised!");
  782. return evBValue;
  783. }
  784. private boolean a;
  785. public boolean getA() {
  786. return a;
  787. }
  788. public void setA(boolean value) {
  789. this.a = value;
  790. }
  791. public void clearEvents() {
  792. evA = false;
  793. }
  794. public void clearOutEvents() {
  795. evB = false;
  796. }
  797. }
  798. private SCInterfaceImpl sCInterface;
  799. public DefaultSMStatemachine() {
  800. sCInterface = new SCInterfaceImpl();
  801. }
  802. public SCInterface getSCInterface() {
  803. return sCInterface;
  804. }
  805. }
  806. p. The name of the default, unnamed statechart interface is generated as @SCInterface@. If a statechart interface has a dedicated name, e.&nbsp;g. _MyInterface_, then the Java interface name will be the statechart interface's name, prepended with string @SCI@, e.&nbsp;g. @SCIMyInterface@.
  807. 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.
  808. h4(#JavaInterfaceObservers). Interface observers
  809. If the general feature _InterfaceObserverSupport_ is enabled in the SGen model, the generated interfaces will support the registration of observers:
  810. bc(prettyprint)..
  811. public interface IDefaultSMStatemachine extends IStatemachine {
  812. public interface SCInterface {
  813. public void raiseEvA(boolean value);
  814. public boolean isRaisedEvB();
  815. public int getEvBValue();
  816. public boolean getA();
  817. public void setA(boolean value);
  818. public List<SCInterfaceListener> getListeners();
  819. }
  820. public interface SCInterfaceListener {
  821. public void onEvBRaised(int value);
  822. }
  823. public SCInterface getSCInterface();
  824. }
  825. 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.
  826. h4(#JavaOperationCallbacks). Operation callbacks
  827. 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:
  828. !images/OperationExample.png(Specifying an operation callback in the model)!
  829. Let's have a look at the generated code:
  830. bc(prettyprint)..
  831. public interface IDefaultSMStatemachine extends IStatemachine {
  832. public interface SCInterface {
  833. public void raiseEvA(boolean value);
  834. public boolean isRaisedEvB();
  835. public int getEvBValue();
  836. public boolean getA();
  837. public void setA(boolean value);
  838. public void setSCInterfaceOperationCallback(
  839. SCInterfaceOperationCallback operationCallback);
  840. }
  841. public interface SCInterfaceOperationCallback {
  842. public int myOperation(int param1, boolean param2);
  843. }
  844. public SCInterface getSCInterface();
  845. }
  846. 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.
  847. bc(prettyprint)..
  848. public static void main(String[] args) {
  849. DefaultSMStatemachine statemachine = new DefaultSMStatemachine();
  850. SCInterfaceOperationCallback callback = new SCInterfaceOperationCallback() {
  851. @Override
  852. public int myOperation(int param1, boolean param2) {
  853. // Your operation code should be placed here;
  854. return 0;
  855. }
  856. };
  857. statemachine.getSCInterface().setSCInterfaceOperationCallback(callback);
  858. statemachine.init();
  859. statemachine.enter();
  860. statemachine.runCycle();
  861. }
  862. h4(#JavaIntegratingGeneratedCode). Integrating generated code
  863. 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@:
  864. bc(prettyprint)..
  865. public static void main(String[] args) {
  866. new CrossingDemoCycleBased().runTrafficLight();
  867. }
  868. p. A new instance of the class is created and the method @runTrafficLight()@ is called. This method can be found in the superclass:
  869. bc(prettyprint)..
  870. public void runTrafficLight() {
  871. setUpAndRunStatemachine();
  872. createUIContent();
  873. shell.open();
  874. while (!shell.isDisposed()) {
  875. // update traffic lights
  876. readStatemachineOutput();
  877. crossing.repaint();
  878. if (!display.readAndDispatch()) {
  879. display.sleep();
  880. }
  881. }
  882. tearDownStatemachine();
  883. }
  884. 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()@:
  885. bc(prettyprint)..
  886. protected void setUpAndRunStatemachine() {
  887. statemachine = new TrafficLightWaitingStatemachine();
  888. statemachine.setTimerService(new TimerService());
  889. statemachine.init();
  890. statemachine.enter();
  891. RuntimeService.getInstance().registerStatemachine(statemachine, 100);
  892. }
  893. 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.
  894. 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.
  895. bc(prettyprint)..
  896. protected void readStatemachineOutput() {
  897. trafficLightFigure.setRed(statemachine.getSCITrafficLight()
  898. .getRed());
  899. trafficLightFigure.setYellow(statemachine.getSCITrafficLight()
  900. .getYellow());
  901. trafficLightFigure.setGreen(statemachine.getSCITrafficLight()
  902. .getGreen());
  903. pedestrianLightFigure.setWhite(statemachine.getSCIPedestrian()
  904. .getRequest());
  905. pedestrianLightFigure.setRed(statemachine.getSCIPedestrian()
  906. .getRed());
  907. pedestrianLightFigure.setGreen(statemachine.getSCIPedestrian()
  908. .getGreen());
  909. }
  910. 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.
  911. Hint: When outgoing events are raised within the state machine, they remain active until the next run-to-completion step is started.
  912. bc(prettyprint)..
  913. @Override
  914. protected void tearDownStatemachine() {
  915. // End TimerHandler and RuntimeService.
  916. statemachine.getTimerService().cancel();
  917. RuntimeService.getInstance().cancelTimer();
  918. }
  919. 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.
  920. h3(#SpecC). Specifications of C code
  921. 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.
  922. 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.
  923. h4(#CGeneratedCode). Generated code files
  924. You will find the generated code in the _src-gen_ folder of the traffic light example.
  925. The C code generator generates three header files. The first one is _sc_types.h_:
  926. bc(prettyprint)..
  927. #ifndef SC_TYPES_H_
  928. #define SC_TYPES_H_
  929. #ifdef __cplusplus
  930. extern "C" {
  931. #endif
  932. #include <stdint.h>
  933. #include <stdbool.h>
  934. typedef int_fast16_t sc_short;
  935. typedef uint_fast16_t sc_ushort;
  936. typedef int32_t sc_integer;
  937. typedef uint32_t sc_uinteger;
  938. typedef double sc_real;
  939. typedef char* sc_string;
  940. typedef void* sc_eventid;
  941. #ifdef __cplusplus
  942. }
  943. #endif
  944. #define sc_boolean bool
  945. #define bool_true true
  946. #define bool_false false
  947. #endif /* SC_TYPES_H_ */
  948. 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_:
  949. bc(prettyprint)..
  950. #ifndef TRAFFICLIGHTWAITING_H_
  951. #define TRAFFICLIGHTWAITING_H_
  952. #include "sc_types.h"
  953. #ifdef __cplusplus
  954. extern "C" {
  955. #endif
  956. /*! \file Header of the state machine 'TrafficLightWaiting'.
  957. */
  958. //! enumeration of all states
  959. typedef enum {
  960. TrafficLightWaiting_main_region_on ,
  961. TrafficLightWaiting_main_region_on_r1_StreetGreen ,
  962. TrafficLightWaiting_main_region_on_r1_PedWaiting ,
  963. TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOn ,
  964. TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOff ,
  965. TrafficLightWaiting_main_region_on_r1_StreetAttention ,
  966. TrafficLightWaiting_main_region_on_r1_StreetRed ,
  967. TrafficLightWaiting_main_region_on_r1_PedestrianGreen ,
  968. TrafficLightWaiting_main_region_on_r1_PedestrianRed ,
  969. TrafficLightWaiting_main_region_on_r1_StreetPrepared ,
  970. TrafficLightWaiting_main_region_off ,
  971. TrafficLightWaiting_main_region_off_r1_YellowOn ,
  972. TrafficLightWaiting_main_region_off_r1_YellowOff ,
  973. TrafficLightWaiting_last_state
  974. } TrafficLightWaitingStates;
  975. //! Type definition of the data structure for the TrafficLightWaitingIfaceTrafficLight interface scope.
  976. typedef struct {
  977. sc_boolean red;
  978. sc_boolean yellow;
  979. sc_boolean green;
  980. } TrafficLightWaitingIfaceTrafficLight;
  981. //! Type definition of the data structure for the TrafficLightWaitingIfacePedestrian interface scope.
  982. typedef struct {
  983. sc_boolean request;
  984. sc_boolean red;
  985. sc_boolean green;
  986. } TrafficLightWaitingIfacePedestrian;
  987. //! Type definition of the data structure for the TrafficLightWaitingIface interface scope.
  988. typedef struct {
  989. sc_boolean pedestrianRequest_raised;
  990. sc_boolean onOff_raised;
  991. } TrafficLightWaitingIface;
  992. //! Type definition of the data structure for the TrafficLightWaitingTimeEvents interface scope.
  993. typedef struct {
  994. sc_boolean TrafficLightWaiting_main_region_on_r1_PedWaiting_time_event_0_raised;
  995. sc_boolean TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOn_time_event_0_raised;
  996. sc_boolean TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOff_time_event_0_raised;
  997. sc_boolean TrafficLightWaiting_main_region_on_r1_StreetAttention_time_event_0_raised;
  998. sc_boolean TrafficLightWaiting_main_region_on_r1_StreetRed_time_event_0_raised;
  999. sc_boolean _main_region_on_r1_PedestrianGreen_time_event_0_raised;
  1000. sc_boolean TrafficLightWaiting_main_region_on_r1_PedestrianRed_time_event_0_raised;
  1001. sc_boolean TrafficLightWaiting_main_region_on_r1_StreetPrepared_time_event_0_raised;
  1002. sc_boolean TrafficLightWaiting_main_region_off_r1_YellowOn_time_event_0_raised;
  1003. sc_boolean TrafficLightWaiting_main_region_off_r1_YellowOff_time_event_0_raised;
  1004. } TrafficLightWaitingTimeEvents;
  1005. //! the maximum number of orthogonal states defines the dimension of the state configuration vector.
  1006. #define TRAFFICLIGHTWAITING_MAX_ORTHOGONAL_STATES 1
  1007. /*! Type definition of the data structure for the TrafficLightWaiting state machine.
  1008. This data structure has to be allocated by the client code. */
  1009. typedef struct {
  1010. TrafficLightWaitingStates stateConfVector[TRAFFICLIGHTWAITING_MAX_ORTHOGONAL_STATES];
  1011. sc_ushort stateConfVectorPosition;
  1012. TrafficLightWaitingIfaceTrafficLight ifaceTrafficLight;
  1013. TrafficLightWaitingIfacePedestrian ifacePedestrian;
  1014. TrafficLightWaitingIface iface;
  1015. TrafficLightWaitingTimeEvents timeEvents;
  1016. } TrafficLightWaiting;
  1017. /*! Initializes the TrafficLightWaiting state machine data structures. Must be called before first usage.*/
  1018. extern void trafficLightWaiting_init(TrafficLightWaiting* handle);
  1019. /*! Activates the state machine */
  1020. extern void trafficLightWaiting_enter(TrafficLightWaiting* handle);
  1021. /*! Deactivates the state machine */
  1022. extern void trafficLightWaiting_exit(TrafficLightWaiting* handle);
  1023. /*! Performs a 'run-to-completion' step. */
  1024. extern void trafficLightWaiting_runCycle(TrafficLightWaiting* handle);
  1025. /*! Raises a time event. */
  1026. extern void trafficLightWaiting_raiseTimeEvent(TrafficLightWaiting* handle, sc_eventid evid);
  1027. /*! Gets the value of the variable 'red' that is defined in the interface scope 'TrafficLight'. */
  1028. extern sc_boolean trafficLightWaitingIfaceTrafficLight_get_red(TrafficLightWaiting* handle);
  1029. /*! Sets the value of the variable 'red' that is defined in the interface scope 'TrafficLight'. */
  1030. extern void trafficLightWaitingIfaceTrafficLight_set_red(TrafficLightWaiting* handle, sc_boolean value);
  1031. /*! Gets the value of the variable 'yellow' that is defined in the interface scope 'TrafficLight'. */
  1032. extern sc_boolean trafficLightWaitingIfaceTrafficLight_get_yellow(TrafficLightWaiting* handle);
  1033. /*! Sets the value of the variable 'yellow' that is defined in the interface scope 'TrafficLight'. */
  1034. extern void trafficLightWaitingIfaceTrafficLight_set_yellow(TrafficLightWaiting* handle, sc_boolean value);
  1035. /*! Gets the value of the variable 'green' that is defined in the interface scope 'TrafficLight'. */
  1036. extern sc_boolean trafficLightWaitingIfaceTrafficLight_get_green(TrafficLightWaiting* handle);
  1037. /*! Sets the value of the variable 'green' that is defined in the interface scope 'TrafficLight'. */
  1038. extern void trafficLightWaitingIfaceTrafficLight_set_green(TrafficLightWaiting* handle, sc_boolean value);
  1039. /*! Gets the value of the variable 'request' that is defined in the interface scope 'Pedestrian'. */
  1040. extern sc_boolean trafficLightWaitingIfacePedestrian_get_request(TrafficLightWaiting* handle);
  1041. /*! Sets the value of the variable 'request' that is defined in the interface scope 'Pedestrian'. */
  1042. extern void trafficLightWaitingIfacePedestrian_set_request(TrafficLightWaiting* handle, sc_boolean value);
  1043. /*! Gets the value of the variable 'red' that is defined in the interface scope 'Pedestrian'. */
  1044. extern sc_boolean trafficLightWaitingIfacePedestrian_get_red(TrafficLightWaiting* handle);
  1045. /*! Sets the value of the variable 'red' that is defined in the interface scope 'Pedestrian'. */
  1046. extern void trafficLightWaitingIfacePedestrian_set_red(TrafficLightWaiting* handle, sc_boolean value);
  1047. /*! Gets the value of the variable 'green' that is defined in the interface scope 'Pedestrian'. */
  1048. extern sc_boolean trafficLightWaitingIfacePedestrian_get_green(TrafficLightWaiting* handle);
  1049. /*! Sets the value of the variable 'green' that is defined in the interface scope 'Pedestrian'. */
  1050. extern void trafficLightWaitingIfacePedestrian_set_green(TrafficLightWaiting* handle, sc_boolean value);
  1051. /*! Raises the in event 'pedestrianRequest' that is defined in the default interface scope. */
  1052. extern void trafficLightWaitingIface_raise_pedestrianRequest(TrafficLightWaiting* handle);
  1053. /*! Raises the in event 'onOff' that is defined in the default interface scope. */
  1054. extern void trafficLightWaitingIface_raise_onOff(TrafficLightWaiting* handle);
  1055. /*! Checks if the specified state is active. */
  1056. extern sc_boolean trafficLightWaiting_isActive(TrafficLightWaiting* handle, TrafficLightWaitingStates state);
  1057. #ifdef __cplusplus
  1058. }
  1059. #endif
  1060. #endif /* TRAFFICLIGHTWAITING_H_ */
  1061. 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_.
  1062. h5. Fundamental statechart methods
  1063. 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.
  1064. 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:
  1065. bc(prettyprint)..
  1066. extern void trafficLightWaiting_init(TrafficLightWaiting* handle);
  1067. extern void trafficLightWaiting_enter(TrafficLightWaiting* handle);
  1068. extern void trafficLightWaiting_exitTrafficLightWaiting* handle);
  1069. extern void trafficLightWaiting_runCycle(TrafficLightWaiting* handle);
  1070. p.
  1071. * 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.
  1072. * The @enter()@ method must be called to enter the state machine. It brings the state machine to a well-defined state.
  1073. * 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.
  1074. * 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:
  1075. # Clear list of outgoing events.
  1076. # Check whether events have occurred which are leading to a state change.
  1077. # If a state change has to be done:
  1078. ## Execute exit actions of the present state.
  1079. ## Save history state, if necessary.
  1080. ## Make the new state active. ==<!-- FIXME: We should also make the old state inactive, shouldn't we? -->==
  1081. ## Execute entry actions of the new state.
  1082. # Clear list of incoming events.
  1083. h5. Variable and event access
  1084. 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)@.
  1085. h4. Timed state machines
  1086. 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.
  1087. The traffic light example uses timing funtionality, namely _after_ clauses. To support time-controlled behavior, such an additional header file is generated.
  1088. bc(prettyprint)..
  1089. extern "C" {
  1090. #endif
  1091. /*! \file This header defines prototypes for all functions that are required by the state machine implementation.
  1092. This is a state machine uses time events which require access to a timing service. Thus the function prototypes:
  1093. - trafficLightWaiting_setTimer and
  1094. - trafficLightWaiting_unsetTimer
  1095. are defined.
  1096. These functions will be called during a 'run-to-completion step' (runCycle) of the statechart.
  1097. There are some constraints that have to be considered for the implementation of these functions:
  1098. - never call the statechart API functions from within these functions.
  1099. - make sure that the execution time is as short as possible.
  1100. */
  1101. //
  1102. // This is a timed state machine that requires timer services
  1103. //
  1104. //! This function has to set up timers for the time events that are required by the state machine.
  1105. /*!
  1106. This function will be called for each time event that is relevant for a state when a state will be entered.
  1107. \param evid An unique identifier of the event.
  1108. \time_ms The time in milli seconds
  1109. \periodic Indicates the the time event must be raised periodically until the timer is unset
  1110. */
  1111. extern void trafficLightWaiting_setTimer(const sc_eventid evid, const sc_integer time_ms, const sc_boolean periodic);
  1112. //! This function has to unset timers for the time events that are required by the state machine.
  1113. /*!
  1114. This function will be called for each time event taht is relevant for a state when a state will be left.
  1115. \param evid An unique identifier of the event.
  1116. */
  1117. extern void trafficLightWaiting_unsetTimer(const sc_eventid evid);
  1118. #ifdef __cplusplus
  1119. }
  1120. #endif
  1121. #endif /* TRAFFICLIGHTWAITINGREQUIRED_H_ */
  1122. 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.
  1123. p. The following methods are dealing with timing functionality:
  1124. h5. Method setTimer
  1125. p. A state machine calls the @setTimer()@ method – short for the method's full name like e.&nbsp;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.
  1126. In order to have the timer service raise the time event periodically, the parameter _periodic_ must be _true_.
  1127. h5. Method unsetTimer
  1128. 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.
  1129. h5. Method raiseTimeEvent
  1130. 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_).
  1131. The time event is recognized by the state machine and will be processed during the next run cycle.
  1132. 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.
  1133. h4(#COperationCallbacks). Operation callbacks
  1134. 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:
  1135. !images/OperationExample.png(Specifying an operation callback in the model)!
  1136. Let's have a look at the generated code:
  1137. bc(prettyprint)..
  1138. #ifndef DEFAULTREQUIRED_H_
  1139. #define DEFAULTREQUIRED_H_
  1140. #include "sc_types.h"
  1141. #ifdef __cplusplus
  1142. extern "C" {
  1143. #endif
  1144. /*! \file This header defines prototypes for all functions that are required by the state machine implementation.
  1145. This state machine makes use of operations declared in the state machines interface or internal scopes. Thus the function prototypes:
  1146. - defaultIface_myOperation
  1147. are defined.
  1148. These functions will be called during a 'run-to-completion step' (runCycle) of the statechart.
  1149. There are some constraints that have to be considered for the implementation of these functions:
  1150. - never call the statechart API functions from within these functions.
  1151. - make sure that the execution time is as short as possible.
  1152. */
  1153. extern sc_integer defaultIface_myOperation(const sc_integer param1, const sc_boolean param2);
  1154. #ifdef __cplusplus
  1155. }
  1156. #endif
  1157. #endif /* DEFAULTREQUIRED_H_ */
  1158. 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.
  1159. h4(#CIntegratingGeneratedCode). Integrating generated code
  1160. 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:
  1161. bc(prettyprint)..
  1162. #include "org_yakindu_sct_examples_c_trafficlight.h"
  1163. #include <QtGui>
  1164. #include <QApplication>
  1165. #include "src-gen/sc_types.h"
  1166. #include "src-gen/TrafficLightWaiting.h"
  1167. #include "statemachine/TrafficLightTimer.h"
  1168. #include "statemachine/TrafficLightRunner.h"
  1169. TrafficLightTimer *timer;
  1170. int main(int argc, char *argv[]) {
  1171. TrafficLightWaiting handle;
  1172. trafficLightWaiting_init(&handle);
  1173. timer = new TrafficLightTimer(&handle);
  1174. trafficLightWaiting_enter(&handle);
  1175. QApplication a(argc, argv);
  1176. TrafficLightRunner *runner = new TrafficLightRunner(&handle, 100);
  1177. org_yakindu_sct_examples_c_trafficlight w(0, runner);
  1178. w.show();
  1179. int ret = a.exec();
  1180. return ret;
  1181. }
  1182. void trafficLightWaiting_setTimer(const sc_eventid evid,
  1183. const sc_integer time_ms, const sc_boolean periodic) {
  1184. timer->setTimer(evid, time_ms, periodic);
  1185. }
  1186. void trafficLightWaiting_unsetTimer(const sc_eventid evid) {
  1187. timer->unsetTimer(evid);
  1188. }
  1189. 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@:
  1190. bc(prettyprint)..
  1191. #include "org_yakindu_sct_examples_c_trafficlight.h"
  1192. org_yakindu_sct_examples_c_trafficlight::org_yakindu_sct_examples_c_trafficlight(
  1193. QWidget *parent, TrafficLightRunner *runner) :
  1194. QMainWindow(parent) {
  1195. ui.setupUi(this);
  1196. crossing = new CrossingWidget(this);
  1197. trafficLight = new TrafficLightWidget(crossing);
  1198. trafficLight->setGeometry(275, 75, 30, 90);
  1199. pedestrianLight = new PedestrianLightWidget(crossing);
  1200. pedestrianLight->setGeometry(50, 10, 70, 20);
  1201. connect(runner, SIGNAL(cycleDone(TrafficLightWaiting*)), this, SLOT(update(TrafficLightWaiting*)));
  1202. pedestrianReq = new QPushButton("pedestrian request", this);
  1203. pedestrianReq->setGeometry(1, 365, 150, 30);
  1204. connect(pedestrianReq, SIGNAL(released()), runner, SLOT(raisePedestrianRequest()));
  1205. off = new QPushButton("off / on", this);
  1206. off->setGeometry(249, 365, 150, 30);
  1207. connect(off, SIGNAL(released()), runner, SLOT(raiseOnOff()));
  1208. }
  1209. void org_yakindu_sct_examples_c_trafficlight::update(
  1210. TrafficLightWaiting *handle) {
  1211. trafficLight->setSignals(handle->ifaceTrafficLight.red,
  1212. handle->ifaceTrafficLight.yellow, handle->ifaceTrafficLight.green);
  1213. pedestrianLight->setSignals(handle->ifacePedestrian.request,
  1214. handle->ifacePedestrian.red, handle->ifacePedestrian.green);
  1215. QMainWindow::update();
  1216. }
  1217. org_yakindu_sct_examples_c_trafficlight::~org_yakindu_sct_examples_c_trafficlight() {
  1218. }
  1219. h3(#CppSpec). Specifications of C++ code
  1220. 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.
  1221. ==<!-- 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. -->==
  1222. h4(#CppGeneratedCode). Generated code files
  1223. You will find the generated code in the _src-gen_ folder of the traffic light example.
  1224. 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.
  1225. h4. Abstract class StatemachineInterface
  1226. Each generated state machine implements the interface @StatemachineInterface@:
  1227. bc(prettyprint)..
  1228. package org.yakindu.sct.examples.trafficlight.cyclebased;
  1229. #ifndef STATEMACHINEINTERFACE_H_
  1230. #define STATEMACHINEINTERFACE_H_
  1231. /*
  1232. * Basic interface for statemachines.
  1233. */
  1234. class StatemachineInterface {
  1235. public:
  1236. virtual ~StatemachineInterface() = 0;
  1237. /*
  1238. * Initializes the statemachine. Use to init internal variables etc.
  1239. */
  1240. virtual void init() = 0;
  1241. /*
  1242. * Enters the statemachine. Sets the statemachine in a defined state.
  1243. */
  1244. virtual void enter() = 0;
  1245. /*
  1246. * Exits the statemachine. Leaves the statemachine with a defined state.
  1247. */
  1248. virtual void exit() = 0;
  1249. /*
  1250. * Start a run-to-completion cycle.
  1251. */
  1252. virtual void runCycle() = 0;
  1253. };
  1254. inline StatemachineInterface::~StatemachineInterface() {}
  1255. #endif /* STATEMACHINEINTERFACE_H_ */
  1256. h5. Fundamental statechart methods
  1257. 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.
  1258. The @StatemachineInterface@ interface specifies the four functions @init()@, @enter()@, @exit()@ and @runCycle()@.
  1259. * 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.
  1260. * The @enter()@ function must be called to enter the state machine. It brings the state machine to a well-defined state.
  1261. * 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.
  1262. * 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:
  1263. # Clear list of outgoing events.
  1264. # Check whether events have occurred which are leading to a state change.
  1265. # If a state change has to be done:
  1266. ## Execute exit actions of the present state.
  1267. ## Save history state, if necessary.
  1268. ## Make the new state active. ==<!-- FIXME: We should also make the old state inactive, shouldn't we? -->==
  1269. ## Execute entry actions of the new state.
  1270. # Clear list of incoming events.
  1271. ==<!-- h5. Variable and event access -->==
  1272. ==<!-- Do we need some equivalent to the C section here? Here's the C text: -->==
  1273. ==<!-- 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)@. -->==
  1274. h4. Timed state machines
  1275. If a statechart uses timing functionality, additional classes are generated.
  1276. The traffic light example uses timing funtionality, namely _after_ clauses. To support time-controlled behavior, the abstract classes @TimedStatemachineInterface@ and @TimerInterface@ are generated.
  1277. 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. -->==
  1278. @TimedStatemachineInterface@ also specifies the callback function @raiseTimeEvent(sc_eventid event)@, enabling the timer service to raise time events.
  1279. bc(prettyprint)..
  1280. #ifndef TIMEDSTATEMACHINEINTERFACE_H_
  1281. #define TIMEDSTATEMACHINEINTERFACE_H_
  1282. #include "sc_types.h"
  1283. #include "TimerInterface.h"
  1284. /*
  1285. * Interface for state machines which use timed event triggers.
  1286. */
  1287. class TimedStatemachineInterface {
  1288. public:
  1289. virtual ~TimedStatemachineInterface() = 0;
  1290. /*
  1291. * Set the ITimerService for the state machine. It must be set
  1292. * externally on a timed state machine before a run cycle can be correct
  1293. * executed.
  1294. */
  1295. virtual void setTimer(TimerInterface* timer) = 0;
  1296. /*
  1297. * Returns the currently used timer service.
  1298. */
  1299. virtual TimerInterface* getTimer() = 0;
  1300. /*
  1301. * Callback method if a time event occurred.
  1302. */
  1303. virtual void raiseTimeEvent(sc_eventid event) = 0;
  1304. };
  1305. inline TimedStatemachineInterface::~TimedStatemachineInterface() {}
  1306. #endif /* TIMEDSTATEMACHINEINTERFACE_H_ */
  1307. 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:
  1308. bc(prettyprint)..
  1309. #ifndef TIMERINTERFACE_H_
  1310. #define TIMERINTERFACE_H_
  1311. #include "sc_types.h"
  1312. //forward declaration of TimedStatemachineInterface to avoid cyclic dependency
  1313. class TimedStatemachineInterface;
  1314. /*
  1315. * Basic interface for state machines.
  1316. */
  1317. class TimerInterface {
  1318. public:
  1319. virtual ~TimerInterface() = 0;
  1320. /*
  1321. * Starts the timing for a time event.
  1322. */
  1323. virtual void setTimer(TimedStatemachineInterface* statemachine, sc_eventid event, sc_integer time, sc_boolean isPeriodic) = 0;
  1324. /*
  1325. * Unsets the given time event.
  1326. */
  1327. virtual void unsetTimer(TimedStatemachineInterface* statemachine, sc_eventid event) = 0;
  1328. /*
  1329. * Cancel timer service. Use this to end possible timing threads and free
  1330. * memory resources.
  1331. */
  1332. virtual void cancel() = 0;
  1333. };
  1334. inline TimerInterface::~TimerInterface() {}
  1335. #endif /* TIMERINTERFACE_H_ */
  1336. p. The @TimerInterface@ interface defines the following functions dealing with timing functionality:
  1337. h5. Function setTimer
  1338. 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.
  1339. In order to have the timer service raise the time event periodically, the parameter _isPeriodic_ must be _true_.
  1340. h5. Function unsetTimer
  1341. 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.
  1342. h5. Function raiseTimeEvent
  1343. 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.
  1344. The time event is recognized by the state machine and will be processed during the next run cycle.
  1345. 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.
  1346. h4(#CppInterVar). Interfaces, Variable and Event access
  1347. ==<!-- FIXME: It should be made clear what a statechart interface is, in contrast to e. g. am interface in a programming language. -->==
  1348. 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:
  1349. bc(prettyprint)..
  1350. interface:
  1351. var a:boolean
  1352. in event evA:boolean
  1353. out event evB:integer
  1354. p. The generated interface code looks like following:
  1355. bc(prettyprint)..
  1356. //! Inner class for SCInterface interface scope.
  1357. class SCInterface {
  1358. public:
  1359. /*! Gets the value of the variable 'a' that is defined in the default interface scope. */
  1360. sc_boolean get_a();
  1361. /*! Sets the value of the variable 'a' that is defined in the default interface scope. */
  1362. void set_a(sc_boolean value);
  1363. /*! Raises the in event 'evA' that is defined in the default interface scope. */
  1364. void raise_evA(sc_boolean value);
  1365. /*! Checks if the out event 'evB' that is defined in the default interface scope has been raised. */
  1366. sc_boolean isRaised_evB();
  1367. /*! Gets the value of the out event 'evB' that is defined in the default interface scope. */
  1368. sc_integer get_evB_value();
  1369. private:
  1370. friend class Default;
  1371. sc_boolean a;
  1372. sc_boolean evA_raised;
  1373. sc_boolean evA_value;
  1374. sc_boolean evB_raised;
  1375. sc_integer evB_value;
  1376. };
  1377. 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.
  1378. 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:
  1379. bc(prettyprint)..
  1380. void Default::SCInterface::raise_evA(sc_boolean value) {
  1381. evA_value = value;
  1382. evA_raised = true;
  1383. }
  1384. sc_boolean Default::SCInterface::isRaised_evB() {
  1385. return evB_raised;
  1386. }
  1387. sc_integer Default::SCInterface::get_evB_value() {
  1388. return evB_value;
  1389. }
  1390. sc_boolean Default::SCInterface::get_a() {
  1391. return a;
  1392. }
  1393. void Default::SCInterface::set_a(sc_boolean value) {
  1394. a = value;
  1395. }
  1396. p. The name of the default, unnamed statechart interface class is generated as @SCInterface@. If a statechart interface has a dedicated name, e.&nbsp;g. _MyInterface_, then the C++ class name will be the statechart interface's name, prepended with string @SCI@, e.&nbsp;g. @SCIMyInterface@.
  1397. 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.
  1398. ==<!-- h4(#CppInterfaceObservers). Interface observers -->==
  1399. ==<!-- In Java we have such a chapter. What about a C++ equivalent? -->==
  1400. h4(#CppOperationCallbacks). Operation callbacks
  1401. 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:
  1402. !images/OperationExample.png(Specifying an operation callback in the model)!
  1403. Let's have a look at the additionally generated code for operation support in the _default.h_ header file:
  1404. bc(prettyprint)..
  1405. //! Inner class for default interface scope operation callbacks.
  1406. class DefaultSCI_OCB {
  1407. public:
  1408. virtual sc_integer myOp(sc_integer param1, sc_boolean param2) = 0;
  1409. };
  1410. /*! Set the working instance of the operation callback interface 'DefaultSCI_OCB'. */
  1411. void setDefaultSCI_OCB(DefaultSCI_OCB* operationCallback);
  1412. 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.
  1413. bc(prettyprint)..
  1414. #include "default.h"
  1415. sc_integer Default::DefaultSCI_OCB::myOp(sc_integer param1, sc_boolean param2) {
  1416. // Your operation code should be placed here;
  1417. return 0;
  1418. }
  1419. int main(int argc, char *argv[]) {
  1420. Default *defaultSM = new Default();
  1421. DefaultSCI_OCB *defaultSCI_OCB = new DefaultSCI_OCB();
  1422. defaultSM->setDefaultSCI_OCB(defaultSCI_OCB);
  1423. defaultSM->init();
  1424. defaultSM->enter();
  1425. defaultSM->runCycle();
  1426. }
  1427. p.
  1428. ==<!-- h4(#CppIntegratingGeneratedCode). Integrating generated code -->==
  1429. ==<!-- This chapter is available for Java and C, but missing for C++. -->==