W3C

State Chart XML (SCXML): State Machine Notation for Control Abstraction

W3C Working Draft 24 January 2006

This version:
http://www.w3.org/TR/2006/WD-scxml-20060124/
Latest version:
http://www.w3.org/TR/scxml/
Previous version:
http://www.w3.org/TR/2005/WD-scxml-20050705/
Editors:
Jim Barnett, Aspect Software (Editor-in-Chief)
RJ Auburn, Voxeo
Michael Bodell, Tellme Networks
Marc Helbing, Nuance
Rafah Hosn, IBM
Klaus Reifenrath, Nuance

Abstract

This document describes SCXML, or the "State Chart extensible Markup Language". SCXML provides a generic state-machine based execution environment based on CCXML and Harel State Tables.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document is the second Public Working Draft of SCXML for review by W3C Members and other interested parties, and has been developed by the Voice Browser Working Group (W3C Members Only) as part of the W3C Voice Browser Activity. This draft differs from the previous primarily in that it adds a data model and fully specifies the syntax of the language.

Comments for this specification are welcomed to www-voice@w3.org (archives).

This document was produced under the 5 February 2004 W3C Patent Policy. The Working Group maintains a public list of patent disclosures relevant to this document; that page also includes instructions for disclosing [and excluding] a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) with respect to this specification should disclose the information in accordance with section 6 of the W3C Patent Policy.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

Table of Contents

1 Terminology
2 Overview
3 Basic State Notation
    3.1 <scxml>
        3.1.1 Attribute Details
        3.1.2 Children
    3.2 <state>
        3.2.1 Attribute Details
        3.2.2 Children
    3.3 <transition>
        3.3.1 Attribute Details
        3.3.2 Children
    3.4 <parallel>
        3.4.1 Attribute Details
        3.4.2 Children
4 Pseudo-States
    4.1 <initial>
        4.1.1 Attribute Details
        4.1.2 Children
    4.2 <history>
        4.2.1 Attribute Details
        4.2.2 Children
    4.3 <join>
        4.3.1 Attribute Details
        4.3.2 Children
    4.4 <invoke>
        4.4.1 Attribute Details
        4.4.2 Children
    4.5 <param>
        4.5.1 Attribute Details
        4.5.2 Children
    4.6 <finalize>
        4.6.1 Attribute Details
        4.6.2 Children
5 Data Model
    5.1 Overview of Data Model
    5.2 <datamodel>
        5.2.1 Attribute Details
        5.2.2 Children
    5.3 <data>
        5.3.1 Attribute Details
        5.3.2 Children
    5.4 Rolling Back the Data Model
6 Executable Content
    6.1 Data Model Operations
        6.1.1 <assign>
            6.1.1.1 Attribute Details
            6.1.1.2 Children
        6.1.2 eventdata
        6.1.3 <var>
            6.1.3.1 Attribute Details
            6.1.3.2 Children
        6.1.4 <script>
            6.1.4.1 Attribute Details
            6.1.4.2 Children
    6.2 Event Generation
        6.2.1 <send>
            6.2.1.1 Overview
            6.2.1.2 Attribute Details
        6.2.2 <cancel>
            6.2.2.1 Overview
            6.2.2.2 Attribute Details
    6.3 Flow Control Elements
        6.3.1 <if>
            6.3.1.1 Overview
            6.3.1.2 Attribute Details
        6.3.2 <elseif>
            6.3.2.1 Overview
            6.3.2.2 Attribute Details
        6.3.3 <else>
            6.3.3.1 Overview
            6.3.3.2 Attribute Details
    6.4 Debugging Elements
        6.4.1 <log>
            6.4.1.1 Overview
            6.4.1.2 Attribute Details
    6.5 Custom Action Elements
7 Boolean Expressions
    7.1 In
        7.1.1 Overview
        7.1.2 Attribute Details
8 SCXML Events
9 Related Work

Appendices

A Contributors
B Open Issues
    B.1 extension mechanism
    B.2 error handling
    B.3 session ID
    B.4 parallel as child of scxml
    B.5 do we need <datamodel>
    B.6 do we need <returndata>
    B.7 Overriding state definitions included with <src> attribute
    B.8 Task Logging
    B.9 updates to external data sources
    B.10 replacement for <synch>
C Probabilistic State Machines
D Schema
E CCXML to SCXML Conversion
F Examples
    F.1 Language Overview
    F.2 Microwave Oven Example
    F.3 Example of Invoke and finalize
G An Overview of UML Notation and SCXML Semantics
    G.1 A Simple State Machine
    G.2 Executing Actions On Entering And Exiting
    G.3 Complex States
    G.4 Parallel States
    G.5 Concurrency And Event Queues
    G.6 Synchronizing And Concurrency
H References


1 Terminology

[Definition: The key words must, must not, required, shall, shall not, should, should not, recommended, may, and optional in this specification are to be interpreted as described in [IETF RFC 2119].]

The terms base URI and relative URI are used in this specification as they are defined in [IETF RFC 2396].

2 Overview

This document outlines State Chart XML (SCXML), which is a general-purpose event-based state machine language that can be used in many ways, including:

SCXML combines concepts from CCXML and Harel State Tables. CCXML [W3C CCXML 1.0] is an event-based state machine language designed to support call control features in Voice Applications (specifically including VoiceXML but not limited to it). The CCXML 1.0 specification defines both a state machine and event handing syntax and a standardized set of call control elements. Harel State Tables are a state machine notation that was developed by the mathematician David Harel [Harel and Politi] and is included in UML [UML 2.0]. They offer a clean and well-thought out semantics for sophisticated constructs such as a parallel states. They have been defined as a graphical specification language, however, and hence do not have an XML representation. The goal of this document is to combine Harel semantics with an XML syntax that is a logical extension of CCXML's state and event notation. For an overview of the UML notation and a brief outline of SCXML's semantics, see G An Overview of UML Notation and SCXML Semantics, below.

For concreteness sake, we use ECMAScript as the language for data elements, but as noted in Section 5 Data Model below, we have not yet chosen a data access language. In any case the complete language definition will permit multiple data access languages to be used.

3 Basic State Notation

3.1 <scxml>

The top-level root element, which carries version information etc.

3.1.1 Attribute Details

NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
initialstate true IDnone Valid state ID The id of the initial state for the document. The statemachine will transition to this state as the last step in document initialization.
xmlnsfalseURInone
versionfalsenone

3.1.2 Children

  • <state> A top-level state in the state machine. Occurs one or more times. See 3.2 <state> for details.

  • <datamodel> Optional specification of a datamodel. See 5 Data Model for details.

3.2 <state>

Holds the representation of a state.

3.2.1 Attribute Details

NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
ID falseIDnone Valid state ID Identifier for this state. If present it must be unique within the document.
srcfalseURInoneThe URI of a document containing a valid state specification URI of a file containing the definition of this state. If it is present, no children are allowed.
finalFalseBooleanFalseBoolean Boolean property indicating whether this is a final state or not. Final states may not have substates or outgoing transitions. When a final state is entered, a completion event "parentID.done" is generated, where "parentID" is the <id> of this state's parent state.
taskFalseBooleanFalseBoolean If true the state is considered to be a task for reporting purposes and entry and exit will be logged automatically. The logging shall include at least the state's ID and the status upon exit. The legal status values are 'success' and 'failure' where 'success' indicates that the task ran to completion, while 'failure' indicates that the task did not reach completion. By default, the task will be considered to have completed successfully if the state reaches a final substate while any other exit will be considered failure. Implementations are encouraged to include more detailed information in addition to status, such as reason for failure, etc. This attribute may occur only on complex states, i.e., those with <state> or <parallel> children.

3.2.2 Children

  • <onentry> Optional element holding executable content to be run upon entering this <state>. May occur 0 or 1 times. See 6 Executable Content

  • <onexit> Optional element holding executable content to be run when exiting this <state>. May occur 0 or 1 times. See 6 Executable Content

  • <transition> Defines an outgoing transition from this <state>. May occur 0 or more times. See 3.3 <transition>

  • <initial> A child which identifies initial state for state machines that have substates. This child is required if and only if the machine has one or more <state> children. See 4.1 <initial>

  • <state> Defines a sequential substate of the parent state. May occur 0 or more times. Incompatible with the <parallel> property.

  • <parallel> Defines a set of parallel substates. May occur 0 or 1 times. Incompatible with the <state> property. See 3.4 <parallel>

  • <history> A child which represents the descendant state that the parent state was in the last time the system transitioned from the parent. A transition with this state as its target is in fact a transition to one of the other descendant states of the parent. May occur 0 or more times. See 4.2 <history>.

  • <join> A pseudo-state that is useful for synchronizing parallel regions. May occur 0 or moretimes. See 4.3 <join>

  • <datamodel> Optional specification of a datamodel. See 5 Data Model for details.

  • <invoke> Used to invoke external components. May occur 0 or 1 times. Incompatible with the <state> and <parallel> elements. For further details, see 4.4 <invoke>

3.3 <transition>

Transitions between states are triggered by events and conditionalized via guard-conditions. The optional attribute "target" specifies the destination of the transition, which may be a <state> or a <parallel> region. If the "target" on a <transition> is omitted, then taking the transition has the effect of leaving the machine in the same state after invoking any executable content that is included in the transition. Such a transition is equivalent to an 'event' handler in Harel State Table notation. Note that this is different from a <transition> whose "target" is its source state. In the latter case, the state is exited and reentered, triggering execution of its <onentry> and <onexit> executable content.

Any executable content contained in a transition is executed after the <onexit> handlers of the source state and before the <onentry> handlers of the target state. Within both the 'cond' attribute of the transition and the executable content, the special variable '_eventdata' may be used to access data contained within the triggering event.

3.3.1 Attribute Details

NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
event falseStringnone Any event name. The wildcard '*' is permitted. The event trigger for this transition. The transition will be taken only when the event is generated. See G An Overview of UML Notation and SCXML Semantics for details on how transitions are selected.
condfalseData language expressionnoneAny data language expression that evaluates to a boolean. Guard condition for this transition. If it is present, the transition is taken only if the guard condition evaluates to true. See 7 Boolean Expressions for details.
targetfalsestate or parallel region IDnoneWhitespace separated list of state IDs in the current state machine. If multiple states are specified all must be descendants of the same <parallel> element. The identifier(s) of the state or parallel region to transition to.

3.3.2 Children

  • Immediate children of <transition> above are executable content that is run after the <onexit> handler for this state and before the <onentry> handler in the target state. See 6 Executable Content

If a transition has both <event> and <cond> conditions, it will be taken only if an event is raised that matches the <event> pattern and the <cond> condition evaluates to true. (See G.5 Concurrency And Event Queues for the case where multiple transitions match a given event or condition.) If the <event> clause is missing, the transition is taken whenever the <cond> evaluates to true. If the <cond> clause is also empty, the transition is taken as soon as the state is entered. Note that the data model can be changed only by the execution of <invoke> or executable content. Therefore transitions with empty <event> conditions need be checked only 1) upon arrival into a state, after the completion of all <onentry> handlers and 2) after an event has been processed (since it may have triggered executable content which could have updated the data model).

3.4 <parallel>

A wrapper element that encapsulates parallel state machines. The <parallel> element has <onenter> and <onexit> properties analogous to <state>. In addition, the <parallel> element holds a set of <state> elements that execute in parallel and join at the <onexit> handler of <parallel> element. In particular, when all of the parallel substates reach a final state, a completion event "ID.done" is generated, where "ID" is the <id> of the <parallel> element. Either the <parallel> element or one of its ancestors can trigger a transition off this event, at which time the <onexit> handler of the element will be executed.

For the <parallel> element to be useful, each of its <state> substates must itself be a complex state, i.e., one with either <state> or <parallel> children. When the state machine enters the parent <parallel> element, it simultaneously enters each <child> state. Transitions wihthin the individual <child> elements operate normally, but there may not be transitions between the <child> elements since that would violate the semantics of parallelism. However any of the <child> elements may take a transition outside the <parallel> element. When this happens, the <parallel> element and all of its <child> elements are exited and the corresponding <onexit> handlers are executed. The handlers for the <child> elements execute first, in no determinate order, followed by that for the parent <parallel> element, followed by an <action> expression in the <transition> element, and then the <onentry> handlers in the "target" state.

3.4.1 Attribute Details

NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
id false IDnone Valid state ID Indicates the name of the parallel region.
srcfalseURInoneThe URI of a document containing a valid parallel region specification URI of a file containing the definition of this parallel region. If it is present, no children are allowed.
taskFalseBooleanfalseBoolean If true the parallel is considered to be a task for reporting purposes and entry and exit will be logged automatically. The legal status values are 'success' and 'failure' where 'success' indicates that the task ran to completion, while 'failure' indicates that the task did not reach completion. By default, the task will be considered to have completed successfully if the state reaches a final substate while any other exit will be considered failure. Implementations are encouraged to include more detailed information in addition to status, such as reason for failure, etc.

3.4.2 Children

  • <onentry> Holds holding executable content to be run upon entering this element. May occur 0 or more times. If more than one instance is present, they are executed in document order. See 6 Executable Content

  • <onexit> Holds executable content to be run when exiting this element. May occur 0 or more times. If more than one instance is present, they are executed in document order. See 6 Executable Content

  • <state> Defines a parallel substate region. Must occur 1 or more times.

  • <join> A pseudo-state that is useful for synchronizing parallel regions. May occur 0 or moretimes. See 4.3 <join>

  • <datamodel> Optional specification of a data model. See 5 Data Model for details.

4 Pseudo-States

The following elements are called 'pseudo-states' because they do not have the full properties of states (for example they lack <onentry> and <onexit> handlers) and do not map to states in the underlying semantics of the language. However, they can be used like states in many places. In particular, they can often be the "target" of <transition>. They are a notational shorthand allowing the simple statement of some sophisticated control constructs.

4.1 <initial>

This element represents the default initial state for a complex state with sequential substates. Suppose <state> S1 has child states S11, S12, and S13. If the system is in S1, it must also be in one (and only one) of S11, S12, or S13. A <transition> in a distinct <state>S2 may take S11, S12, or S13 as its "target", but it may also simply specify the parent S1. In that case, the <initial> child of S1 specifies which of S11, S12, or S13 the system should transition to.

4.1.1 Attribute Details

NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
ID falseIDnone Valid state ID Identifier for this pseudo-state. If present it must be unique within the document.

4.1.2 Children

  • <transition> A conditionless transition (i.e., one without a <cond> or <event> property). Such a transition is always enabled and will be taken as soon as the state is entered. The "target" of the transition must be a descendant of the <initial> element's parent <state>. If <state>S1 has an <initial>child with a <transition> with "target" S12, there is no semantic difference between a the following three transitions: a) one that takes S1 as its "target" b) one that takes S1's <initial> child as a "target" c) one that takes S12 as its "target". The result in all three cases is that the system enters both S1 and S12 as an atomic action, executing the <onentry> handlers of first S1 and then S12.

4.2 <history>

The <history> pseudo-state allows for 'pause and resume' control flow. Whenever a complex <state> is exited, its <history> pseudo-state, if present, records the state configuration at exit. Later a <transition> taking the <history> state as its "target" allows the <state> to pick up where it left off.

4.2.1 Attribute Details

NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
ID falseIDnone Valid state ID Identifier for this pseudo-state. If present it must be unique within the document.
typefalsestringshallow "deep" or "shallow" If the value is 'shallow' then this state records only the immediate children of the parent <state>. In this case a <transition> with the history pseudo-state as its "target" will end up in the immediate child state that the parent was in the last time it was exited. On the other hand, if this attribute is set to 'deep', the history pseudo-state will remember nested states. In this case a <transition> with the history pseudo-state as its "target" will end up in the mostly deeply nested descendant <state> the parent was in the last time it was exited.
snapshot falseData model locationnone one or more data model expressions denoting nodes in the data model. An optional attribute specifying locations in the datamodel that are to be rolled back when the history state is entered. See Section 5.4 Rolling Back the Data Model for details.

4.2.2 Children

  • <transition> A conditionless transition (i.e., one without a <cond> or <event> property). Such a transition is always enabled and may be taken as soon as the state is entered. This <transition> represents the default history state and indicates the <state> to transition to if the parent <state> has never been entered before. if <type> is 'shallow', then the "target" of this <transition> must be an immediate child of the parent <state>. Otherwise it can be any descendant <state>.

4.3 <join>

The <join> pseudo-state provides barrier logic allowing the synchronization of defined threads of control. All incoming transitions must be unconditional. For a discussion of join's semantics see G An Overview of UML Notation and SCXML Semantics.

4.3.1 Attribute Details

NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
ID falseIDnone Valid state ID Identifier for this pseudo-state. If present it must be unique within the document.

4.3.2 Children

  • <transition>. May occur one or more times. May not contain an <event>. At least one instance must not contain <cond> guard condition. These restrictions ensure that at least one transition is enabled whenever the join is reached.

4.4 <invoke>

<invoke> and its child <finalize> are useful in states that model the behavior of an external service. The <invoke> tag is executed immediately after the state's <onenter> tags and sends an event invoking the external service. (<invoke> can thus be considered to be a syntactically distinguished <onenter> tag.) The <param> element may be used to pass data to the service. Any events that are received by the state machine from the invoked component during the invocation are preprocessed by the <finalize> handler before transitions are selected. The <finalize> code is used to normalize the form of the returned data and to update the data model before the transitions' <event> and <cond> clauses are invoked.

When the <invoke> tag is executed, the platform must start a new logical instance of the external service specified in "targettype" and pass it the arguments specified in "src" and <param>. The service instance may be local or remote. In addition to the explicit arguments, the platform must pass the external service the "id" of the state that is invoking it. (Exact syntax TBD.) The external service must include the same "id" in all events that it returns to the invoking machine. (Syntax TBD.)

The external service may generate multiple events while it is processing, but it must generate a special 'Done' event (syntax TBD) once it has finished processing. It may not generate any other events afterwards. If the the invoking state machine takes a transition out of the state containing the <invoke> before it receives the 'Done' event, it must automatically send a 'Cancel' event to the invoked component to notify it that it may stop its processing. The 'Cancel' event will be sent as if it were the final <onexit> handler in the invoking state. The invoked component must respond to the 'Cancel' event with a 'CancelResponse' event (syntax of both events TBD). The invoking state machine will take its transition without waiting for the CancelResponse event, which will be processed like any other external event.

Note that the <invoke> element may be used to invoke an external SCXML interpreter to execute a different state machine. In this case, the external state machine acts as a set of substates of the invoking state. The behavior is thus similar to a complex state defined with <state> child elements. The most important difference is that in the <invoke> case, the external state machine does not share context with the invoking machine. In particular, the invoked machine cannot access any variables declared in the invoking machine and data can be shared only by being explicitly passed via the <param> element. Furthermore, IDs need not be distinct across the two machines (though they must, of course, be distinct within each machine.) The <invoke> tag thus provides a means of well-encapsulated code reuse.

For the niceties of the semantics of <invoke>, consider the case when parallel states invoke the same external service concurrently. In this case, two separate instances of the external service will be started. They can be distingused by the states' "id" which is passed with the invocation. Similarly, the "id" contained in the events returned from the external services can be used to determine which events are responses to which invocation. Each event that is returned will be processed only by the <finalize> in the state that invoked it, but that the event is then processed like any other event that the state machine receives. The finalize code can thus be thought of as a preprocessing stage that applies before the event is added to the event queue. Note that the event will be passed to all parallel states simultaneously to check for transitions. If the application developer wishes to ensure that the event is processed only by the state that issued the <invoke>, he should condition its transitions on the event's <id> property.

4.4.1 Attribute Details

NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
targettypetruestring'scxml' 'scxml', 'vxml', 'ccxml', plus other platform-specific values. A string specifying the type of the external service. Default value is 'scxml'. 'vxml'indicates a VoiceXML 2.x interpreter, while 'ccxml'indicates a CCXML 1.0 interpreter. Platforms may provide additional values.
srcfalseURInone Any URI A URL that will be passed to the external service when it is invoked. If "targettype" is one of the predefined types, the document at the URI will contain the corresponding markup to execute (i.e., an SCXML, VoiceXML, or CCXML document). In other cases, the content of the document will depend on the external service.
srcexpr falseExpressionNone Any expression evaluating to valid URI. A data model expression that will be evaluated at the time that invoke is executed to produce the URI to pass to the external service. Exactly one of "src" and "srcexpr" must be specified.

4.4.2 Children

  • <param>. Optional child element containing data to be passed to the external service. May occur 0 or more times. See 4.5 <param>.

  • <finalize>. Optional element containing executable content to massage the data returned from the invoked component. May occur 0 or 1 times. See 4.6 <finalize> for details.

<invoke> is incompatible with the <state> and <parallel> elements. It may thus occur only in atomic states, namely those which do not have substates.

4.5 <param>

4.5.1 Attribute Details

NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
name true Data model expressionnone Valid data model path expression The name of the parameter. It will be passed unmodified to the external service. It need not specify a node in the surrounding data model.
exprfalseData model expressionnone Valid data model expression An optional expression in the data model language which evaluates to an XML tree. The tree may be part of the data model of the surrounding state machine or may be specified in-line. Normal data model scoping rules apply as specified in 5 Data Model .

If the <expr> attribute is missing, the <name> attribute will be taken as a data model expression referring to a location within the data model and the corresponding data model tree will be passed to the invoked component. If the <name> attribute does not refer to a location in the data model, an error will be generated. Normal data model access and scoping rules apply as specified in 5 Data Model .

4.5.2 Children

None.

4.6 <finalize>

4.6.1 Attribute Details

None.

4.6.2 Children

<finalize>'s children consist of executable content. The content will be invoked on any event that the external service returns after <invoke> has been executed. In the case of parallel states, only the finalize code in the original invoking state will be executed (i.e., the state whose <id> matches the id in the event.) Within the executable content, the special variable '_eventdata' may be used to refer to the data contained in the event which is being finalized.

If no executable content is specified, a default canonicalization handler will be invoked which will update the data model with any return values corresponding to <param> elements with missing <expr> attributes. Thus the effect of a <param> element with an empty <expr> attribute coupled with an empty <finalize> element is first to send all or part of the data model to the invoked component and then to update the that part of the state machine's data model with the returned values. Note that the automatic update does not take place if the <finalize> element is absent as opposed to empty.

The purpose of the executable content is to normalize the format of data and update the data model before transitions are selected. <finalize> code may only massage data. It may not raise events or invoke external actions.

5 Data Model

N.B. This section is provisional and may end up being part of a separate specification. In either case, the definition of the data model may change significantly in the future. Note furthermore that we have not yet specified the language to be used to access the data model.

5.1 Overview of Data Model

To provide a uniform method of access to both local and remote data, we introduce a <datamodel> tag which encapsulates any number of <data> elements. Each such element defines a single data element whose value is an XML tree. The XML tree may be fetched from an external source or specified in-line. Note that atomic variable values are simply degenerate XML trees consisting of a single leaf, so that the <data> element subsumes the <var> element of CCXML.

Data accessed via the <data> tag is local to the SCXML interpreter and not shared with any external resource. However, the local data model, or parts of it, may be sent to an external resource via the <send> tag. (See 6.2.1 <send>.) Existing data values may be modified with the <assign> tag. (See 6.1.1 <assign>).

We have not determined how the XML trees that compose the data model will be specified, accessed, and modified. (Candidates include the DOM API, E4X, and XPath.)

Logically, there is a single globally visible data model for the entire state machine. As an authoring convenience, however, we allow <datamodel> as a child of any <state>, thus allowing parts of the data model to be distributed throughout the document closer to the locations where the data will be accessed. However, all instances of the <data> tag are created and initialized when the state machine is instantiated and may be accessed from any state at any time.

As a further authoring convenience, ambiguous data references will be resolved by standard lexical scoping rules. For example, suppose <state> S has a child S1, S1 has children S11 and S12, and that both S1 and S11 contain <data> elements defining a data tree called 'foo'. References to 'foo' in both S1 and S12 will refer to S1's definition, while a reference inside S11 will refer to S11's definition. A reference to 'foo' in root state S would result in an error because no instance of 'foo' is declared in any surrounding scope. To avoid such errors and override the default scoping rules, the <data> element's name may be prefixed with the ID of the state in which it is declared. Thus in any of the above states, 'S1.foo' will unambiguously refer to the instance of 'foo' defined in S1, while 'S11.foo' will refer to the instance defined in S11. <data> elements defined at the top level under the <scxml> tag may be unambiguously designated by using the '_dm.' prefix.

5.2 <datamodel>

5.2.1 Attribute Details

None.

5.2.2 Children

  • <data> Occurs 0 or more times. Each instance defines a named XML data tree. Trees are created when the document is loaded.

5.3 <data>

5.3.1 Attribute Details

NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
name true stringnone Any valid string The name of the data item. It must be unique within the <state> but need not be unique within the document.
srcfalseURInoneAny URI referencing a valid XML tree Gives the location from which the data XML tree should be downloaded. If present, the <data> element may not have children or an <expr> attribute.
exprfalseExpressionnoneAny valid data model expression Evaluates to the provide the value of the data item. If present, the <data> element may not have children or a <src> attribute.

5.3.2 Children

If <scr> and <expr> are not present, the children of the <data>element should form one or more an XML trees, which represent the value of the element.

In addition to the <src> attribute and in-line child elements, values for the top-level <data> elements can be provided by the environment at instantiation time. The exact mechanism for this is implementation dependent, but values provided at instantiation time override those contained in the <scxml> tag, whether they are specified in-line or via the <src> attribute.

5.4 Rolling Back the Data Model

The data model can be snapshotted and then rolled back using <history> pseudo-states. Each history state has an optional <snapshot>attribute, whose value is one or more path expressions designating locations in the data model. When the history state's parent state is exited, the history state will take and store a snapshot of those locations in the data model. The snapshot will be taken after the parent state's <onexit> handlers have executed, but before the execution of any executable content in the parent's ancestor states or in the transition itself. When the history state is the target of a transition, the stored values will be restored right before the history state's parent state is entered (but after the entry into any of the parent state's ancestors, including the execution of their <onentry> handlers.) Note that this feature can be used in conjunction with multiple history states to control when both the snapshot and the rollback occur in the case of nested states.

6 Executable Content

Executable content consists of actions that are performed as part of taking transitions and entering and leaving states (<onentry> and <onexit>, etc.) In general, such content must be able to modify the data model, raise events, and invoke functionality in the underlying platform. On the other hand, executable content may not cause transitions or any form of change of state, except indirectly, by raising events that are then caught by transitions. The content presented here is closely based on that in CCXML. This is partly for reasons of backward compatibility, but also because CCXML's executable content is quite flexible and has proved is usefulness in a variety of applications. Platforms are free to provide additional executable content corresponding to special features of their implementations. It is important to remember, however, that SCXML treats executable content as a single blocking atomic operation and that no events are processed until all executable content has completed. For example, upon entering a state, the SCXML processor will not process any events or take any transitions until all <onentry> handlers have finished. Thus all executable content, including platform-specific extensions, should complete quickly under all circumstances. A general method for implementing extensions using the <send> tag is presented in 6.5 Custom Action Elements below.

6.1 Data Model Operations

The <assign> tag may be used to modify the data model.

6.1.1 <assign>

6.1.1.1 Attribute Details
NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
location true path expressionnone Any valid path expression denoting a location in the data model The location in the data model into which to insert the new value. Standard lexical scoping rules apply. It is not required to assign to the root of a tree (the <name> value in a <data> tag), since the path expression can reach down into the tree to assign a new value to an internal node.
srcfalseURInoneAny URI referencing a valid XML tree The location from which the new value should be read. Incompatible with expr.
exprfalsedata model language expressionnoneAny expression evaluating to a valid XML tree An expression returning the value to be assigned. Incompatible with src.
6.1.1.2 Children

If <scr> and <expr> are not present, the children of the <assign>element should form one or more an XML trees, which represent the value of the element.

6.1.2 _eventdata

SCXML events carry data and executable content needs to be able to access that data in order to update the data model. The special variable '_eventdata' can be used within executable content to access the data in the current event. In the executable content of <onentry>, <onexit> and <transition> elements, the 'current event' is defined to be the event that triggered the transition. If there is no such event or the event contains no data, _eventdata is undefined. In the 'cond' attribute of <transition>, the current event is the one that is currently being matched against the transition. In all other locations, '_eventdata' is undefined.

6.1.3 <var>

Variables local to a specific block of executable content may be declared using the <var> element and are initialized with the results of evaluating the optional <expr> attribute as an expression. If the <expr> attribute is not present in the <var> declaration, the variable is initialized to <undefined>. The values of variables may be subsequently changed with <assign>.

Variables are declared explicitly by <var> :

<var name="sessionid" />
<var name="currentstate" expr="'initial'" />

Variables can be assigned new values using <assign> with an appropriate atomic value.:

<assign name="currentstate" expr="'cleanup'" />

The implementation MUST evaluate the expression contained in the <expr> attribute of <assign>, and assign the results to the variable referenced in the <name> attribute.

N.B. <var> is included for reasons of backward compatibility with CCXML. It may be removed as we refine the data model. For the most part, <data> offers a superset of the capabilties of <var>. For example, <var> value must be atomic, while <data> may hold a general XML tree as a value. The main differences between <var> and <data> are: 1) <var> can occur anywhere in executable content while <data> can occur only inside the <datamodel> tag 2) <var> is re-initialized each time it is executed, while <data> is initialized when the document is loaded 3) The value of <var> is accessible only within the block of executable content in which it occurs, while the values of <data> are global.

New applications should use the <data> tag wherever possible.

6.1.3.1 Attribute Details
NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
name true Variable namenone Valid Variable name Indicates the name of the variable.
exprfalseExpressionnone Valid Expression Indicates the new value of the variable. This is the initial value.
6.1.3.2 Children
None.

6.1.4 <script>

<script> encloses computations written in the ECMAScript Compact Profile [ECMA327] scripting language. The ECMAScript Compact Profile is a strict subset of the third edition of ECMA-262 [ECMASCRIPT]. It has been designed to meet the needs of resource-constrained environments. Special attention has been paid to constraining ECMAScript features that require proportionately large amounts of system memory, and continuous or proportionately large amounts of processing power. In particular, it is designed to facilitate prior compilation for execution in a lightweight environment. For specific details on what ECMAScript functions are not supported please take a look at ECMA-327 specification.

An implementation must support the ECMAScript Compact Profile and MAY support the full ECMA-262 ECMAScript specification. The implementation must evaluate <script> in executable content as it is processed. The ECMAScript contained within the <script> can declare variables with the ECMAScript var statement. Variables declared in this manner are declared in the scope of the surrounding executable content element. They are known from the point of declaration to the end of that element.

If the implementation is unable to run the script referenced it must throw an error.semantic event.

N.B. <script> is included for reasons of backward compatability with CCXML. It may be removed in future versions of this document.

6.1.4.1 Attribute Details

None.

6.1.4.2 Children

The children of <script> must form a valid EXMAScript expression.

6.2 Event Generation

6.2.1 <send>

6.2.1.1 Overview

<send> is used to send events and data to external systems, including external SCXML Interpreters, or to raise events in the current SCXML session.

The target of <send> is specified using the "target" and "targettype" attributes. These attributes control how the platform should dispatch the event to its final destination.

The "target" attribute specifies the unique identifier of the event target that the system should send the event to. This can be the session ID of another SCXML session. In other cases the value of this attribute will depend on the type of the target. (For example a SIP URL for SIP-INFO messages or a HTTP URL for Web Services). If no "target" attribute is specified the default target is the current SCXML session. If the value of the "target" attribute is not supported, invalid or unreachable by the platform, the system will throw a <error.send.targetunavailable> event.

The "targettype" attribute describes the type of the event target and is used in conjunction with the "target" attribute to determine how to connect to the target. The default value of this attribute is 'scxml'. If the event "targettype" specified is not supported, the platform will throw a <error.send.targettypeinvalid> event.

A platform must support the following values for the "targettype" attribute:

ValueDetails
"scxml"SCXML Session.
"webservice"External Web Service

Platforms may support other target, for example: SIP or basic HTTP GET.

<send> also specifies the content of the message to be sent. <send> may specify message content in one of the two following mutually exclusive ways:

  • <event> attribute with an OPTIONAL <namelist>

    • The <event> attribute specifies an expression that returns the name of the event.

    • The <namelist> attribute specifies a space separated list of data model locations to be included with the message.

    <datamodel>
    <data name="target" expr="'tel:+18005551212'"/>
    <data name="content" expr="'http://www.example.com/mycontent.txt'"/>
    </datamodel>
       ...
    <send target="target" targettype="'x-messaging'" event="'fax.SEND'" namelist="content"/>
  • <xmlns> attribute with explicit content inline XML content specifying the message to sent the <xmlns:<namespace> defines a namespace for the inline content

    <send target="'csta://csta-server.example.com/'"
          targettype="'x-csta'"
          xmlns:csta="http://www.ecma.ch/standards/ecma-323/csta">
          <csta:MakeCall>
            <csta:callingDevice>22343</callingDevice>
            <csta:calledDirectoryNumber>18005551212</csta:calledDirectoryNumber>
          </csta:MakeCall>
    </send>

If an explicit namespace is provided as in the xmlns attribute of the <send>, this namespace can be used to validate the content of the <send>. A namespace specified on a <send> applies only to the attributes and content of the <send>. Multiple namespaces may be included in the <send> to associate message content with more than one namespace.

When an explicit namespace is specified for the <send>, the content of the <send> is parsed but can be ignored by the sending SCXML interpreter until the <send> is executed. XML namespace identifiers contained in the <send> must be preserved and it is the responsibility of the platform to parse the incoming message and remove the namespace prefix, if required by the <send> target.

The sending SCXML Interpreter must not alter the content of the <send> and send all the data contained within the message to the destination specified in the target attribute of <send>. When <send> is used with inline XML content, and the target is a SCXML session, the mapping of that XML content to event object properties is implementation-specific, and outside the scope of this specification.

When a message is successfully sent to the target, the platform will raise a <send.successful> event. Note that this does not mean that the target processed the message successfully. It is up to the target to generate events specific to the message. These events are application specific.

If the send request fails, an <error.send.failed> event will be raised.

6.2.1.2 Attribute Details
NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
eventfalse This attribute may not be specified in conjunction with inline content Expressionnone An expression which returns a character string that indicates the type of event being generated. The event type may include alphanumeric characters and the "." (dot) character. The first character may not be a dot or a digit. Event type names are case-insensitive. If neither the event attribue or in-line content is specified, an error.fetch event will be thrown. If used in conjunction with the inline content, an error.fetch will be thrown.
targetfalse ExpressionnoneA valid target URL An expression returning a unique identifier of the event target that the platform should send the event to.
targettypefalse Expression scxml scxml webservice An expression which returns a character string that specifies the type of the event target. Values defined by the specification are:
  • scxml

  • webservice

sendidfalse Left Hand Side Expressionnone Variable Any data model expression evaluating to a data model location. The location's value will be set to an internally generated unique string identifier to be associated with the event being sent. If this attribute is not specified, the event identifier is dropped.
delayfalse Expression'0s' An expression which returns a character string in CSS2 [CSS2] format The character string returned is interpreted as a time interval. The send tag will return immediately, but the event is not dispatched until the delay interval elapses. Timers are useful for a wide variety of programming tasks, and can be implemented using this attribute. Note: The queue for sending events is maintained locally. Any events waiting to be sent will be purged when the session that issued this request terminates.
xmlns:[YourNameSpacePrefix]false stringnone This returns a namespace identifying the contained message format. More than one xmlns attribute may be included.
namelistfalse This attribute may not be specified in conjunction with inline content Var Listnone List of data model locations A list of zero or more data model locations to be included with the event. If used in conjunction with the inline content, an error.fetch will be thrown.
hintsfalse ExpressionnoneAn expression. The data returned contains information which may be used by the implementing platform to optimize message transmission. The meaning of these hints is platform-specific.

6.2.2 <cancel>

6.2.2.1 Overview

When a SCXML program uses <send> to send an event and includes a <delay> attribute, the <cancel> command will cancel the pending event, if possible. If the delay has expired and the event has already been sent, the <cancel> request will fail and an <error.notallowed> event will be delivered to the SCXML session that executed the <cancel>.

The <cancel> element may be used to cancel events delivered to local or remote SCXML sessions. Compliant SCXML implementations are REQUIRED to support the cancellation of local events but may choose not to support the cancellation of remote events in which case an <error.notallowed> event should be thrown for such requests. The format of the event identifier returned by a <send> request, and specified in the <sendid> attribute of <cancel>, is implementation specific but is expected to uniquely define events across SCXML sessions.

6.2.2.2 Attribute Details
NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
sendidtrue ExpressionnoneA valid event identifier An expression which returns the value of the event identifier that was received when the send command was issued.

6.3 Flow Control Elements

6.3.1 <if>

6.3.1.1 Overview

<if> is a container for conditionally executed elements. <else> and <elseif> can optionally appear within an <if> as immediate children, and serve to partition the elements within an <if>. <else> and <elseif> have no content. <else/> is a synonym for <elseif cond="true"/>.

Each partition within an <if> is preceded by an element having a <cond> attribute. The initial partition is preceded by the <if> and subsequent partitions by <elseif>s (or <else>s). The first partition in document order with a <cond> that evaluates to <true> is selected. <else> always evaluate to <true>. A partition may be empty.

If an <if> has no immediate <elseif> or <else> children, the full contents of the <if> will be selected when the <cond> attribute is <true>.

<else> was chosen to match similar concepts in other languages, and supports examples such as

<if cond="...">
  <!- selected when <if cond> is true ->
  <else/>
  <!- selected when <if cond> is false ->
</if>
            

However, <else> is a synonym for <elseif cond="true"/>, so an example such as:

<if cond="...">
  <!- selected when <if cond> is true ->
  <else/>
  <!- selected when <if cond> is false ->
  <else/>
  <!- never selected ->
</if>
  

is also possible and must be interpreted as:

<if cond="...">
  <!- selected when <if cond> is true ->
  <elseif cond="true"/>
  <!- selected when <if cond> is false ->
  <elseif cond="true"/>
  <!- never selected ->
</if>

With this definition for <else>, a valid XML [XML] document is also a valid SCXML document.

6.3.1.2 Attribute Details
NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
condtrueExpressionnoneA valid expression An boolean expression. See 7 Boolean Expressions for details.

6.3.2 <elseif>

6.3.2.1 Overview

An <elseif> partitions the content of an <if>, and provides a condition that determines the selection of the partition it begins. <elseif> can appear optionally as an immediate child of an <if>.

6.3.2.2 Attribute Details
NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
condtrue ExpressionnoneA valid expression An expression which can be evaluated to true or false.

6.3.3 <else>

6.3.3.1 Overview

<else> is a synonym for <elseif cond="true"/>.

6.3.3.2 Attribute Details
NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
nonenone else is a synonym for elseif cond="true".

6.4 Debugging Elements

6.4.1 <log>

6.4.1.1 Overview

<log> allows an application to generate a logging or debug message which a developer can use to help in application development or post-execution analysis of application performance. The manner in which the message is displayed or logged is platform-dependent. The usage of label is platform-dependent. The use of <log> SHOULD have no other side-effects on interpretation. <log>is an empty element.

6.4.1.2 Attribute Details
NameRequiredAttribute ConstraintsTypeDefault ValueValid ValuesDescription
labelfalse Expressionnone An expression which returns a character string which may be used, for example, to indicate the purpose of the log.
exprtrue Expressionnone An expression evaluating to a string to be logged.
level falseTBDTBD TBD This information will be logged only if the system's log level is at this level or higher. The mechanism for specifying the log level and its legal values will be specified in a future version of this document.

6.5 Custom Action Elements

Custom Action Elements can be defined in other specifications/namespaces and are responsible for performing actions on behalf of custom components. Logically Custom Acton Elements can be thoughts of a collection of actions and handlers to perform specific tasks. An example of this is a CCXML <accept> element that is a Custom Acton Element:

<transition event="ccxml:connection.alerting">
  <ccxml:accept connectionid="_eventdata.connectionid"/>
</transition>

This could be written using a <send> element using the following syntax:

<datamodel>
<data name="connectionid"/>
</datamodel>
<transition event="ccxml:connection.alerting">
  <assign name="connectionid" expr="_eventdata.connectionid"/>
  <send targettype="ccxml" event="ccxml:accept" namelist="connectionid"/>
</transition>

A more complicated example might be a CCXML <createcall> where you are both providing variables and getting values back that using only the <send> syntax would be more complex as it would need to be broken over several steps. For example:

<onentry>
  <ccxml:createcall dest="'tel:+18315552020'" connectionid="myConnectionID"/> 
</onentry>

Would need to be modeled in two steps using <send> as you would need to do something like the following:

<datamodel>
  <data name="dest" expr="'tel:+18315552020'"/>
  <data name="connectionid"/>
</datamodel>
<onentry>
  <send targettype="ccxml" event="ccxml:createcall" namelist="dest"/>
</onentry>
<transition event="ccxml:createcall.success">
   <assign name="connectionid" expr="_eventdata.connectionid"/>
</transition>

The exact mappings between Custom Action Elements and <send> actions are to be defined in the individual Custom Action Element specifications.

7 Boolean Expressions

This section describes the content that can be placed in <cond> elements. In general, a restricted subset of data model expressions is permitted, namely those which evaluate to a boolean and do not have side effects. (Note that in particular <assign> is not permitted inside <cond>.) Data model expressions may refer to the special variable '_eventdata', as described in 6.1.2 _eventdata and to the following special predicate:

7.1 In

7.1.1 Overview

The In predicate allows guard condition in one state to test whether the system is also in another state. This is useful in <parallel> regions.

7.1.2 Attribute Details

  • <state> The <id> of a state. The expression returns true if the system is currently in that <state>.

8 SCXML Events

Events are one of the basic concepts in SCXML since they drive most transitions. The internal structure of events is platform-specific as long as the following external interface is observed:

There is a special class of error events whose names begin with 'error.'. They may be raised by the platform, as specified in this document, or under application control. They are placed in the event queue and processed like any other event, except that there is a special built-in default transition at the <scxml> level that will exit the state machine. Thus errors that are not explicitly handled are not dropped as other events are, but cause the session to terminate.

In may applications, it is important for SCXML to receive events from external entities (for example those to which it contacted with <invoke> and <send>.) For the moment, the delivery of external events to SCXML is left as a platform-specific, but it may be specified in a future version of this document. In any case, external events must be placed in the event queue for processing and must obey the external interface specified above.

For the most part, the set of events raised during the execution of an SCXML document is application-specific and generated under author control by use of the <send> tag. However, certain events are mandatory and generated automatically by the interpeter. In this version of the specification, in addition to error events, there is only the 'Cancel' event which is sent if the state machine leaves the containing state after executing the <invoke> tag but before receiving the 'Done' event. Note that there are also mandatory events that invoked components must return to the invoking SCXML state machine. In this version of the specification, there are two such events, namely 'Done' and 'CancelResponse'. We may well change or expand this set of mandatory events in future drafts of this specification. Furthermore, it is likely that there will be distinct profiles of SCXML for specific applications, such as the Multi-modal Interaction Framework [W3C MMI] and VoiceXML 3.0. These profiles will define extensions to the core language and will likely extend the set of mandatory events with additional events appropriate to the specific application.

9 Related Work

A number of other XML-based state machine notations have been developed, but none serves the same purpose as SCXML. XMI [UML XMI] is a notation developed for representing UML diagrams, including Harel State charts. However it is intended as a machine interchange format and is not readily authorable by humans. ebXML [OASIS ebXML] is a language for business process specification intended to support B2B e-commerce applications. It contains a state machine language that is in some ways similar to the one presented here, but its syntax and semantics are closely tied to its intended use in e-commerce. It is therefore not suitable as a general-purpose state machine language. XTND [XTND], also called XML Transition Network Definition, is a notation for simple finite state machines but lacks Harel's notions of hierarchical and parallel states and are thus not suitable for a general-purpose state machine that is semantically equivalent to Harel statecharts.

A Contributors

The following people contributed to the development of this specification.

B Open Issues

B.1 extension mechanism

Issue ():

We need to define the extension mechanism used for specific applications such as the MMI framework

Resolution:

None recorded.

B.2 error handling

Issue ():

We need to specify the full set of errors that the platform may raise.

Resolution:

None recorded.

B.3 session ID

Issue ():

We need to specify how SCXML session IDs are created an accessed.

Resolution:

None recorded.

B.4 parallel as child of scxml

Issue (parallel):

Should we permit <parallel> as an immediate child of <sxcml>? The current draft requires an empty wrapper <state> element.

Resolution:

None recorded.

B.5 do we need <datamodel>

Issue (datamodel):

Do we need <datamodel>? It has no attributes and <data> could be a direct child of <state>.

Resolution:

None recorded.

B.6 do we need <returndata>

Issue (returndata):

Do we need a <returndata> tag separate from <send>?

Resolution:

None recorded.

B.7 Overriding state definitions included with <src> attribute

Issue (IssueStateTemplates):

Do we need to allow the including state to override content in the included state? If so, the elements in question would both need to have IDs specified.

Resolution:

None recorded.

B.8 Task Logging

Issue (logging):

How can a state with <task> set to true override the default values for success or failure? Do we want to allow this attribute to occur on atomic state? It wouldn't make much sense, but the restriction to complex states may be hard to enforce.

Resolution:

None recorded.

B.9 updates to external data sources

Issue (updates):

We need to explain in more detail how <send> can be used to update external data sources - message protocols and formats, etc.

Resolution:

None recorded.

B.10 replacement for <synch>

Issue (synch):

We have removed the <synch> tag. We need to explain why it is no longer needed.

Resolution:

None recorded.

C Probabilistic State Machines

In some applications, it is useful for a state machine to behave non-deterministically according to a probability distribution. For example, we may want to have a state S1 which transitions to S2 30% of the time and to S3 70% of the time. Such behavior can be modelled in SCXML as long as the executable content includes a random number generator. In the example below, we use ECMAScript to generate a random number between 0.0 and 1.0 in the <onentry> handler of state S1. S1 has two transitions, both triggered by E1, going to states S2 and S3. S1 takes the first transition if the variable <rand> is ≤ 0.3 but the second transition if <rand> is > 0.3. Since <rand> is evenly distributed between 0.0 and 1.0, S1 will transition to S2 30% of the time and S3 70% of the time on event E1. Note that it is important that the random number generation take place outside the <cond> clause of the transition since there are no guarantees of when or often that will be evaluated.

<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initalstate="S1">
  
  <state id="S1">
    <datamodel>
      <data name="rand">
    </datamodel>
    <onentry>
      <assign name="rand" expr="Math.random()"/>
    </onentry>
    <transition event="E1" cond="rand <= 0.3" target="S2"/>
    <transition event="E1" cond="rand > 0.3" target="S3">
  </state>
  
  <state id="S2"/>
  <state id="S3"/>
  
</scxml>

D Schema

      <?xml version="1.0" encoding="UTF-8" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3.org/2005/07/scxml"
	xmlns="http://www.w3.org/2005/07/scxml">
	<xsd:annotation>
		<xsd:documentation>State Chart XML Schema (20060118)</xsd:documentation>
	</xsd:annotation>
	<xsd:annotation>
		<xsd:documentation>
		Copyright 1998-2006 W3C (MIT, ERCIM, Keio), All Rights Reserved. Permission to
		use, copy, modify and distribute the VoiceXML schema and its accompanying
		documentation for any purpose and without fee is hereby granted in perpetuity,
		provided that the above copyright notice and this paragraph appear in all
		copies.  The copyright holders make no representation about the suitability of
		the schema for any purpose. It is provided "as is" without expressed or
		implied warranty.
	</xsd:documentation>
	</xsd:annotation>
	<xsd:element name="scxml">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref="datamodel" minOccurs="0" maxOccurs="1" />
				<xsd:element ref="state" minOccurs="1" maxOccurs="unbounded" />
			</xsd:sequence>
			<xsd:attribute name="version" type="xsd:string" fixed="1.0" />
			<xsd:attribute name="initialstate" type="xsd:IDREF" use="required" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="datamodel">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref="data" minOccurs="0" maxOccurs="unbounded" />
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="data">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:any processContents="lax" minOccurs="0" maxOccurs="unbounded" />
			</xsd:sequence>
			<xsd:attribute name="src" type="xsd:anyURI" />
			<xsd:attribute name="expr" type="xsd:string" />
			<xsd:attribute name="name" type="xsd:NMTOKEN" use="required" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="state">
		<xsd:complexType>
			<xsd:choice minOccurs="0" maxOccurs="unbounded">
				<xsd:element ref="onentry" minOccurs="0" maxOccurs="1" />
				<xsd:element ref="invoke" minOccurs="0" maxOccurs="1" />
				<xsd:element ref="transition" minOccurs="0" />
				<xsd:element ref="initial" minOccurs="0" maxOccurs="1" />
				<xsd:element ref="state" minOccurs="0" />
				<xsd:element ref="history" minOccurs="0" />
				<xsd:element ref="parallel" minOccurs="0" maxOccurs="1" />
				<xsd:element ref="onexit" minOccurs="0" maxOccurs="1" />
				<xsd:element ref="datamodel" minOccurs="0" maxOccurs="1" />
				<xsd:element ref="join" minOccurs="0"/>
			</xsd:choice>
			<xsd:attribute name="id" type="xsd:ID" use="optional" />
			<xsd:attribute name="src" type="xsd:anyURI" />
			<xsd:attribute name="final" type="xsd:boolean" />
			<xsd:attribute name="task" type="xsd:boolean" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="initial">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref="transition" minOccurs="1" />
			</xsd:sequence>
			<xsd:attribute name="id" type="xsd:ID" use="optional" />
			<xsd:attribute name="src" type="xsd:anyURI" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="onentry">
		<xsd:complexType>
			<xsd:group ref="executablecontent" minOccurs="0" maxOccurs="unbounded" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="onexit">
		<xsd:complexType>
			<xsd:group ref="executablecontent" minOccurs="0" maxOccurs="unbounded" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="transition">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:group ref="executablecontent" minOccurs="0" maxOccurs="unbounded" />
			</xsd:sequence>
			<xsd:attribute name="event" type="xsd:string" />
			<xsd:attribute name="cond" type="xsd:string" />
			<xsd:attribute name="target" type="xsd:IDREF" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="target">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref="state" minOccurs="1" />
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="invoke">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref="param" minOccurs="0" maxOccurs="unbounded" />
				<xsd:element ref="finalize" minOccurs="0" maxOccurs="1" />
			</xsd:sequence>
			<xsd:attribute name="src" type="xsd:anyURI" />
			<xsd:attribute name="srcexpr" type="xsd:string" />
			<xsd:attribute name="targettype" type="targettype" use="required" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="finalize">
		<xsd:complexType>
			<xsd:group ref="executablecontent" minOccurs="0" maxOccurs="unbounded" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="parallel">
		<xsd:complexType>
			<xsd:choice minOccurs="0" maxOccurs="unbounded">
				<xsd:element ref="onentry" minOccurs="0" maxOccurs="1" />
				<xsd:element ref="onexit" minOccurs="0" maxOccurs="1" />
				<xsd:element ref="state" minOccurs="0" maxOccurs="1" />
				<xsd:element ref="datamodel" minOccurs="0" maxOccurs="1" />
				<xsd:element ref="join" minOccurs="0" />
			</xsd:choice>
			<xsd:attribute name="id" type="xsd:ID" use="required" />
			<xsd:attribute name="src" type="xsd:anyURI" />
			<xsd:attribute name="task" type="xsd:boolean" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="history">
		<xsd:complexType>
			<xsd:sequence minOccurs="1" maxOccurs="1">
				<xsd:element ref="transition" />
			</xsd:sequence>
			<xsd:attribute name="id" type="xsd:ID" use="required" />
			<xsd:attribute name="src" type="xsd:anyURI" />
			<xsd:attribute name="type" type="historytype" />
			<xsd:attribute name="snapshot" type="xsd:string" />
		</xsd:complexType>
	</xsd:element> <!-- possible values for the 'type' attribute of the 'history' element -->
	<xsd:simpleType name="historytype">
		<xsd:restriction base="xsd:string">
			<xsd:enumeration value="shallow" />
			<xsd:enumeration value="deep" />
		</xsd:restriction>
	</xsd:simpleType>
	<xsd:element name="param">
		<xsd:complexType>
			<xsd:attribute name="name" type="xsd:Name" use="required" />
			<xsd:attribute name="expr" type="xsd:string" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="join">
		<xsd:complexType>
			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
				<xsd:element ref="transition" />
			</xsd:sequence>
			<xsd:attribute name="id" type="xsd:ID" use="required" />
		</xsd:complexType>
	</xsd:element> <!-- all declarations for executable content go in this group --> <!-- those elements are declared after this group -->
	<xsd:group name="executablecontent">
		<xsd:choice>
			<xsd:element ref="var" minOccurs="0" maxOccurs="unbounded" />
			<xsd:element ref="assign" minOccurs="0" maxOccurs="unbounded" />
			<xsd:element ref="send" minOccurs="0" maxOccurs="unbounded" />
			<xsd:element ref="if" minOccurs="0" maxOccurs="unbounded" />
			<xsd:element ref="log" minOccurs="0" maxOccurs="unbounded" />
			<xsd:element ref="script" minOccurs="0" maxOccurs="unbounded" />
		</xsd:choice>
	</xsd:group>
	<xsd:element name="var">
		<xsd:complexType>
			<xsd:attribute name="name" type="xsd:Name" use="required" />
			<xsd:attribute name="expr" type="xsd:string" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="assign">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:any processContents="lax" minOccurs="0" maxOccurs="unbounded" />
			</xsd:sequence>
			<xsd:attribute name="location" type="xsd:Name" use="required" />
			<xsd:attribute name="src" type="xsd:anyURI" />
			<xsd:attribute name="expr" type="xsd:string" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="send">
		<xsd:complexType>
			<xsd:attribute name="event" type="xsd:string" />
			<xsd:attribute name="target" type="xsd:anyURI" />
			<xsd:attribute name="targettype" type="targettype" default="scxml" />
			<xsd:attribute name="sendid" type="xsd:string" /> <!-- attention: "xsd:string" is not the proper type for the following attribute,
				            rather a string in CSS2 format is required -->
			<xsd:attribute name="delay" type="xsd:string" default="'0s'" />
			<xsd:attribute name="namelist" type="xsd:string" />
			<xsd:attribute name="hints" type="xsd:string" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="cancel">
		<xsd:complexType>
			<xsd:attribute name="sendid" type="xsd:string" use="required" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="if">
		<xsd:complexType>
			<xsd:choice minOccurs="0" maxOccurs="unbounded">
				<xsd:element ref="elseif" />
				<xsd:element ref="else" />
				<xsd:group ref="executablecontent" />
			</xsd:choice>
			<xsd:attribute name="cond" type="xsd:string" use="required" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="elseif">
		<xsd:complexType>
			<xsd:choice>
				<xsd:group ref="executablecontent" />
			</xsd:choice>
			<xsd:attribute name="cond" type="xsd:string" use="required" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="else">
		<xsd:complexType>
			<xsd:choice>
				<xsd:group ref="executablecontent" />
			</xsd:choice>
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="log">
		<xsd:complexType>
			<xsd:attribute name="label" type="xsd:string" />
			<xsd:attribute name="expr" type="xsd:string" use="required" />
			<xsd:attribute name="level" type="loglevel" />
		</xsd:complexType>
	</xsd:element>
	<xsd:element name="script">
		<xsd:complexType mixed="true"></xsd:complexType>
	</xsd:element>
	<xsd:simpleType name="targettype">
		<xsd:restriction base="xsd:string">
			<xsd:enumeration value="scxml" />
			<xsd:enumeration value="webservice" />
		</xsd:restriction>
	</xsd:simpleType> <!-- log levels are TBD; values below are taken from Java Commons Logging -->
	<xsd:simpleType name="loglevel">
		<xsd:restriction base="xsd:string">
			<xsd:enumeration value="trace" />
			<xsd:enumeration value="debug" />
			<xsd:enumeration value="info" />
			<xsd:enumeration value="warn" />
			<xsd:enumeration value="error" />
			<xsd:enumeration value="fatal" />
		</xsd:restriction>
	</xsd:simpleType>
</xsd:schema>
      

E CCXML to SCXML Conversion

One of the goals of the SCXML activity is to make sure that the resulting language is compatible with CCXML and that there is an easy path for CCXML scripts to be converted to SCXML without major changes to the programing model or document structure. However, the XSLT script that was included in the first draft of this document is out of date and is therefore omitted in this draft. It will be updated in a future version.

F Examples

F.1 Language Overview

This SCXML document gives an overview of the SCXML language and shows the use of it's state machine transition flows:

Example: Main.scxml
<?xml version="1.0" encoding="us-ascii"?>
<!-- A wrapper state that contains all other states in this file
- it represents the complete state machine -->
<scxml xmlns="http://www.w3.org/2005/07/scxml"
       version="1.0"
       initalstate="Main">  
  <state id="Main">
    <!-- its initial state is Test1 -->
    <initial>
      <transition target="Test1"/>
    </initial>

    <!-- Really simple state showing the basic syntax. -->
    <state id="Test1">
      <initial>
        <transition target="Test1Sub1"/>
      </initial>
      <!-- Runs before we go into the substate -->
      <onentry> 
        <log expr="'Inside Test1'"/>
      </onentry>
      <!-- Here is our first substate -->
      <state id="Test1Sub1">
        <onentry>
          <log expr="'Inside Test1Sub1.'"/>
        </onentry>
        <onexit>
          <log expr="'Leaving Test1Sub1'"/>
        </onexit>
        <!-- Go to Sub2 on Event1 -->
        <transition event="Event1" target="Test1Sub2"/>
      </state>
      <!-- Here is the second substate 
           -    It is final, so Test1 is done when we get here -->
      <state id="Test1Sub2" final="true">
        <onentry>
          <log expr="'Inside Test1Sub2...'"/>
        </onentry>
        <onexit>
          <log expr="'Leaving Test1Sub2'"/>
        </onexit>
      </state>
      <!-- We get this event when we reach Test1Sub2. -->
      <transition event="Test1.done" target="Test2"/>
       <!-- We run this on the way out of Test1 -->
      <onexit>
        <log expr="'Leaving Test1...'"/>
      </onexit>
    </state>

    <state id="Test2">
      <initial>
        <transition target="Test2Sub1"/>
      </initial>
      <!-- This time we reference a state 
           -    defined in an external file -->
      <state id="Test2Sub1" src="Test2Sub1.scxml"/>
  
      <state id="Test2Sub2" final="true">
        <onexit>
          <log expr="'Leaving Substate Test2Sub2'"/>
        </onexit>
      </state>
      <!-- Test2Sub2 is defined as final, so this
           -  event is generated when we reach it -->
      <transition event="Test2.done" next="Test3"/>
    </state>

    <state id="Test3">
      <initial>
        <transition target="Test3Sub1"/>
      </initial>
      <state id="Test3Sub1">
        <onentry>
          <log expr="'Inside Test3Sub1...'"/>
          <!-- Send our self an event in 5s -->
          <send event="Timer"  delay="5s"/>
        </onentry>
    <!-- Transition on to Test4.
      -    This will exit both us and our parent. -->
        <transition event="Timer" target="Test4"/>
        <onexit>
          <log expr="'Leaving Test3Sub1...'"/>
        </onexit>
      </state>
      <onexit>
        <log expr="'Leaving Test3...'"/>
      </onexit>
    </state>
    
    <state id="Test4">
      <onentry>
        <log expr="'Inside Test4...'"/>
      </onentry>
      <initial>
        <transition target="Test4Sub1"/>
        </initial>

        <state id="Test4Sub1" >
           <onexit>
             <log expr="'Leaving Test4Sub1...'"/>
            </onexit>     
              <!-- This transition causes the state to exit immediately
                   - after entering Test4Sub1.  The transition has no event or guard 
                   - so it is always active -->
              <transition target next="Test5"/>
            </state>
       </state>
       
    <state id="Test5">
      <onentry>
        <log expr="'Inside Test5...'"/>
      </onentry>
      <initial>
        <transition target="Test5P"/>
      </initial>
      <!-- Fire off our parallel states -->
      <parallel id="Test5P">
        <state id="Test5PSub1" final="true">
          <onentry>
            <log expr="'Inside Test5PSub1...'"/>
          </onentry>
        </state>
        <state id="Test5PSub2" final="true">
          <onentry>
            <log expr="'Inside Test5PSub2...'"/>
          </onentry>
        </state>
        <onexit>
          <log expr="'all parallel states done'"/>
        </onexit>
      </parallel>
      <!-- The parallel states are all final, so this
           -  event is generated immediately -->
      <transition event="Test5P.done" target="Test6"/>
    </state>

    <!-- 
         - This state shows invocation of external component
         - We will use CCXML + VoiceXML actions as an example 
         - as it is a good smoke test to show how it all 
         - fits together. 
         - Note: Odds are in a real app you would 
         - split this over several states but we 
         - are trying to keep it simple here. 
    -->
    <state id="Test6"
           xmlns:ccxml="http://www.w3.org/2002/09/ccxml"
           xmlns:v3="http://www.w3.org/2005/07/vxml3">
      <datamodel>
        <data name="dest" expr="'tel:+18315552020'"/>
        <data name="src" expr="'helloworld2.vxml'"/>
        <data name="id" expr="'HelloWorld'"/>
      </datamodel>
      <onentry>
        <!--
            - Use <send> to run a createcall using the 
            - CCXML component / Event I/O Processor
        -->
       <send targettype="ccxml" event="ccxml:createcall" namelist="dest"/>
      </onentry>
      <transition event="ccxml:connection.connected">      
        <!--
            - Here as a platform-specific extension we use example V3 
            - Custom Action Elements instead of send . 
        -->
        <v3:form id="HelloWorld">
          <v3:block><v3:prompt>Hello World!</v3:prompt></v3:block>          
        </v3:form>
      </transition>
      <!--
          - Here we are using the low level <send> 
          - element to run a v3 form. Note that the event "v3:HelloWorld.done" 
          is assumed either to be set/sent explicitly by the v3:form code or 
          implicitly by some process outside of the v3:form
      -->
      <transition event="v3:HelloWorld.done">
        <send targettype="v3" event="v3:formstart" namelist="src id"/>
      </transition>
      <transition event="v3:HelloWorld2.done">
      <!-- 
          we use _eventdata to access data in the event we're processing
          -->
        <ccxml:disconnect connectionid="_eventdata.connectionid"/>      
      </transition>
      <transition event="ccxml:connection.disconnected" target="Done"/>
  
      <!-- Transitions to handle events generated by the component
           - component invoked successfully. this transition has no target 
           - so Test6 is not exited.
           - We are just going to log tha we were able to send an event. -->
      <transition event="send.successful">
        <log expr="'Event was able to be sent'"/>
      </transition>
      <!--
          - If we get an error event we move to the Done state that 
          - is a final state. 
      -->
      <transition event="error.send" target="Done">
        <log expr="'Sending to and External component failed'"/>
       </transition>
      <onexit>
        <log expr="'Finished with external component'"/>
      </onexit>
    </state>

    <!-- This final state is an immediate child of Main
         -  when we get here, Main.done is generated. -->
    <state id="Done" final="true"/>
    <!-- End of Main > -->
  </state>
</scxml>
Example: Test2Sub1.scxml
<?xml version="1.0" encoding="us-ascii"?>
<scxml version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> 
  <!-- 
  -
  - This is an example substate defined in
  - an external file referenced by Main.scxml. 
  -
  -->
  <state id="Test2Sub1">
    <onentry>
      <log expr="'Inside Test2Sub1'"/>
     </onentry>
    <transition event="Event2" target="Test2Sub2"/>
  </state>
</scxml>

F.2 Microwave Oven Example

The next example implements a simple microwave oven that can be in one of two states:

On --- the oven is running
Off --- the oven is turned off

State <on> itself has two substates:

Cooking --- the oven is cooking
Idle --- the oven is idle

The oven responds to three external event sources:

Door open/close
Timer that tracks cook-time
Power button

Example: Microwave Oven
State machine diagram for a microwave showing the                         logic for switching among its various states.

SCXML Equivalent:

<?xml version="1.0"?>
<scxml xmlns="http://www.w3.org/2005/07/scxml"
       version="1.0"
       initialstate="off">
  
  <!--  trivial microwave oven example -->
  <state id="off">
    <!-- off state -->
    <transition event="turn_on" target="on"/>
  </state>

  <state id="on">
    <initial>
        <transition target="idle"/>
    </initial>
    <!-- on/pause state -->
    <onentry>
      <!-- we assume the cook_time is passed in as a context parameter -->
      <if cond="${empty cook_time}">
        <!-- default setting -->
        <var name="cook_time" expr="${5}"/>
      </if>
      <!-- again, door_closed should be a part of a global context -->
      <if cond="${empty door_closed}">
        <!-- default setting -->
        <var name="door_closed" expr="${true}"/>
      </if>
      <!-- timer variable -->
      <var name="timer" expr="${0}"/>
    </onentry>

    <transition event="turn_off" target="off"/>
    <transition cond="${timer ge cook_time}" target="off"/>

    <state id="idle">
      <!-- default immediate transition -->
      <transition cond="${door_closed}" target next="cooking"/>
      <transition event="door_close" target="cooking">
        <assign name="door_closed" expr="${true}"/>
        <!-- start cooking -->
        </transition>
    </state>

    <state id="cooking">
      <transition event="door_open" target="idle">
        <assign name="door_closed" expr="${false}"/>
      </transition> 

      <transition event="time" target="cooking">
        <assign name="timer" expr="${timer + 1}"/>
      </transition>
    </state>

  </state>

</scxml>

        

Next, we show the same microwave example, but this time implemented using <parallel>.

Example: Microwave Oven
Microwave logic implemented using concurrency

SCXML Equivalent:

<?xml version="1.0"?>
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"  
       initialstate="oven"> 

  <!--  trivial microwave oven example -->
  <!-- using parallel and In() predicate -->

  <state id="oven">
    <parallel id="parts">
      <state id="engine">
        <transition target="off"/>

        <state id="off">
          <!-- off state -->
          <transition event="turn_on" target="on"/>
        </state>
        
        <state id="on">
          <transition target="idle"/>
           <!-- on/pause state -->
          <onentry>
            <!-- we assume the cook_time is passed in as a context parameter -->
            <if cond="${empty cook_time}">
              <!-- default setting -->
              <var name="cook_time" expr="${5}"/>
            </if>
            <!-- timer variable -->
            <var name="timer" expr="${0}"/>
          </onentry>
          
          <transition event="turn_off" target="off"/>

          <transition cond="${timer ge cook_time}" target="off"/>
          
          <state id="idle">
            <transition cond="${In('closed')}" target="cooking"/>
          </state>
          
          <state id="cooking">
            <transition cond="${not In('closed')}" target="idle"/>

            <transition event="time" target="cooking">
              <assign name="timer" expr="${timer + 1}"/>
            </transition>
          </state>
        </state>
      </state>
      <state id="door">
        <initial>
          <transition target="closed"/>
        </initial>
        <state id="closed">
          <transition event="door_open" target="open"/>

        </state>
        <state id="open">
          <transition event="door_close" target="closed"/>
         </state>
      </state>
    </parallel>
  </state>


</scxml>

        

F.3 Example of Invoke and finalize

This SCXML document demonstrates the use of Invoke and finalize.

Example: Invoke and finalize
<?xml version="1.0"?>
<?access-control allow="*"?>
<smxml initialstate="Intro">
  <state id="Intro">
    <invoke src="dialog.vxml#Intro"/>
    <transition event="success" cond="g_DataModel.sessionChrome.playAds"
target="PlayAds"/>
    <transition event="success" cond="!g_DataModel.sessionChrome.playAds
&amp;&amp; g_DataModel.ANIQuality" target="ShouldGoBack"/>
    <transition event="success" cond="!g_DataModel.sessionChrome.playAds
&amp;&amp; !g_DataModel.ANIQuality" target="StartOver"/>
  </state>

  <state id="PlayAds">
    <invoke src="dialog.vxml#PlayAds"/>
    <transition event="success" cond="g_DataModel.ANIQuality"
target="ShouldGoBack"/>
    <transition event="success" cond="!g_DataModel.ANIQuality"
target="StartOver"/>
  </state>

  <state id="StartOver">
    <onenter>
      <script>enterStartOver();</script>   
    </onenter>
    <invoke src="dialog.vxml#StartOver">
      <param name="gotItFromANI" expr="g_DataModel.gotItFromANI"/>
    </invoke>
    <normalize> 
       <script>finalizeStartOver();</script>   
    </normalize>
    <transition event="success" target="ShouldGoBack"/>
    <transition event="doOver" target="StartOver"/>
    <transition event="restart" target="Intro"/> <!-- bail out to caller
-->
  </state>

  <state id="ShouldGoBack">
    <invoke src="dialog.vxml#ShouldGoBack">
      <param name="cityState" expr="g_DataModel.cityState"/>
      <param name="gotItFromANI" expr="g_DataModel.gotItFromANI"/>
    </invoke>
    <normalize> 
      <script>finalizeShouldGoBack();</script>   
    </normalize>
    <transition event="highWay" target="HighwayReport"/>
    <transition event="go_back" target="StartOver"/>
    <transition event="doOver" target="ShouldGoBack"/>
    <transition event="restart" target="Intro"/>
  </state>

  <state id="HighwayReport">
    <invoke src="dialog.vxml#HighwayReport">
      <param name="cityState" expr="g_DataModel.cityState"/>
      <param name="gotItFromANI" expr="g_DataModel.gotItFromANI"/>
      <param name="playHRPrompt" expr="g_DataModel.playHRPrompt"/>
      <param name="metroArea" expr="g_DataModel.metroArea"/>
    </invoke>
    <normalize> 
      <script>finalizeHighwayReport();</script>   
    </normalize>
    <transition event="highway" target="PlayHighway"/>
    <transition event="go_back" target="StartOver"/>
    <transition event="doOver" target="HighwayReport"/>
    <transition event="fullreport" target="FullReport"/>
    <transition event="restart" target="Intro"/>
  </state>

  <state id="FullReport">
    <invoke src="dialog.vxml#FullReport">
      <param name="cityState" expr="g_DataModel.cityState"/>
      <param name="metroArea" expr="g_DataModel.metroArea"/>
    </invoke>
    <normalize> 
       <script>finalizeFullReport();</script>   
    </normalize>
    <transition event="go_back" target="HighwayReport"/>
    <transition event="new_city" target="StartOver"/>
  </state>

  <state id="PlayHighway">
    <invoke src="dialog.vxml#PlayHighway">
      <param name="cityState" expr="g_DataModel.cityState"/>
      <param name="curHighway" expr="g_DataModel.curHighway"/>
    </invoke>
    <normalize> 
      <script>finalizePlayHighway();</script>   
    </normalize>
    <transition event="go_back" target="HighwayReport"/>
  </state>
</smxml>

Another example application (again that actually runs and works) that might be appropriate in the appendix/examples at the end is blackjack:

<?xml version="1.0"?>
<?access-control allow="*"?>
<smxml initialstate="master">
<state id="master">
    <initial id="init1">
      <transition target="_home"/>
    </initial>
    <transition event="new_dealer" target="NewDealer"/>
    <transition event="mumble" target="_home"/> <!-- bail out to caller
-->
    <transition event="silence" target="_home"/> <!-- bail out to caller
-->
    <state id="_home">
      <onenter>
        <script>
        g_DataModel = {};
        </script>
      </onenter>    
      <invoke src="datamodel.v3#InitDataModel"/>
      <normalize>
        <script>
        var n;
        for (n in g_InvokeResults) {
            g_DataModel[n] = g_InvokeResults[n];
        }
        </script>
      </normalize>
      <transition event="success" target="Welcome"/>
    </state>

    <state id="Welcome">
      <invoke src="dialog.vxml#Welcome">
        <param name="skinpath" expr="g_DataModel.skinpath"/>
      </invoke>
      <transition event="success" target="Intro2"/>
    </state>

    <state id="Intro2">
      <invoke src="dialog.vxml#Intro2">
        <param name="skinpath" expr="g_DataModel.skinpath"/>
      </invoke>
      <transition event="success" target="EvalDeal"/>
    </state>

    <state id="EvalDeal">
      <onenter>
        <script>enterEvalDeal();</script>
      </onenter>    
      <invoke src="dialog.vxml#EvalDeal">
        <param name="skinpath" expr="g_DataModel.skinpath"/>
        <param name="playercard1" expr="g_DataModel.playercard1"/>
        <param name="playercard2" expr="g_DataModel.playercard2"/>
        <param name="playertotal"
expr="g_DataModel.blackjack.GetTotalOf('caller').toString()"/>
        <param name="dealercardshowing"
expr="g_DataModel.dealercardshowing"/>
      </invoke>
      <transition event="success" target="AskHit"/>
    </state>

    <state id="AskHit">
      <invoke src="dialog.vxml#AskHit">
        <param name="skinpath" expr="g_DataModel.skinpath"/>
      </invoke>
      <normalize> 
         <script>finalizeAskHit();</script>   
      </normalize>
      <transition event="hit" target="PlayNewCard"/>
      <transition event="stand" target="PlayDone"/>
    </state>

    <state id="PlayNewCard">
      <invoke src="dialog.vxml#PlayNewCard">
        <param name="skinpath" expr="g_DataModel.skinpath"/>
        <param name="playernewcard" expr="g_DataModel.playernewcard"/>
        <param name="playertotal"
expr="g_DataModel.blackjack.GetTotalOf('caller').toString()"/>
      </invoke>
      <transition event="success"
cond="g_DataModel.blackjack.GetTotalOf('caller') &gt;= 21"
target="PlayDone"/>      
      <transition event="success" target="AskHit"/> <!-- less than 21
--> 
    </state>

    <state id="PlayDone">
      <onenter>
        <script>enterPlayDone();</script>
      </onenter>    
      <invoke src="dialog.vxml#PlayDone">
        <param name="skinpath" expr="g_DataModel.skinpath"/>
        <param name="gameresult"
expr="g_DataModel.blackjack.GetGameResult()"/>
        <param name="dealertotal"
expr="g_DataModel.blackjack.GetTotalOf('dealer').toString()"/>
      </invoke>
      <transition event="playagain" target="Intro2"/>
      <transition event="quit" target="_home"/>      
    </state>

    <state id="NewDealer">
      <onenter>
       <script>enterNewDealer();</script>
      </onenter>
      <invoke src="dialog.vxml#Dummy"/>
      <transition event="success" target="Welcome"/>    
    </state>
  </state>
</smxml>

G An Overview of UML Notation and SCXML Semantics

This section will outline the most salient features of SCXML semantics, as well as the corresponding UML notation. A future version of this document will define the semantics of SCXML in greater detail. Diagram 1 shows a simple state machine with three states S1, S2, and S3.

G.1 A Simple State Machine

Example: A Simple State Machine
a basic diagram with three states

SCXML Equivalent

 <?xml version="1.0" encoding="us-ascii"?>
<scxml version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> 
  <state id="S1">
    <transition event="Event1" target="S2"/>
  </state>
 
  <state id="S2">
    <transition event="Event2" cond="X>0" target="S1"/>
    <transition event="Event2" cond ="X<0" target next="S3"/>
  </state> 
  
  <state id="S3">
  </state>
  
</scxml>

        

These states linked by transitions, which are triggered by events. In this example State S1 transitions to state S2 when the event Event1 occurs. This is the only way the system can move from S1 to S2, since it is the only transition between those two states. Any other events that occur while the system is in S1 will therefore be ignored. The logic in S2 is slightly more complex. It has two transitions, both triggered by event Event2. Both transitions have guard conditions that check the value of the variable X. If X < 0, S2 will transition to S3 when Event2 occurs. If X > 0, it will transition back to S2. Note that there is no condition covering the case where X = 0. Therefore the system will remain in state S2 if X = 0 when Event2 occurs. As in state S1, all events not mentioned in transitions will be ignored.

G.2 Executing Actions On Entering And Exiting

OnEntry and OnExit handlers are a useful feature of Harel State Tables. They allow code to be embedded in states that will be executed whenever the state is entered or exited. In Diagram 2 we see the same three states, but now S1 has an OnEntry handler that decrements X , while S2 has an OnExit handler that also decrements X. S3 has both OnEntry and OnExit handlers, both of which increment X. Now suppose that X has a current value of 2, and that the system enters S1. When it does so, X is decremented to 1. When Event1 occurs, the system will transition to S2, as before. Now when Event2 occurs, X is equal to 1, so the system will transition back to S1. As the system exits state S2, the OnExit handler will decrement X to 0. Note that this happens after the transition is selected and the guard condition has been evaluated. X. The entry into S1 decrements X again to -1. Now if Event1 occurs again and the system returns to S2, it will transition to S3 when Event2 occurs, since X is now < 0. Leaving S2 will decrement X again, but entering S3 will increment it, so X = -1 when the system is in S3. S3 has no transitions so the system will stay in S3 forever. However if a transition is added to S3, the OnExit handler in S3 will set Y to 0 when S3 is exited.

Example: Diagram 2. OnEntry and OnExit Handlers
diagram with onentry and onexit handlers added

SCXML Equivalent

 <?xml version="1.0" encoding="us-ascii"?>
<scxml version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> 
  <datamodel>
    <data name="X" expr="2"/>
  </datamodel>
  
  <state id="S1">
    <onentry> 
      <assign name="X" expr="X--"/>
    </onentry>
    <transition event="Event1" target="S2"/>
   </state>
 
  <state id="S2">
    <transition event="Event2" cond= "X>0" target="S1"/>
    <transition event="Event2" cond ="X><0" target="S3"/>
    <onexit> 
      <assign name="X" expr="X--"/>
    </onexit>    
  </state> 
  
  <state id="S3">
    <onentry> 
      <assign name="X" expr="X++"/>
    </onentry>
    <onexit> 
      <assign name="Y" expr="0"/>
    </onexit>       
  </state>
  
</scxml>

        

G.3 Complex States

Of particular interest is the concept of a complex state, namely one that has substates. In Diagram 3 below, the State S1 now has two substates, labeled S11 and S12.

Example: Diagram 3. A State with Sequential Substates
diagram with sequential substates added

SCXML Equivalent

 <?xml version="1.0" encoding="us-ascii"?>
<scxml version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> 

  <state id="S1">
    <state id="S11">
    </state>
    <state id="s12">
    </state>
    <initial>
      <transition target next="S11"/>
    </initial>    
  </state>
</scxml>


        

In this particular case, S1 has sequential substates. When a state machine is in a state with such substates, it must also be in one and only one of the substates. The substates have a kind of "Or" semantics and can be thought of as representing a decomposition of the parent state. A transition moving the system to S1 may specify S11 or S12 as its "target" directly. However, to handle the case where it doesn't, S1 contains an <initial> element defining the default substate that it will start in if the transition simplify specifies S1 as its destination. In Diagram 3, the default substate is S11.

G.4 Parallel States

In addition to sequential substates, Harel State Charts provide concurrent substates, which represent a form of "And" logic. When a state machine is in a state with concurrent substates it must be simultaneously in each of the concurrent child states. The concurrent child states operate independently until they all terminate (normally by reaching terminal child states) at which point the parent state also terminates. Concurrent substates thus represent fork and join logic. They are represented in our notation by the <parallel> tag. Diagram 4 below represents an elaboration of Diagram 3. First of all, State S11 has been decomposed into further sequential substates, S111 and S112, with S111 being the default initial state. Secondly, concurrent substates S121, S122, and S123 have been added to State S12.

Example: Diagram 4. A Combination of Concurrent and Sequential Substates
diagram with both sequential and concurrent substates added

SCXML Equivalent

 <?xml version="1.0" encoding="us-ascii"?>
<scxml version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> 

  <state id="S1">
    
    <state id="S11">
      <state id="S111"/>
      <state id="S112"/>
      <initial>
        <transition target next="S111"/>
      </initial>  
    </state>
    
    <state id="s12">
      <parallel>
        <state id="S121"/>
        <state id="S122"/>
        <state id="S123"/>
      </parallel>
    </state>
    
    <initial>
      <transition target="S11"/>
    </initial>
  </state>

  <state>   
  </state>
</scxml>

        

As Diagram 4 shows, the notion of complex state is fully recursive, so that the child states of a complex parent may themselves have sequential or concurrent children. Thus a complex state machine is not normally in a single state, but in a configuration of compatible states. Applying the rules for sequential and concurrent states recursively in Diagram 4, we see that when the machine is in S1 it must also be in S11 or S12. When the machine is in S11, it must be in S111 or S112. When the machine is in S12, on the other hand, it must simultaneously be in all three substates S121, S11 and S1123. Thus there are 3 legal configurations they machine can be in: S1 plus S11 plus S111, S1 plus S11 plus S112, and S1 plus S12 plus S121, S122, and S123.

G.5 Concurrency And Event Queues

The Harel semantics for transitions is based on the notion of an underlying event queue. At any given point, the state machine is in a specific configuration of states. If there is an event in the queue, it is processed according to the given state configuration, and a transition may be triggered. The transition is then taken and it and all actions associated with it are executed before the next event in the queue is examined. Of particular interest is the way that <onexit> and <onevent> handlers interact with transitions. Suppose the machine is in state S2 (which is not shown in the diagram) and an event occurs which triggers a transition to state S112 in Diagram 4. In this case, the machine first leaves S2, executing S2's <onexit>handlers. It then executes any <actions> in the selected transitions. Then it enters S1, S11, and S112 executing their <onentry> handlers in that order. Only when all these actions have been executed will the machine check its queue for another event. Suppose that there is an event in the queue and it triggers a transition from S112 to S12. Going to S12 entails leaving both S112 and S11, so both their <onexit> handlers fire in that order, before the executable content in the transition. (Note that the <onexit> handlers fire in the reverse order of the <onentry> handlers.) Since S11 and S12 are both substates of S1, this transition does not entail leaving S1 so its <onexit> handler does not fire. After the transition's <actions>, S12's <onentry> handler will fire. Furthermore, the semantics of parallel states requires that entering S12 also involves entering each of its concurrent substates simultaneously. Therefore the <onentry> handlers for S121, S122, and S123 will all fire after the one for S12. Since entry into the parallel substates is simultaneous, however, there is no guarantee on the order in which the three substate handlers fire.

Complex state configurations also interact with the selection of the transition to execute. First off, note that even a simple state may contain multiple transitions that match a given event. For example State S1 may contain two transitions, T1 which is triggered by event E1 with guard Cond1, and T2 which is also triggered by E1, but with a different guard expression Cond2. If the machine is in S2 when event E1 is taken from the queue and processed, it is possible that both Cond1 and Cond2 will evaluate to true. In this case, we will say that both T1 and T2 are enabled, but only one of them can be selected and executed. In the case of a single state, we will use document order as the tie-breaker, choosing whichever transition occurs first in the definition of S1. With complex states, the issue is more difficult. Returning to Diagram 4, suppose that we are in the complex configuration S1, S11, and S112, when event E1 is processed. It is possible that all three states, S1, S11, and S112, contain transitions that are enabled. In this case, we start in the innermost state S112. If it has an enabled transition, we select it (using document order as a tie-breaker if it has more than one.) If S112 does not contain an enabled transition, we look in S11 and then in S1. Thus the most narrowly scoped transition wins. The motivation for this choice becomes clear when we remember that sequential substates are decompositions of the parent state. Thus S112 is a refinement of S11 and S11 in turn is a refinement of S1. The innermost state thus "knows the most" about the situation so its transitions are preferred to those in outer states, which can be treated as defaults or fallbacks.

In the case of concurrent substates, the event is processed by all concurrent states simultaneously and they select their transitions independently. Thus if we are in S1, S12 and parallel substates S121, S122, and S123, any event will be processed by S121, S122, and S123 simultaneously, and they may all select transitions. This makes most sense if all three states are themselves complex and the event is triggering transitions among their substates. If none of the three states handles the event, we move to S12 and then to S1.

Although parallel substates run independently their operations can be coordinated by means of Join states. The Join pseudo-state is has multiple incoming transitions and one or more outgoing transition. The incoming transitions must be unconditional (i.e., they cannot have <cond> or <event> properties.) The outgoing transitions on the <join> may not have <event> triggers and at least one must lack a <cond> guard condition. Thus when the <join> pseudo-state is finally entered, there is always a transition that can be taken immediately. The <join> pseudo-state is not entered until all its incoming transitions are enabled. Thus the various threads of control wait in their current states until they are all ready to enter the <join>, at which point they all enter simultaneously and an outgoing transition is selected.

Now suppose we have two parallel states, S1 and S2, with sequential substates S11, S12, S13 and S21, S22 and S23, as shown in Diagram 5.

Example: Diagram 5. Parallel States to be Coordinated
diagram with concurrent substates added
 <?xml version="1.0" encoding="us-ascii"?>
<scxml version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> 

  <state>
    <parallel>
      
      <state id="S1">
        <state id="S11">
          <transition target="S12"/>
        </state>
        <state id="S12">
          <transition target="S13"/>
        </state>
        <state id="S13"/>
      </state>
      
      <state id="S2">
        <state id="S21">
          <transition target="S22"/>

        </state>
        <state id="S22">
          <transition target="S23"/>
 
        </state>
        <state id="S23"/>
      </state>
      
    </parallel>
  </state>
</scxml>

        

G.6 Synchronizing And Concurrency

Given the basic Harel semantics S1 and S2 will function independently, so that S1 will move from S11 to S12 to S13 without regard to what S2 is doing, and vice-versa. But now suppose that we want to ensure that S2 does not transition from S22 to S23 until S1 has left S11. Diagram 6 shows how we can do this using a <join> state.

Example: Diagram 6. Use of the Join State
diagram with joinc state added

SCXML Equivalent

 <?xml version="1.0" encoding="us-ascii"?>
<scxml version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> 

  <state>
    <parallel>
      
      <state id="S1">
        <state id="S11">
          <transition target next ="S12 synch1"/>
        </state>
        <state id="S12">
          <transition target next="S13"/>
        </state>
        <state id="S13"/>
        </state>
      
      <state id="S2">
        <state id="S21">
          <transition target="S12"/>
        </state>
        <state id="S22>
          <transition target="j1"/>
         </state>
        <state id="S23"/>
        <join id="j1">
        <transition target="S23"/>
        </join>
      </state>
    
    </parallel>
  </state>
</scxml>

        

We have inserted a <join> pseudo-state between S22 and S23, with a conditionless incoming transition from S22 and a conditionless outgoing transition to S23. (The <join> pseudo-state is represented as a vertical bar with multiple incoming transitions and a single outgoing transition.) Then we took the transition leaving S11 and made it branch to include the <join> state as an extra target. (In the diagram this is shown by inserting a 'fork' vertical bar, with a single incoming transition and multiple outgoing transitions. In our SCXML notation, we use multiple values in the "target" element). Now when the machine reaches S22, it will wait until the <join> state is active (and therefore ready to transition) before entering the <join> and transitioning to S23. Similarly, when S1 is ready to leave S11, it will wait until S2 reaches S22 before entering the <join> state. In either case, the effect of the <join> state is to cause S1 and S2 wait for each other and then to enter S12 and S23 simultaneously.

H References

CSS2
Cascading Style Sheets, level 2: CSS2 Specification. B. Bos, et al., Editors. World Wide Web Consortium, 12 May 1998. This version of the CSS2 Recommendation is http://www.w3.org/TR/1998/REC-CSS2-19980512/. The latest version of CSS2 is available at http://www.w3.org/TR/REC-CSS2/. (See http://www.w3.org/TR/1998/REC-CSS2-19980512/.)
OASIS ebXML
ebXML Business Process Specification Schema v2.0. (See http://www.oasis-open.org/committees/documents.php?wg_abbrev=ebxml-bp.)
Harel and Politi
Modeling Reactive Systems with Statecharts: The STATEMATE Approach By D. Harel and M. Politi. McGraw-Hill, 1998. (See http://www.wisdom.weizmann.ac.il/~dharel/reactive_systems.html.)
IETF RFC 2119
RFC 2119: Key words for use in RFCs to Indicate Requirement Levels. Internet Engineering Task Force, 1997. (See http://www.ietf.org/rfc/rfc2119.txt.)
IETF RFC 2396
RFC 2396: Uniform Resource Identifiers. Internet Engineering Task Force, 1995. (See http://www.ietf.org/rfc/rfc2396.txt.)
W3C CCXML 1.0
Voice Browser Call Control: CCXML Version 1.0. W3C, 2005. (See http://www.w3.org/TR/2005/WD-ccxml-20050111/.)
W3C MMI
CMultimodal Architecture and Interfaces Working Dra. W3C, 2005. (See http://www.w3.org/TR/mmi-arch/.)
W3C VoiceXML 2.0
VoiceXML 2.0: Format for Literal IPv6 Addresses in URL's. W3C, 2004. (See http://www.w3.org/TR/VoiceXML20.)
UML 2.0
UML Specification Version 2.0. OMG. (See http://www.uml.org/#UML2.0)
UML XMI
XML Metadata Exchange version 2.1. (See http://www.omg.org/technology/documents/modeling_spec_catalog.htm#XMI.)
XTND
XML Transition Network Definition. (See http://www.w3.org/TR/2000/NOTE-xtnd-20001121/.)