Mobile client application

Table of Contents

1. Introduction

The Sponge mobile client application is a Flutter application that provides a generic GUI to call remote Sponge actions. It can be run on both Android and iOS. It could be used as the one app to rule them all for Sponge services that publish actions via the Sponge REST API. All business logic has to be placed in Sponge actions, so the only requirement to have the application working is to create your own Sponge service by writing a knowledge base that define actions that will be visible and ready to run in the application or to connect to an existing Sponge service.

The application is currently under development. It will be released as an open source.

The application is especially useful when data and functionality are more important than visual aspects of a GUI, e.g. for prototyping, rapid application development, low cost solutions, etc. The reason is that the application provides only a generic and opinionated GUI whose customization is limited.

mobile architecture
Figure 1. The mobile application architecture

One of many use cases of the application is to connect to IoT devices that have Sponge installed and execute available actions. Different types of such devices provide different sets of actions that are specific to a device features. For example one device could have a camera and provide an action to take a picture. Another device could have a temperature sensor and provide its readings or have a machine learning model and provide predictions.

The mobile application uses several Sponge concepts such as actions and action arguments metadata, data types metadata, action and data type features, annotated values, provided action arguments, categories and events. It supports a convention over configuration paradigm.

You could build a customized GUI using your own Flutter code that will call the same Sponge actions. In that case the generic Sponge mobile client would be used as a Flutter library in your Flutter project.

2. Functionalities

The following chapters show the key functionalities of the mobile application.

2.1. Connections

actions connection list
Figure 2. Selecting a connection to the Sponge instance in the action list screen

You may configure many connections to Sponge REST API services. The application allows you to connect to a single service at the same time.

Figure 3. List of connections to Sponge instances

You may add, edit and remove connections to Sponge instances as well as activate a connection. To remove a connection swipe the corresponding element.

connections edit
Figure 4. Editing a connection to a Sponge instance

A Sponge address is the URL of the Sponge instance.

2.2. Action list

Figure 5. The action list

The main screen shows the list of actions defined in the connected Sponge engine. Only actions that have argument and result metadata are available. This is because the application uses a generic access to the actions utilizing their data types, labels, descriptions, features and so on. The number in the action icon is the number of action arguments.

To call an action or set action attributes tap the triangular icon on the right side of the action label.

The floating button allows to refresh the action list from the server. The refresh button clears all entered action arguments and received results.

The application currently doesn’t supports all Sponge data types.
Figure 6. The navigation drawer

The navigation drawer allows switching between the available main views.

2.4. Action call

action call manage lcd
Figure 7. The action call that manages the Raspberry Pi LCD display

Actions may have read only, provided arguments only to show a data from the server (see the Current LCD text attribute). The REFRESH button retrieves the current values of read only, provided arguments from the server.

The definition of the action that manages the Raspberry Pi LCD display
class ManageLcd(Action):
    def onConfigure(self):
        self.withLabel("Manage the LCD text and color")
        self.withDescription("Provides management of the LCD properties (display text and color). A null value doesn't change an LCD property.")
                .withLabel("Current LCD text").withDescription("The currently displayed LCD text.").withProvided(ProvidedMeta().withValue().withReadOnly()),
                .withLabel("Text to display").withDescription("The text that will be displayed in the LCD.").withProvided(ProvidedMeta().withValue()),
                .withLabel("LCD color").withDescription("The LCD color.").withProvided(ProvidedMeta().withValue().withOverwrite()),
                .withLabel("Clear text").withDescription("The text the LCD will be cleared.")
        self.withFeature("icon", "monitor")
    def onCall(self, currentText, text, color, clearText = None):"SetLcd", [text, color, clearText])
    def onProvideArgs(self, context):
        grovePiDevice = sponge.getVariable("grovePiDevice")
        if "currentText" in context.provide:
            context.provided["currentText"] = ProvidedValue().withValue(grovePiDevice.getLcdText())
        if "text" in context.provide:
            context.provided["text"] = ProvidedValue().withValue(grovePiDevice.getLcdText())
        if "color" in context.provide:
            context.provided["color"] = ProvidedValue().withValue(grovePiDevice.getLcdColor())

class SetLcd(Action):
    def onCall(self, text, color, clearText = None):
        sponge.getVariable("grovePiDevice").setLcd("" if (clearText or text is None) else text, color)
action call manage sensors
Figure 8. The action call that manages the Grove Pi sensors and actuators

The action call screen allows editing the action arguments.

The definition of the action that manages the Grove Pi sensors and actuators
class ManageSensorActuatorValues(Action):
    def onConfigure(self):
        self.withLabel("Manage the sensor and actuator values").withDescription("Provides management of the sensor and actuator values.")
            NumberType("temperatureSensor").withNullable().withLabel(u"Temperature sensor (°C)").withProvided(ProvidedMeta().withValue().withReadOnly()),
            NumberType("humiditySensor").withNullable().withLabel(u"Humidity sensor (%)").withProvided(ProvidedMeta().withValue().withReadOnly()),
            NumberType("lightSensor").withNullable().withLabel(u"Light sensor").withProvided(ProvidedMeta().withValue().withReadOnly()),
            NumberType("rotarySensor").withNullable().withLabel(u"Rotary sensor").withProvided(ProvidedMeta().withValue().withReadOnly()),
            NumberType("soundSensor").withNullable().withLabel(u"Sound sensor").withProvided(ProvidedMeta().withValue().withReadOnly()),
            BooleanType("redLed").withLabel("Red LED").withProvided(ProvidedMeta().withValue().withOverwrite()),
            IntegerType("blueLed").withMinValue(0).withMaxValue(255).withLabel("Blue LED").withProvided(ProvidedMeta().withValue().withOverwrite()),
        self.withFeature("icon", "thermometer")
    def onCall(self, temperatureSensor, humiditySensor, lightSensor, rotarySensor, soundSensor, redLed, blueLed, buzzer):
        grovePiDevice = sponge.getVariable("grovePiDevice")
    def onProvideArgs(self, context):
        values ="GetSensorActuatorValues", [context.provide])
        for name, value in values.iteritems():
            context.provided[name] = ProvidedValue().withValue(value)

class GetSensorActuatorValues(Action):
    def onCall(self, names):
        values = {}
        grovePiDevice = sponge.getVariable("grovePiDevice")
        if "temperatureSensor" or "humiditySensor" in names:
            th = grovePiDevice.getTemperatureHumiditySensor()
            if "temperatureSensor" in names:
                values["temperatureSensor"] = th.temperature if th else None
            if "humiditySensor" in names:
                values["humiditySensor"] = th.humidity if th else None
        if "lightSensor" in names:
            values["lightSensor"] = grovePiDevice.getLightSensor()
        if "rotarySensor" in names:
            values["rotarySensor"] = grovePiDevice.getRotarySensor().factor
        if "soundSensor" in names:
            values["soundSensor"] = grovePiDevice.getSoundSensor()
        if "redLed" in names:
            values["redLed"] = grovePiDevice.getRedLed()
        if "blueLed" in names:
            values["blueLed"] = grovePiDevice.getBlueLed()
        if "buzzer" in names:
            values["buzzer"] = grovePiDevice.getBuzzer()
        return values
action call send sms
Figure 9. The action call that sends an SMS from the Raspberry Pi

Actions arguments may be edited in multiline text fields.

The definition of the action that sends an SMS from the Raspberry Pi
class SendSms(Action):
    def onConfigure(self):
        self.withLabel("Send an SMS").withDescription("Sends a new SMS.")
            StringType("recipient").withFormat("phone").withLabel("Recipient").withDescription("The SMS recipient."),
            StringType("message").withMaxLength(160).withFeatures({"maxLines":5}).withLabel("Message").withDescription("The SMS message.")
        self.withFeature("icon", "cellphone-text")
    def onCall(self, recipient, message):
        gsm.sendSms(recipient, message)
action call color
Figure 10. The action call argument editor for a color type

The color picker widget allows a user to choose a color as an argument value.

The definition of the action that takes a color argument
class ChooseColor(Action):
    def onConfigure(self):
        self.withLabel("Choose a color").withDescription("Shows a color argument.")
                .withLabel("Color").withDescription("The color.")
        ).withResult(StringType()).withFeatures({"icon":"format-color-fill", "showClear":True})
    def onCall(self, color):
        return ("The chosen color is " + color) if color else "No color chosen"
action call digit drawing
Figure 11. The action call argument editor for a digit drawing

The drawing panel allows a user to paint an image that will be set as an argument value in an action call.

The definition of the action that recognizes a handwritten digit
class DigitsPredict(Action):
    def onConfigure(self):
        self.withLabel("Recognize a digit").withDescription("Recognizes a handwritten digit")
        self.withArg(createImageType("image")).withResult(IntegerType().withLabel("Recognized digit"))
        self.withFeature("icon", "brain")
    def onCall(self, image):
        predictions = py4j.facade.predict(image)
        prediction = max(predictions, key=predictions.get)
        probability = predictions[prediction]

        # Handle the optional predictionThreshold Sponge variable.
        predictionThreshold = sponge.getVariable("predictionThreshold", None)
        if predictionThreshold and probability < float(predictionThreshold):
            self.logger.debug("The prediction {} probability {} is lower than the threshold {}.", prediction, probability, predictionThreshold)
            return None
            self.logger.debug("Prediction: {}, probability: {}", prediction, probability)
            return int(prediction)

def imageClassifierServiceInit(py4jPlugin):
    SpongeUtils.awaitUntil(lambda: py4jPlugin.facade.isReady())
action call digit
Figure 12. The action call for an attribute of type drawing

The action call screen shows all action arguments.

action call digit result
Figure 13. The action call result for a digit recognition

If the action has been called, the result is shown below the action label. If the result can’t be fully shown in the action list, you may tap the result to see the details.

action call doodle drawing
Figure 14. The action call argument editor for a doodle drawing

Drawing panels can be configured in a corresponding action definition, where a color, a background color etc. could be specified.

The definitions of actions that represent drawing and viewing a doodle
from java.lang import System
from os import listdir
from os.path import isfile, join, isdir

class DrawAndUploadDoodle(Action):
    def onConfigure(self):
        self.withLabel("Draw and upload a doodle").withDescription("Shows a canvas to draw a doodle and uploads it to the server")
                     .withFeatures({"characteristic":"drawing", "width":300, "height":250, "background":"FFFFFF", "color":"000000", "strokeWidth":2})
    def onCall(self, image):
        filename = str(System.currentTimeMillis()) + ".png"
        SpongeUtils.writeByteArrayToFile(image, sponge.getProperty("doodlesDir") + "/" + filename)
        return "Uploaded as " + filename

class ListDoodles(Action):
    def onConfigure(self):
        self.withLabel("List doodles").withDescription("Returns a list of doodle filenames").withFeatures({"visible":False})
    def onCall(self):
        dir = sponge.getProperty("doodlesDir")
        doodles = [f for f in listdir(dir) if isfile(join(dir, f)) and f.endswith(".png")] if isdir(dir) else []
        return sorted(doodles, reverse=True)

class ViewDoodle(Action):
    def onConfigure(self):
        self.withLabel("View a doodle").withDescription("Views a doodle")
        self.withArg(StringType("image").withLabel("Doodle name").withProvided(ProvidedMeta().withValue().withValueSet().withOverwrite()))
        self.withResult(BinaryType().withAnnotated().withMimeType("image/png").withLabel("Doodle image"))
        self.withFeature("icon", "drawing")
    def onCall(self, name):
        return AnnotatedValue(SpongeUtils.readFileToByteArray(sponge.getProperty("doodlesDir") + "/" + name)).withFeatures({"filename":"doodle_" + name})
    def onProvideArgs(self, context):
        if "image" in context.provide:
            doodles ="ListDoodles")
            context.provided["image"] = ProvidedValue().withValue(doodles[0] if doodles else None).withValueSet(doodles)

def onStartup():"ListDoodles")))
action call doodle
Figure 15. The action call for a doodle drawing as an argument

The action call screen shows all action arguments, for example a drawing.

action call arg depends
Figure 16. The action call that shows argument dependencies

Action arguments may depend on each other. Argument dependencies are supported in the action call panel and allow creating simple, interactive forms where some arguments are provided by the server, some entered by the user, some read only and some depend on the values of others. The important thing is that all that configuration is defined in an action in a knowledge base placed on the server side, not in the mobile application.

The definition of the action that provides arguments with dependencies
class DependingArgumentsAction(Action):
    def onConfigure(self):
        self.withLabel("Action with depending arguments")
        self.withFeatures({"icon":"flag", "showClear":True, "showCancel":True})
    def onCall(self, continent, country, city, river, weather):
        return "There is a city {} in {} in {}. The river {} flows in {}. It's {}.".format(city, country, continent, river, continent, weather.lower())
    def onProvideArgs(self, context):
        if "continent" in context.provide:
            context.provided["continent"] = ProvidedValue().withValueSet(["Africa", "Asia", "Europe"])
        if "country" in context.provide:
            continent = context.current["continent"]
            if continent == "Africa":
                countries = ["Nigeria", "Ethiopia", "Egypt"]
            elif continent == "Asia":
                countries = ["China", "India", "Indonesia"]
            elif continent == "Europe":
                countries = ["Russia", "Germany", "Turkey"]
                countries = []
            context.provided["country"] = ProvidedValue().withValueSet(countries)
        if "city" in context.provide:
            country = context.current["country"]
            if country == "Nigeria":
                cities = ["Lagos", "Kano", "Ibadan"]
            elif country == "Ethiopia":
                cities = ["Addis Ababa", "Gondar", "Mek'ele"]
            elif country == "Egypt":
                cities = ["Cairo", "Alexandria", "Giza"]
            elif country == "China":
                cities = ["Guangzhou", "Shanghai", "Chongqing"]
            elif country == "India":
                cities = ["Mumbai", "Delhi", "Bangalore"]
            elif country == "Indonesia":
                cities = ["Jakarta", "Surabaya", "Medan"]
            elif country == "Russia":
                cities = ["Moscow", "Saint Petersburg", "Novosibirsk"]
            elif country == "Germany":
                cities = ["Berlin", "Hamburg", "Munich"]
            elif country == "Turkey":
                cities = ["Istanbul", "Ankara", "Izmir"]
                cities = []
            context.provided["city"] = ProvidedValue().withValueSet(cities)
        if "river" in context.provide:
            continent = context.current["continent"]
            if continent == "Africa":
                rivers = ["Nile", "Chambeshi", "Niger"]
            elif continent == "Asia":
                rivers = ["Yangtze", "Yellow River", "Mekong"]
            elif continent == "Europe":
                rivers = ["Volga", "Danube", "Dnepr"]
                rivers = []
            context.provided["river"] = ProvidedValue().withValueSet(rivers)
        if "weather" in context.provide:
            context.provided["weather"] = ProvidedValue().withValueSet(["Sunny", "Cloudy", "Raining", "Snowing"])
action call arg depends value set
Figure 17. The action call that shows argument dependencies and value sets

Allowed argument values can be defined in an action and provided from the server every time the action call screen is shown or an argument dependency value changes.

2.5. Action result

actions binary result
Figure 18. The action binary result

Actions may return contents that can be viewed for example as a HTML or a PDF file using the mobile OS viewers.

The definitions of the actions that return a HTML and a PDF file respectively
class HtmlFileOutput(Action):
    def onConfigure(self):
        self.withLabel("HTML file output").withDescription("Returns the HTML file.")
        self.withNoArgs().withResult(BinaryType().withMimeType("text/html").withLabel("HTML file"))
    def onCall(self):
        return String("""
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
      <title>HTML page</title>
        <!-- Main content -->
        <p>Some text

class PdfFileOutput(Action):
    def onConfigure(self):
        self.withLabel("PDF file output").withDescription("Returns the PDF file.")
        self.withNoArgs().withResult(BinaryType().withMimeType("application/pdf").withLabel("PDF file"))
    def onCall(self):
        return sponge.process(ProcessConfiguration.builder("curl", "")
actions console result
Figure 19. The action console formatted result

Actions may return a console output, for example the result of running the df -h command on the server.

The definitions of the actions that returns OS commands output
from org.openksavi.sponge.util.process import ProcessConfiguration

class OsGetDiskSpaceInfo(Action):
    def onConfigure(self):
        self.withLabel("Get disk space info").withDescription("Returns the disk space info.")
        self.withNoArgs().withResult(StringType().withFormat("console").withLabel("Disk space info"))
        self.withFeature("icon", "console")
    def onCall(self):
        return sponge.process(ProcessConfiguration.builder("df", "-h").outputAsString()).run().outputString

class OsDmesg(Action):
    def onConfigure(self):
        self.withLabel("Run dmesg").withDescription("Returns the dmesg output.")
        self.withNoArgs().withResult(StringType().withFormat("console").withLabel("The dmesg output"))
        self.withFeature("icon", "console")
    def onCall(self):
        return sponge.process(ProcessConfiguration.builder("dmesg").outputAsString()).run().outputString
actions markdown result
Figure 20. The action Markdown formatted result

Actions may return a Markdown formatted text.

2.6. Events

The application can subscribe to Sponge events. The subscription uses a Sponge gRPC service published on a default port (i.e. the REST API port plus 1). A user must have priviliges to subscribe to events and to send events.

There are a few places where Sponge events are directly used in the application:

  • An event list screen (handles events subscribed globally for the application).

  • An action call screen for actions that have refresh events configured (handles events subscribed locally for an action).

2.6.1. Event subscription

Events can be subscribed globally for the application. Subscription management is performed by a subscription action, i.e. an action that has the intent feature set to subscription. Sponge provides a default subscription action GrpcApiManageSubscription.

In case of a new event an operating system notification will be displayed.

event subscription management
Figure 21. Event subscription management

2.6.2. Event list

The event list screen shows all events the application has subscribed for but only those that has been sent when the application is running.

By tapping on an event the user will be directed to a screen presenting an action associated with this event. This action is called an event handler action and is set up in the event type definition as a feature handlerAction. The action is required to have an ObjectType argument with object class RemoteEvent. An event instance will be passed to that argument. After the action is called, the event is automatically dismissed from the GUI.

If there is no event handler action defined for a specific event type, a default event handler action will be shown. The default action is searched by its intent feature which has to be defaultEventHandler. Sponge provides a default event handler action GrpcApiViewEvent.

event list
Figure 22. Event list
Event type with a default event handler action
from java.util.concurrent.atomic import AtomicLong
from org.openksavi.sponge.restapi.model import RemoteEvent

def onInit():
    sponge.setVariable("notificationNo", AtomicLong(1))

def onBeforeLoad():
    sponge.addType("Person", lambda: RecordType().withFields([
        StringType("firstName").withLabel("First name"),

    sponge.addEventType("notification", RecordType().withFields([
        sponge.getType("Person", "person").withNullable()

class NotificationSender(Trigger):
    def onConfigure(self):
    def onRun(self, event):
        eventNo = str(sponge.getVariable("notificationNo").getAndIncrement())
        sponge.event("notification").set({"source":"Sponge", "severity":10, "person":{"firstName":"James", "surname":"Joyce"}}).label(
            "The notification " + eventNo).description("The new event " + eventNo + " notification").send()

def onStartup():
event handler action notification
Figure 23. Default event handler action
Event type with a custom event handler action
from org.openksavi.sponge.restapi.model import RemoteEvent

def onBeforeLoad():
    sponge.addEventType("memo", RecordType().withFields([
    ]).withLabel("Memo").withFeature("handlerAction", "ViewMemoEvent"))

class ViewMemoEvent(Action):
    def onConfigure(self):
        self.withLabel("Memo").withDescription("Shows the memo event.")
            ObjectType("event", RemoteEvent).withFeature("visible", False),
            StringType("uppercaseMessage").withLabel("Upper case message").withProvided(
        self.withFeatures({"visible":False, "callLabel":"Dismiss", "cancelLabel":"Close"})
    def onCall(self, event, uppercaseMessage):
    def onProvideArgs(self, context):
        if "uppercaseMessage" in context.provide:
            message = context.current["event"].attributes["message"]
            context.provided["uppercaseMessage"] = ProvidedValue().withValue(message.upper() if message else "NO MESSAGE")
event handler action memo
Figure 24. Custom event handler action

2.6.3. Action with refresh events

Every action can have refresh events configured. When such an action is shown in the GUI, the application will subscribe to refresh events. When such event arrives, the action arguments will be automatically refreshed. Event arguments are ignored.

Action with refresh events
class ViewCounter(Action):
    def onConfigure(self):
        self.withLabel("Counter").withDescription("Shows the counter.")
        # This action when open in a GUI will subscribe to counterNotification events. When such event arrives, the action arguments
        # will be automatically refreshed, so the counter argument will be read from the variable and provided to a GUI.
        self.withFeatures({"cancelLabel":"Close", "refreshEvents":["counterNotification"]})
    def onProvideArgs(self, context):
        if "counter" in context.provide:
            context.provided["counter"] = ProvidedValue().withValue(sponge.getVariable("counter").get())
actions counter
Figure 25. Action with refresh events

2.6.4. Sending events

Events can be sent by the application using an action. Sponge provides a default, generic action for sending events GrpcApiSendEvent.

event send
Figure 26. Action that sends events

3. Advanced use cases

3.1. Context actions

Context actions can be specified for actions, record arguments and list elements (see the list-details) to provide related, customized sub-actions. Context actions should be specified as the contextActions feature statically for a type or an action or dynamically for an annotated value. The latter option takes precedence.

action context actions
Figure 27. The action with context actions
The definition of the action with context actions
class ActionWithContextActions(Action):
    def onConfigure(self):
        self.withLabel("Action with context actions").withArgs([
            StringType("arg1").withLabel("Argument 1"),
            StringType("arg2").withLabel("Argument 2")
        ]).withNoResult().withFeature("contextActions", [
            "ActionWithContextActionsContextAction1", "ActionWithContextActionsContextAction2(arg2)", "ActionWithContextActionsContextAction3(arg2=arg2)",
            "ActionWithContextActionsContextAction4(arg1)", "ActionWithContextActionsContextAction5", "ActionWithContextActionsContextAction6",
        self.withFeature("icon", "attachment")
    def onCall(self, arg1, arg2):

class ActionWithContextActionsContextAction1(Action):
    def onConfigure(self):
        self.withLabel("Context action 1").withArgs([
                StringType("arg1").withLabel("Argument 1"),
                StringType("arg2").withLabel("Argument 2")
            ]).withFeature("visible", False)
        self.withFeatures({"visible":False, "icon":"tortoise"})
    def onCall(self, arg):
        return arg["arg1"]

class ActionWithContextActionsContextAction2(Action):
    def onConfigure(self):
        self.withLabel("Context action 2").withArgs([
            StringType("additionalText").withLabel("Additional text"),
        self.withFeatures({"visible":False, "icon":"tortoise"})
    def onCall(self, arg, additionalText):
        return arg + " " + additionalText

class ActionWithContextActionsContextAction3(Action):
    def onConfigure(self):
        self.withLabel("Context action 3").withArgs([
            StringType("arg1").withLabel("Argument 1"),
            StringType("arg2").withLabel("Argument 2"),
            StringType("additionalText").withLabel("Additional text"),
        self.withFeatures({"visible":False, "icon":"tortoise"})
    def onCall(self, arg1, arg2, additionalText):
        return arg1 + " " + arg2 + " " + additionalText

class ActionWithContextActionsContextAction4(Action):
    def onConfigure(self):
        self.withLabel("Context action 4").withArgs([
            StringType("arg1NotVisible").withLabel("Argument 1 not visible").withFeatures({"visible":False}),
            StringType("arg2").withLabel("Argument 2"),
        self.withFeatures({"visible":False, "icon":"tortoise"})
    def onCall(self, arg1NotVisible, arg2):
        return arg1NotVisible + " " + arg2

class ActionWithContextActionsContextAction5(Action):
    def onConfigure(self):
        self.withLabel("Context action 5").withArgs([
                StringType("arg1").withLabel("Argument 1"),
                StringType("arg2").withLabel("Argument 2")
            StringType("additionalText").withLabel("Additional text")
        self.withFeatures({"visible":False, "icon":"tortoise"})
    def onCall(self, arg, additionalText):
        return arg["arg1"] + " " + additionalText

class ActionWithContextActionsContextAction6(Action):
    def onConfigure(self):
        self.withLabel("Context action 6").withArgs([
                StringType("arg1").withLabel("Argument 1"),
                StringType("arg2").withLabel("Argument 2")
        self.withFeatures({"visible":False, "icon":"tortoise"})
    def onCall(self, arg):

3.1.1. Arguments substitution

Modes of passing arguments to a context action:

  • Default (e.g. "ContextAction"). In case of a context action for an action, all action arguments as a record (represented as a map) will be passed as the first argument of the context action. In case of a record argument or a list element, the record or the list element value will be passed as the first argument respectively.

  • Explicit substitution (format "ContextAction(targetArgName=sourceArgName,…​)", e.g. "ContextAction(contextArg1=arg1,contextArg2=arg2)"). In case of a context action for an action, the argument contextArg1 of the context action will be set to a value of the argument arg1 of the parent action and the argument contextArg2 of the context action will be set to a value of the argument arg2.

  • Implicit substitution (format "ContextAction(sourceArgName,…​)", e.g. "ContextAction(arg1)"). In case of a context action for an action, the first argument of the context action will be set to a value of the argument arg1 of the parent action.

  • No arguments passed (e.g. "ContextAction()").

The target argument must have the same type as the source value.

A source argument name could be a path if a source value is a record, e.g. "ContextAction(contextArg1=arg1.field1)". The this keyword can be used as the source argument name. In case of a context action for an action it is a record of all parent action arguments. In case of a record argument or a list element it is the value itself.

If a context action has any visible arguments, a new action call screen will be shown. If a context value is an annotated value, the screen will show a header containing a label of the annotated value.

The context actions feature is not propagated to sub-actions in an annotated value feature.

Context actions can use globally saved (in a mobile application) action arguments but only if there is no argument substitutions (i.e. there are no arguments passed from the main action). It is necessary to avoid inconsistency.

3.1.2. Result substitution

A context action result can be assigned to a main action argument by using the notation "parentArgName=ContextAction()". As a parent argument name you can use the this keyword which means all action arguments or all record value or a list element.

For list elements only the this keyword as a result substitution is supported.

If a context action returns null and the result substitution is this, the result will be ignored.

3.1.3. Active or inactive context actions

Before showing a list of context actions the application checks (by connecting to the server) if the context actions are active. Inactive actions will be greyed out.

3.2. List-details

action form list actions list
Figure 28. The list-details action in the action list
action form list details main action
Figure 29. The list-details main action screen
action form list details subactions
Figure 30. The CRUD and context actions
action form list details subaction create
Figure 31. The create/add sub-action
action form list details subaction read
Figure 32. The read/view sub-action
action form list details subaction update
Figure 33. The update/modify sub-action
action form list details subaction delete
Figure 34. The delete/remove sub-action
action form list details subaction context binary
Figure 35. The context action returning a binary result
action form list details subaction context no result
Figure 36. The context action with no result
action form list details subaction context args
Figure 37. The context action with an additional argument
action form list details subaction context args result
Figure 38. The result of the context action with an additional argument
The definitions of actions implementing the list-details
from org.openksavi.sponge.util.process import ProcessConfiguration

def createBookRecordType(name):
    """ Creates a book record type.
    return RecordType(name).withFields([
        IntegerType("id").withLabel("ID").withNullable().withFeature("visible", False),

class RecordLibraryForm(Action):
    def onConfigure(self):
        self.withLabel("Library (books as records)")
            StringType("search").withNullable().withLabel("Search").withFeature("responsive", True),
            StringType("order").withLabel("Sort by").withProvided(ProvidedMeta().withValue().withValueSet()),
                    "createAction":"RecordCreateBook", "readAction":"RecordReadBook", "updateAction":"RecordUpdateBook", "deleteAction":"RecordDeleteBook",
                # Provided with overwrite to allow GUI refresh.
                }).withProvided(ProvidedMeta().withValue().withOverwrite().withDependencies(["search", "order"])).withElement(
        ]).withCallable(False).withFeature("icon", "library-books")
    def onProvideArgs(self, context):
        global LIBRARY
        if "order" in context.provide:
            context.provided["order"] = ProvidedValue().withValue("author").withAnnotatedValueSet([
                AnnotatedValue("author").withValueLabel("Author"), AnnotatedValue("title").withValueLabel("Title")])
        if "books" in context.provide:
            context.provided["books"] = ProvidedValue().withValue(
                # Context actions are provided dynamically in an annotated value.
                map(lambda book: AnnotatedValue(book.toMap()).withValueLabel("{} - {}".format(, book.title)).withFeature("contextActions", [
                        "RecordBookContextBinaryResult", "RecordBookContextNoResult", "RecordBookContextAdditionalArgs"]),
                    sorted(LIBRARY.findBooks(context.current["search"]), key = lambda book: if context.current["order"] == "author" else book.title.lower())))

class RecordCreateBook(Action):
    def onConfigure(self):
        self.withLabel("Add a new book")
                # Overwrite the author field.
        self.withFeatures({"visible":False, "callLabel":"Save", "cancelLabel":"Cancel", "icon":"plus-box"})

    def onCall(self, book):
        global LIBRARY
        LIBRARY.addBook(book["author"], book["title"])

    def onProvideArgs(self, context):
        global LIBRARY
        if "book" in context.provide:
            # Create an initial, blank instance of a book and provide it to GUI.
            context.provided["book"] = ProvidedValue().withValue({})
        if "" in context.provide:
            context.provided[""] = ProvidedValue().withValueSet(LIBRARY.getAuthors())

class RecordReadBook(Action):
    def onConfigure(self):
        self.withLabel("View the book")
        # Must set withOverwrite to replace with the current value.
        self.withCallable(False).withFeatures({"visible":False, "cancelLabel":"Close", "icon":"book-open"})
    def onProvideArgs(self, context):
        global LIBRARY
        if "book" in context.provide:
            context.provided["book"] = ProvidedValue().withValue(AnnotatedValue(LIBRARY.getBook(context.current[""]).toMap()))

class RecordUpdateBook(Action):
    def onConfigure(self):
        self.withLabel("Modify the book")
            # Must set withOverwrite to replace with the current value.
        self.withFeatures({"visible":False, "callLabel":"Save", "cancelLabel":"Cancel", "icon":"square-edit-outline"})
    def onCall(self, book):
        global LIBRARY
        LIBRARY.updateBook(book.value["id"], book.value["author"], book.value["title"])
    def onProvideArgs(self, context):
        global LIBRARY
        if "book" in context.provide:
            context.provided["book"] = ProvidedValue().withValue(AnnotatedValue(LIBRARY.getBook(context.current[""]).toMap()))
        if "" in context.provide:
            context.provided[""] = ProvidedValue().withValueSet(LIBRARY.getAuthors())

class RecordDeleteBook(Action):
    def onConfigure(self):
        self.withLabel("Remove the book")
        self.withArg(createBookRecordType("book").withAnnotated().withFeature("visible", False)).withNoResult()
        self.withFeatures({"visible":False, "callLabel":"Save", "cancelLabel":"Cancel", "icon":"delete", "confirmation":True})

    def onCall(self, book):
        global LIBRARY"Deleting book id: {}", book.value["id"])

class RecordBookContextBinaryResult(Action):
    def onConfigure(self):
        self.withLabel("Text sample as PDF")
            createBookRecordType("book").withAnnotated().withFeature("visible", False)
        self.withFeatures({"visible":False, "icon":"file-pdf"})
    def onCall(self, book):
        return AnnotatedValue(sponge.process(ProcessConfiguration.builder("curl", "")

class RecordBookContextNoResult(Action):
    def onConfigure(self):
        self.withLabel("Return the book")
            createBookRecordType("book").withAnnotated().withFeature("visible", False)
        ).withNoResult().withFeatures({"visible":False, "icon":"arrow-left-bold"})
    def onCall(self, book):

class RecordBookContextAdditionalArgs(Action):
    def onConfigure(self):
        self.withLabel("Add book comment")
            createBookRecordType("book").withAnnotated().withFeature("visible", False),
            StringType("comment").withLabel("Comment").withFeatures({"multiline":True, "maxLines":2})
        ]).withResult(StringType().withLabel("Added comment"))
        self.withFeatures({"visible":False, "icon":"comment-outline"})
    def onCall(self, book, message):
        return message

The main action should have a list argument that is provided with the overwrite option. The action shouldn’t be callable. The list argument type can be annotated and the provided list elements may have labels (AnnotatedValue().withLabel()) and descriptions. The list argument may have the following features: createAction, readAction, updateAction, deleteAction. Their values are the sub-action names that will be called to perform the CRUD operations.

There are two types of sub-actions: CRUD actions and context actions. CRUD actions implement create, read, update and delete operations. Context actions implement customized operations related to a list element.

The CRUD actions should not be visible in the actions list so they should have the visible feature set to False.

In the default scenario read, update and delete actions should have the first argument corresponding to the value of the list element. In most cases the argument visible feature should be set to False to hide it. Its type should be the same as the list element’s type. The value of the list element will be passed as this argument. In the case of a create action, no argument corresponding to any list element is necessary.

The result of a create, an update and a delete action is ignored and should be set to withNoResult.

After calling a CRUD action the main action arguments are refreshed.

3.3. Interactive form

An interactive form provides live update in a GUI and an instant modifications of a server state. It can be implemented by an action with provided and submittable arguments and action refresh events. Interactive forms can be used for example to manage IoT devices.

The following example shows a very simple MPD player implemented as a Sponge action. A change in an MPD server state generates a Sponge event. Such event is subscribed by the action in the mobile application and causes the action to refresh its arguments. On the other hand, a change made by a user in the GUI will cause such argument to be submitted to the server.

Interactive form example
import os

class MpdPlayer(Action):
    def onConfigure(self):
        self.withLabel("Player").withDescription("The MPD player.")
            StringType("song").withLabel("Song").withNullable().withFeatures({"multiline":True, "maxLines":2}).withProvided(
                {"widget":"slider", "group":"position"}).withProvided(
            VoidType("prev").withLabel("Previous").withAnnotated().withFeatures({"icon":"skip-previous", "group":"navigation"}).withProvided(
            VoidType("next").withLabel("Next").withAnnotated().withFeatures({"icon":"skip-next", "group":"navigation"}).withProvided(
        self.withFeatures({"cancelLabel":"Close", "refreshEvents":["statusPolling", "mpdNotification_.*"], "icon":"music", "contextActions":[
            "MpdPlaylist()", "MpdSetAndPlayPlaylist()", "ViewSongInfo()", "ViewSongLyrics()", "MpdLibrary()", "ViewMpdStatus()",

    def __ensureStatus(self, mpc, status):
        return status if mpc.isStatusOk(status) else mpc.getStatus()

    def onProvideArgs(self, context):
        mpc = sponge.getVariable("mpc")
        status = None
        (position, size) = (None, None)

                if "position" in context.submit:
                    if context.current["position"]:
                        status = mpc.seekByPercentage(context.current["position"].value)
                if "volume" in context.submit:
                        status = mpc.setVolume(context.current["volume"].value)
                if "play" in context.submit:
                    status = mpc.togglePlay(context.current["play"].value)
                if "prev" in context.submit:
                    status = mpc.prev()
                if "next" in context.submit:
                    status =
                sponge.logger.warn("Submit error: {}", sys.exc_info()[0])

            currentSong = None
            if "song" in context.provide or "date" in context.provide:
                currentSong = mpc.getCurrentSong()
            if "song" in context.provide:
                context.provided["song"] = ProvidedValue().withValue(mpc.getSongLabel(currentSong) if currentSong else None)
            if "date" in context.provide:
                context.provided["date"] = ProvidedValue().withValue(currentSong["date"] if currentSong else None)
            if "position" in context.provide or "context" in context.submit:
                status = self.__ensureStatus(mpc, status)
                context.provided["position"] = ProvidedValue().withValue(AnnotatedValue(mpc.getPositionByPercentage(status)).withFeature(
                    "enabled", mpc.isStatusPlayingOrPaused(status)))
            if "time" in context.provide:
                status = self.__ensureStatus(mpc, status)
                context.provided["time"] = ProvidedValue().withValue(mpc.getTimeStatus(status))
            # Provide an annotated volume value at once if submitted.
            if "volume" in context.provide or "volume" in context.submit:
                status = self.__ensureStatus(mpc, status)
                volume = mpc.getVolume(status)
                context.provided["volume"] = ProvidedValue().withValue(AnnotatedValue(volume).withTypeLabel(
                    "Volume" + ((" (" + str(volume) + "%)") if volume else "")))
            if "play" in context.provide:
                status = self.__ensureStatus(mpc, status)
                playing = mpc.getPlay(status)
                context.provided["play"] = ProvidedValue().withValue(AnnotatedValue(playing).withFeature("icon", "pause" if playing else "play"))

            if "prev" in context.provide or "next" in context.provide:
                status = self.__ensureStatus(mpc, status)
                (position, size) = mpc.getCurrentPlaylistPositionAndSize(status)
            if "prev" in context.provide:
                context.provided["prev"] = ProvidedValue().withValue(AnnotatedValue(None).withFeature("enabled", position is not None))
            if "next" in context.provide:
                context.provided["next"] = ProvidedValue().withValue(AnnotatedValue(None).withFeature("enabled",
                        position is not None and size is not None))
actions mpd player main
Figure 39. The MPD player action
actions mpd player context actions
Figure 40. The context actions

3.4. Choose dialog

A choose dialog can be used to pick a value and pass it as a result to a parent action argument.

Choose dialog example
def createFruitWithColorRecordType(name = None):
    return RecordType(name).withLabel("Fruit").withAnnotated().withFields([

class FruitsWithColorsContextSetter(Action):
    def onConfigure(self):
        self.withLabel("Fruits with colors - context setter").withArgs([
                AnnotatedValue({"name":"Orange", "color":"orange"}),
                AnnotatedValue({"name":"Lemon", "color":"yellow"}),
                AnnotatedValue({"name":"Apple", "color":"red"})]).withFeatures({
                    "updateAction":"this=FruitsWithColorsContextSetter_Update(this)", "contextActions":["this=FruitsWithColorsContextSetter_Choose"]})

class FruitsWithColorsContextSetter_Update(Action):
    def onConfigure(self):
        self.withLabel("Update a fruit").withArgs([
    def onCall(self, fruit):
        return fruit

class FruitsWithColorsContextSetter_Choose(Action):
    def onConfigure(self):
        self.withLabel("Choose a fruit").withArgs([
            createFruitWithColorRecordType("chosenFruit").withNullable().withFeature("visible", False).withProvided(

    def onCall(self, chosenFruit, fruits):
        if chosenFruit:
            chosenFruit.valueLabel = None
        return chosenFruit

    def onProvideArgs(self, context):
        chosenFruit = None
        if "fruits.fruit" in context.submit:
            chosenFruit = context.current["fruits.fruit"]

        if "chosenFruit" in context.provide or "fruits.fruit" in context.submit:
            context.provided["chosenFruit"] = ProvidedValue().withValue(chosenFruit)

        if "fruits" in context.provide or "fruits.fruit" in context.submit:
            if chosenFruit is None:
                chosenFruit = context.current["chosenFruit"]
            chosenFruitName = chosenFruit.value["name"] if chosenFruit else None

            context.provided["fruits"] = ProvidedValue().withValue([
                AnnotatedValue({"name":"Kiwi", "color":"green"}).withValueLabel("Kiwi").withFeature("icon", "star" if chosenFruitName == "Kiwi" else None),
                AnnotatedValue({"name":"Banana", "color":"yellow"}).withValueLabel("Banana").withFeature("icon", "star" if chosenFruitName == "Banana" else None)
actions call choose dialog parent
Figure 41. The choose dialog parent action
actions call choose dialog
Figure 42. The choose dialog action

4. User experience

dark theme
Figure 43. The application dart theme

The application may be switched to the dark theme in the settings.

5. Supported Sponge concepts

5.1. Data types

Table 1. Data types
Type Description


Not supported.


Editing (as an action attribute) is supported only for image/png mime type with drawing characteristic feature. Viewing is supported for image formats supported by Flutter and other binary content supported by the open_file Flutter plugin that is used by the application.




Viewing supported. Editing is currently limited to the DATE_TIME date kind.


A limited support. This functionality is experimental.




Editing is supported with limitations (see the Advanced use cases chapter). A unique list with a provided element value set is represented as a multichoice widget. Viewing is not supported. This functionality is experimental.


Not supported.




Supported only if an object type defines a companion type that is supported.


Editing supported. Viewing support is limited to fields that have simple data types. This functionality is experimental.


Not supported.




Not supported.


Supported. A chip widget is presented as an editor. A user can tap the chip widget to submit an argument if it is configured as submittable.

5.2. Data type formats

Table 2. Supported data type formats
Format Description


A phone number format. Applicable for StringType.


An email format. Applicable for StringType.


A URL format. Applicable for StringType.


A console format. Text is presented using a monospaced font. Applicable for StringType.


A Markdown format. Applicable for StringType.

5.3. Features

Table 3. Supported features
Feature Applies to Description



If True, an action will be visible in the main list of actions in the application. Defaults to true.



If True, an action argument or a record field is visible in the action call screen. Defaults to true.



If True, an action argument or a record field is enabled for editing. Defaults to true.



If True, a provided list will have a button to refresh (i.e. provide arguments from the server). Defaults to false.



An action icon name. The supported set of icons is limited to the material design icons (currently v4.5.95).



An type icon name. Currently supported only for list elements.



A GUI widget type. See the table below for supported values. Support for this feature is limited. In most cases a default, opinionated widget will be used.



A name of a group of action arguments or record fields. Grouped values will be placed in a compact GUI panel close to each other, if it is possible.



A responsive GUI widget. If this feature is set for a provided type, every change in GUI will cause invoking a provideActionArgs operation. This feature may be resource consuming (especially when used with an argument submit option) because of possible many server roundtrips.



If True then before calling the action a confirmation dialog will be shown. Defaults to false.



A value of this feature indicates a special meaning of the type.

characteristic: drawing


A BinaryType that represents a drawing. Currently supported only for mime type image/png.

characteristic: color


A StringType that represents a color as a hexadecimal RGB string.



A filename associated with a binary value.



An action with an intent is handled by the application in a specific way.

intent: login


Should be set in an action that represents a user login in the user management functionality. See the user management example project.

intent: logout


Should be set in an action that represents a user logout in the user management functionality.

intent: signUp


Should be set in an action that implements a user sign up in the user management functionality.

intent: subscription


Should be set in an action that manages event subscriptions.

intent: defaultEventHandler


A default event handler action.

intent: reload


Should be set in an action that reloads knowledge bases. Refreshes actions cached in a mobile application.



A type with an intent is handled by the application in a specific way.

intent: username

Action argument type

Indicates that the action argument represents a username. Applies only to actions that implement the user management functionality. This intent may be omitted if an action argument name is username.

intent: password

Action argument type

Indicates that the action argument represents a password. Applies only to actions that implement the user management functionality. This intent may be omitted if an action argument name is password.

intent: eventNames

Action argument type

Indicates that the action argument represents event names to subscribe. Applies only to event subscription actions.

intent: subscribe

Action argument type

Indicates that the action argument represents a flag telling if to turn on or off an event subscribtion. Applies only to event subscription actions.



Refresh event names for an action.


Event type

An event handler action name.



If True, a string will be multilined in the GUI. Defaults to false.



A maximum number of lines in the GUI.



If True, a string will be obscured in the GUI, e.g. in case of passwords. Defaults to false.



An action call button will be shown in the action call screen. Defaults to true.



An action arguments refresh button will be shown in the action call screen. Defaults to false. The refresh button fetches provided action arguments from the server. Only arguments provided with read only or overwrite flags will be refreshed.



An action arguments clear button will be shown in the action call screen. Defaults to false. The clear button resets the action argument values.



A cancel button will be shown in the action call screen. Defaults to false.



An action call button label in the action call screen. Defaults to RUN if the feature is not set. If set to None, the button will not be shown.



An action refresh button label in the action call screen. Defaults to REFRESH if the feature is not set. If set to None, the button will not be shown.



An action clear button label in the action call screen. Defaults to CLEAR if the feature is not set. If set to None, the button will not be shown.



An action cancel button label in the action call screen. Defaults to CANCEL if the feature is not set. If set to None, the button will not be shown.


Action, RecordType, ListType action argument

Context actions. For more information on context actions and sub-actions see the Advanced use cases chapter.


ListType action argument

A create sub-action for a list element.


ListType action argument

A read sub-action for a list element.


ListType action argument

A update sub-action for a list element.


ListType action argument

A delete sub-action for a list element.


ListType action argument

An action that will be called on list element tap. If the action string has the special value submit, then instead of calling an action, a provideActionArgs will be invoked with the submitted list element.


BinaryType drawing

An image width.


BinaryType drawing

An image height.


BinaryType drawing

A drawing stroke width.


BinaryType drawing

A drawing pen color.


BinaryType drawing

A drawing background color.



A flag indicating that a list will have its own scroll. This feature turns off the main scroll in an action screen. It is useful for long lists. This feature is only supported for main action arguments (i.e. not nested).

5.3.1. Widgets

Table 4. Supported widget types for a widget feature
Widget Description


Supported for an IntegerType but only if it has min and max values defined. The default behaviour of a slider is lazy, i.e. a value is set on an end of drag. If an integer type has a responsive feature set to true, the value will be set while dragging.


Supported for a BooleanType. The default widget for BooleanType is a checkbox.

A data type property can be dynamically overwritten by a corresponding feature in an AnnotatedValue. The feature name has to be exactly the same as the data type property name. The overwrite is handled by the Sponge mobile client application.

5.3.2. List pagination

Table 5. List pagination features
Feature Applies to Description



If True, a list will be pageable. Defaults to false. A pageable list type has to be annotated, because values of offset, limit and count are passed by features in an annotated list value.


ListType annotated value

An offset of the first element of a page.


ListType annotated value

A limit of a page, i.e. a maximum number of elements in a page.


ListType annotated value

A count of all available elements of a list. This value is optional.

A pagination uses the provideActionArgs REST API operation. The features offset and limit have to be set when invoking provideActionArgs. A provided, annotated list must have the offset and the limit set and optionally the count. A client code is responsible for setting offset and limit. An action onProvideArgs callback method is not required to support offset or limit if they are not set in the request. A page size is established by a client code.

The pagination is supported only for primary (i.e. not nested) action arguments and only for read provided annotated lists.

A pageable list should also have the feature scroll set to true. The pagination works only forward, i.e. all previous list elements fetched from the server are stored in mobile device memory.

6. Included demos

The access to actions in the mobile application is generic. However the application may include demos that use a customized UI.

6.1. Handwritten digit recognition

drawer digits
Figure 44. The navigation drawer if connected to a Sponge instance that supports a digit recognition

If the current connection points to a Sponge instance that has the required action that performs a handwritten digit recognition, this demo is enabled in the navigation drawer.

digits info
Figure 45. The digit recognition demo - the information dialog
digits drawing
Figure 46. The digit recognition demo - drawing a digit

The digit recognition demo screen allows drawing a digit that will be recognized by the Sponge action. After each stroke the remote action call is made and the result is shown in the circle.