Overview

The State Machine plugin serves as a configurable programming point for JADE systems by supporting a state machine implementation in configuration. State machines are composed of states which generally can take some “actions” and define logic for if and how to transition to other states. For the State Machine plugin, the “actions” one can specify in a given state are:

  • performing computations
  • sending messages to:
    – specific plugins (any which support such messages)
    – subscribers (any plugins which have subscribed to the State Machine instance)
    – the command line

This plugin can subscribe to any other plugins and will maintain a cache of that data for use when performing computations or sending messages This overall setup allows the state machine to flow through a defined set of logically controlled states which use any subscription data and any of its own computations.

User Interface

The State Machine interface is simple by design, containing three strings: one for the Latest Message (displayed on top left), one for the Merged Messages (displayed on the bottom left), and one for displaying the @VAR{} variable container with all computations in it (displayed on the right). The first two are updated as messages are received, the latter is updated whenever computations are performed, and a splitter provides the ability to change how much of each JSON object is shown at a given time. Below we show the State Machine interface with example data:


Subscription Data Handling

The State Machine plugin accepts published JSON messages and displays both the Latest Message and Merged Messages. As data arrives, the State Machine plugin aggregates that data into the Merged Messages object, which is available to states in an @SUB{} variable container. Let’s look at an example to help build our mental model for how subscription data is handled. Suppose the State Machine plugin subscribes to two plugins named MySerialPublisher1 and MySerialPublisher2 which publish temperature and pressure data respectively.

Suppose MySerialPublisher1 publishes:

{
    "instanceName": "MySerialPublisher1",
    "temperature": 22.4,
    "unit": "Celcius"
}

Suppose MySerialPublisher2 publishes:

{
    "instanceName": "MySerialPublisher2",
    "pressure": 148.7,
    "unit": "PSI"
}

When those published messages arrive, the State Machine will look for the special key instanceName which uniquely identifies the source of the data and use its value as a top level key name for storing the incoming data. It does this “namespacing” of sorts to avoid naming collisions in the Merged Messages object. Don’t worry, you can configure the list of such “special keys” in the State Machine’s messageSourceKeyNames configuration option, but almost all publishing plugins use instanceName. In this case, the incoming data results in the following Merged Messages object:

{
    "MySerialPublisher1": {
        "instanceName": "MySerialPublisher1",
        "temperature": 22.4,
        "unit": "Celcius"
    },
    "MySerialPublisher2": {
        "instanceName": "MySerialPublisher2",
        "pressure": 148.7,
        "unit": "PSI"
    }
}

With that data in the @SUB{} variable container, we could - for example - access the temperature from MySerialPublisher1 as @SUB{MySerialPublisher1.temperature}.

Subscription Data Special Cases

Ok, so we know we can handle messages published from plugins who use a special key to identify themselves. Let’s cover some special cases:

  1. What happens if data comes in without the special instaneName key?
    In that case, the State Machine will simply put that data under a top level key named __UNKNOWN_MESSAGE__.

  2. I know the Worker can publish data such as the statuses of all plugins. How do I subscribe to that data and how does it get set in the Merged Messages object?
    First, the State Machine would need to subscribe to __PLUGIN_INFO__ (literally just add __PLUGIN_INFO__ to the subscribesTo array in configuration). Then the question becomes, what special key does the Worker use to identify itself. The answer is workerName. So as long as the messageSourceKeyNames array in the State Machine’s configuration has workerName in it, you’re all set.

  3. What if I want my plugin data to go under a different top level key in Merged Messages?
    Well, the list of special keys are be configured in messageSourceKeyNames. The messageSourceKeyNames (string array) defaults to ["instanceName", "workerName"] to cover the common/standard cases right “out of the box”, but you have full control over this just in case.

  4. What if my plugin publishes both an instanceName as well as a uniqueId key, but I want to use the uniqueId instead of the instanceName for the top level key in Merged Messages?
    In this case, you’d just add uniqueId to the front of the messageSourceKeyNames array. When incoming messages are processed, the order of the strings in messageSourceKeyNames determines the order of precedence for which special key gets used. In other words, the first one in the array to be found in the incoming subscription message gets used.

Example

Below is an example of a simple machine definition (the machine snippet of the overall plugin configuration) with two states (Initialize and ToggleRelays) which toggles the states of two relays. The form of the message sent to the Relay Manager instance (below named “Relay Manager”) is of course defined by the Relay Manager itself. Notice the initialState defines where we enter the machine and the states object allows defining the machine’s states.

{
    "initialState": "Initialize",
    "states": {
        "Initialize": {
            "computations": [
                {
                    "enable": true,
                    "mode": "Merge",
                    "variables": {
                        "relayState": false
                    }
                }
            ],
            "messages": [],
            "nextState": "ToggleRelays",
            "transitionDelay": 0
        },
        "ToggleRelays": {
            "computations": [
                {
                    "enable": true,
                    "mode": "Merge",
                    "variables": {
                        "relayState": "Boolean:( !@VAR{relayState} )"
                    }
                }
            ],
            "messages": [
                {
                    "enable": true,
                    "target": "Relay Manager",
                    "message": {
                        "operation": "Update Relays",
                        "data": {
                            "relayStates": [
                                {
                                    "relay": "All Relays.Relay 1",
                                    "state": "Boolean:( @VAR{relayState} )"
                                },
                                {
                                    "relay": "All Relays.Relay 2",
                                    "state": "Boolean:( !@VAR{relayState} )"
                                }
                            ]
                        }
                    }
                }
            ],
            "nextState": "ToggleRelays",
            "transitionDelay": 1000
        }
    }
}

Notice that each state has elements:

  • computations is an array of computation objects
  • messages is an array of messages to send)
  • nextState is a string defining the next state to which to transition
  • transitionDelay is the delay to wait until transitioning to the next state

Notice that each message has a target which defines where each message goes:

  • __WORKER__ to send a message to the worker
  • __SUBSCRIBERS__ to send a message to any subscribers of the state machine
  • __TERMINAL__ to issue a command to the command line
  • <any plugin instance name> to send a message to any specific plugin by its instance name (but do not include the < and > characters ;-)

An enable option is available on computations and messages so that they can be conditionally computed/sent as needed in the application. Also, owing to expression support throughout the entire state machine definition, any option under the machine option can be specified as a string expression with a return type: see the Expression Language documenation for more on this. Further details of the state machine configuration options are captured in the detailed documentation below.


Configuration Example

Plugin Defaults
0
0
0

Configuration Details

Filter:Search in:
ROOT object
This top level object holds all configuration information for this plugin.
Required: true
Default: (not specified; see any element defaults within)
subscribesTo array
An array of plugin instance names corresponding to plugin instances which will be subscribed to by this plugin instance.
Required: true
Default:
[]
subscribesTo[n] string
A plugin instance name (corresponding to a plugin you wish to subscribe to) or a topic published by the worker (ex. __PLUGIN_INFO__).
Required: false
Default: ""
options object
Configuration options specific to this plugin. Note that variables and expressions are generally allowed in this section.
Required: true
Default: (not specified; see any element defaults within)
options.messageSourceKeyNames array
An array of key names to look for when inspecting incoming messages for merge. The first element in this array found as a key name in the Latest Message will be used as the key under which that message will be placed in the Merged Messages object. If no key is found, the message will be placed under a key named "__UNKNOWN_SOURCE__".
Required: true
Default:
[
    "workerName",
    "instanceName"
]
options.messageSourceKeyNames[n] string
A key name to look for when inspecting incoming messages for merge.
Required: false
Default: ""
options.enableDebugLogging boolean
Whether to enable debug logging which will log states (with computations completed) to the log files defined by the logger.
Required: true
Default: false
options.machine object
An object defining the state machine.
Required: true
Default:
{
    "initialState": "Initialize",
    "states": {
        "Initialize": {
            "computations": [
                {
                    "enable": true,
                    "mode": "Merge",
                    "variables": {
                        "ready": true
                    }
                }
            ],
            "messages": [],
            "nextState": "DoSomething",
            "transitionDelay": 0
        },
        "DoSomething": {
            "computations": [],
            "messages": [],
            "nextState": "",
            "transitionDelay": 1000
        }
    }
}
options.machine.initialState string
The state which the machine enters to start the state machine.
Required: true
Default: "Initialize"
options.machine.states object
An object containing states; keys are the state names and values are objects defining the state.
Required: true
Default:
{
    "Initialize": {
        "computations": [
            {
                "enable": true,
                "mode": "Merge",
                "variables": {
                    "ready": true
                }
            }
        ],
        "messages": [],
        "nextState": "OtherState",
        "transitionDelay": 100
    }
}
options.machine.states.{State Name} object
An object defining the behavior of a state.
Required: false
Default: (not specified; see any element defaults within)
options.machine.states.{State Name}.computations array
An array containing objects which define computations to perform. Variable set here are put into an @VAR{} variable container which is accessible to computations. Computations also have access to an @SUB{} variable container with data from any subscriptions, where all incoming plugin subscription data is put under a primary key name equal to the plugin instance name. Note that these computations (and elsewhere in the state definition) my occur before some subscription data is available. Use approaches such as @SUB{IsDefined(myVar)} to ensure variables exist before using them meaningfully.
Required: true
Default:
[]
options.machine.states.{State Name}.computations[n] object
An object describing a set of computations to perform. Note that computations in the same object should not be dependent upon one another. Use separate objects in the computations array to guarantee the order in which computations are performed.
Required: false
Default: (not specified; see any element defaults within)
options.machine.states.{State Name}.computations[n].enable booleanstring
Whether to enable / perform the computations specified in this object.
Required: true
Default: true
options.machine.states.{State Name}.computations[n].mode enum (string)
The mode to use when updating values.
Required: true
Default: "Merge"
Enum Items: "Merge" | "Upsert" | "Update Only" | "Append Only" | "Replace"
options.machine.states.{State Name}.computations[n].variables object
An object where keys define json paths to write and values are the value to write at the specified json path.
Required: true
Default: (not specified; see any element defaults within)
options.machine.states.{State Name}.computations[n].variables.{Valid JSON Set Path} stringnumberbooleanarrayobject
undefined
Required: false
Default: ""
options.machine.states.{State Name}.messages array
An array containing objects which define messages to send.
Required: true
Default:
[]
options.machine.states.{State Name}.messages[n] object
An object describing a message to send.
Required: false
Default: (not specified; see any element defaults within)
options.machine.states.{State Name}.messages[n].enable booleanstring
Whether to enable / perform the computations specified in this object.
Required: true
Default: true
options.machine.states.{State Name}.messages[n].target string
Where to send the message. Valid values include: 1. __WORKER__ to send a message to the application worker (ex. to run a plugin), 2. __SUBSCRIBERS__ to send a message to any subscribers of the state machine plugin instance, 3. __TERMINAL__ to issue a command line argument to underlying system / operating system, or 4. any plugin instance name to send a message to the corresponding plugin instance. See plugin documentation for messages handled by each plugin, and worker documentation for messages handled by the worker.
Required: true
Default: ""
options.machine.states.{State Name}.messages[n].message stringnumberbooleanarrayobject
A message of any type supported by the target. For messages targeting __WORKER__ or plugin instances, this will often be a JSON object with something like "operation" and "data" keys, but is ultimately decided by the receiver of the message. For the __TERMINAL__ target, the message must be an object with the following parameters: commandLine (string | required | description: the command to execute), standardInput (string | optional | description: the standard input to supply, if any), waitUntilComplete (boolean | optional | default: true | description: whether to wait synchronously until the command completes, or to simply continue without assigning output variables), runMinimized (boolean | optional | default: true | description: whether to run the terminal window minimized), expectedOutputSize (integer in bytes | optional | default: 4096 | description: though not required, this parameter can help optimize run-time performance; set this to slightly greater than the expected response), workingDirectory (string path | optional | description: do not use working directory to locate the executable you want to run; this parameter applies to the executable only after it launches). See the JADE documentation for plugins and the framework for more information.
Required: true
Default:
{}
options.machine.states.{State Name}.terminate booleanstring
Whether to terminate the state machine. Note that, if true, this does not shut down the plugin, but simply terminates the state machine. This way, for example, you may still observe final variable values in the interface. Furthermore, this termination is strictly a state machine semantic, not a plugin semantic, and therefore we would not want to conflate doing something to the entire plugin when it should only impact the state machine therein.
Required: false
Default: false
options.machine.states.{State Name}.nextState string
The next state to enter (unless the machine is terminated). Note that if 'terminate' evaluates to true the machine will indeed terminate and the next state specified here will not be reached. Also note that states (and expressions used therein) may execute before incoming subscription data arrives. Thus, be mindful that variables in the @PUB{} container may not exist. Missing variable errors are generally not thrown when expressions in state machines are evaluated, so boolean expressions using missing variables will return false.
Required: true
Default: ""
options.machine.states.{State Name}.transitionDelay stringinteger
An integer representing the delay in milliseconds before entering the next state.
Required: true
Default: 0
options.logger object
Defines the logging (data and errors) for this plugin. Note that a LOG variable space is provided here, as well as the VAR variable space. Available variables are: @LOG{LOGGERNAME}, @LOG{TIMESTAMP}, @LOG{LOGMESSAGE}, @LOG{ERRORMESSAGE}, and @VAR{instanceName} are available variables. note: @LOG{LOGGERNAME} is equal to the @VAR{instanceName} here.
Required: true
Default: (not specified; see any element defaults within)
options.logger.Enable boolean
Whether to enable the logger.
Required: true
Default: true
options.logger.LogFolder string
The folder in which to write log files.
Required: true
Default: "\\JADE_LOGS\\@VAR{instanceName}"
options.logger.FileNameFormat string
The filename to use when creating log files. Note: if the filesize limit is reached new files will be created with enumerated suffixes such as: MyLogFile-1.txt, MyLogFile-2.txt, etc.
Required: true
Default: "@VAR{instanceName}-@LOG{TIMESTAMP}.log"
options.logger.ErrorsOnly boolean
Whether to log only errors.
Required: true
Default: true
options.logger.DiskThrashPeriod integer
The period in milliseconds with which to flush the file buffer to ensure it's committed to the hard drive. Note: This is a performance consideration to prevent writing to disk too frequently.
Required: true
Default: 1000
options.logger.FileSizeLimit integer
The file size at which to create new files.
Required: true
Default: 1000000
options.logger.StartLogFormat string
The initial string to put into the log file when opened for the first time.
Required: true
Default: "**** START LOGGER - @LOG{LOGGERNAME} (@LOG{TIMESTAMP}) ****"
options.logger.EndLogFormat string
The final string to put in the log file when closed.
Required: true
Default: "\n\n**** END LOGGER - @LOG{LOGGERNAME} (@LOG{TIMESTAMP}) ****"
options.logger.LogEntryFormat string
The format to use when writing log entries when errors are not present.
Required: true
Default: "\n\n@LOG{LOGMESSAGE}"
options.logger.ErrorLogEntryFormat string
The message format used to construct error log entries.
Required: true
Default: "\n\n@LOG{ERRORMESSAGE}"
options.logger.TimestampFormat string
The format used by the @LOG{TIMESTAMP} variable.
Required: true
Default: "%Y-%m-%d %H-%M-%S%3u"
panel object
Required: true
Default: (not specified; see any element defaults within)
panel.open boolean
Whether to open the front panel immediately when run.
Required: true
Default: true
panel.state enum (string)
The state in which the window will open.
Required: true
Default: "Standard"
Enum Items: "Standard" | "Hidden" | "Closed" | "Minimized" | "Maximized"
panel.transparency integer
The transparency of the window. 0 = opaque, 100 = invisible.
Required: true
Default: 0
panel.title string
The title of the plugin window when it runs. Note that the variable 'instanceName' is provided here in a VAR variable container.
Required: true
Default: "@VAR{instanceName}"
panel.titleBarVisible boolean
Whether the window title bar is visible.
Required: true
Default: true
panel.showMenuBar boolean
Whether the menu bar is visible.
Required: true
Default: false
panel.showToolBar boolean
Whether the toolbar is visible.
Required: true
Default: false
panel.makeActive boolean
Whether the window becomes active when opened.
Required: true
Default: false
panel.bringToFront boolean
Whether the window is brought to the front / top of other windows when opened.
Required: true
Default: false
panel.minimizable boolean
Whether the window is minimizable.
Required: true
Default: true
panel.resizable boolean
Whether the window is resizable.
Required: true
Default: true
panel.closeable boolean
Whether the window is closeable.
Required: true
Default: true
panel.closeWhenDone boolean
Whether to close the window when complete.
Required: true
Default: true
panel.center boolean
Whether to center the window when opened. Note: this property overrides the 'position' property.
Required: true
Default: false
panel.position object
The position of the window when opened the first time.
Required: true
Default: (not specified; see any element defaults within)
panel.position.top integer
The vertical position of the window in pixels from the top edge of the viewport. Note: this property is overriden by the 'center' property.
Required: true
Default: 100
panel.position.left integer
The horizontal position of the window in pixels from the left edge of the viewport. Note: this property is overriden by the 'center' property.
Required: true
Default: 100
panel.size object
The size of the window when opened the first time.
Required: false
Default: (not specified; see any element defaults within)
panel.size.width integer
The width of the window in pixels. -1 means use the default width for the panel. Note that depending on panel features exposed, there may be a limit to how small a panel can become.
Required: true
Default: -1
panel.size.height integer
The height of the window in pixels. -1 means use the default height for the panel. Note that depending on panel features exposed, there may be a limit to how small a panel can become.
Required: true
Default: -1
channel object
The communication channel definition used by this plugin. Note: this section rarely needs modifications. In many cases, the underlying plugin implementation depends on at least some of these settings having the values below. Consult with a JADE expert before making changes to this section if you are unfamiliar with the implications of changes to this section.
Required: true
Default: (not specified; see any element defaults within)
channel.SendBreakTimeout integer
The timeout duration in milliseconds to wait for sending messages.
Required: true
Default: 1000
channel.WaitOnBreakTimeout integer
The timeout duration in milliseconds to wait for receiving messages. Note: -1 means wait indefinitely or until shutdown is signalled.
Required: true
Default: -1
channel.WaitOnShutdownTimeout integer
The timeout duration in milliseconds to wait for shutdown acknowledgment.
Required: true
Default: 2000
channel.ThrowTimeoutErrors boolean
Whether to throw timeout errors vs simply returning a boolean indicating whether a timeout occurred.
Required: true
Default: false
channel.ThrowShutdownUnacknowledgedErrors boolean
Whether to throw 'shutdown unacknowledged' errors.
Required: true
Default: true
channel.QueueSize integer
The size of the underlying communication queue in bytes. Note: -1 means unbounded (i.e. grow as needed with available memory).
Required: true
Default: -1
channel.SendBreakEnqueueType enum (string)
The enqueue strategy employed on the underlying queue for standard messages.
Required: true
Default: "Enqueue"
Enum Items: "Enqueue" | "EnqueueAtFront" | "LossyEnqueue" | "LossyEnqueueAtFront"
channel.SendErrorEnqueueType enum (string)
The enqueue strategy employed on the underlying queue for error messages.
Required: true
Default: "Enqueue"
Enum Items: "Enqueue" | "EnqueueAtFront" | "LossyEnqueue" | "LossyEnqueueAtFront"
channel.SendShutdownEnqueueType enum (string)
The enqueue strategy employed on the underlying queue for the shutdown message.
Required: true
Default: "LossyEnqueueAtFront"
Enum Items: "Enqueue" | "EnqueueAtFront" | "LossyEnqueue" | "LossyEnqueueAtFront"
channel.FlushQueueBeforeWaitingOnBreak boolean
Whether to flush the queue upon waiting for new messages (i.e. whether to clear the queue and wait for the next 'new' message; this has the effect of removing old messages and waiting for the next message.
Required: true
Default: false
channel.FlushQueueAfterBreaking boolean
Whether to flush the queue after receiving a new message (i.e. whether to handle the next message coming in the queue and then flush; this has the effect of handling the oldest message (if it exsits) or the next message before flushing the queue.
Required: true
Default: false