Conditional Formula Fields and Global Actions in Foundry


The Basics

Using Formula fields in conjunction with Global Actions is a powerful way to perform a wide variety of actions.  Below is a chart showing the relationship between Device formulas and Global Actions.

IMPORTANT NOTE: Formula Fields are only executed when an object is updated. This could be through an MQTT message, DynamoDB Update, or other related events.



Key:

Device: Also known as assets in Foundry, devices are object representations of your real-world products.  All devices are instantiations of a ‘device type’ which can be thought of as a template or abstract class

Attribute: Attributes are device variables.  A device can only have attributes that are declared in its device type.  Attributes reflect real world data that is passed up from physical products


MQTT Topic: This takes the form of a backwards URL. You can think of it as the channel that device data enters your object through.  Data sent to the device on a MQTT topic takes the form of a JSON message and will update device attributes immediately


Formula Field: This is an expression that will execute when device data is updated.  In the above diagram we make use of a conditional action formula, it takes the form of a ternary expression which is a fancy if statement.  It links up to global actions.  Formula fields are the same across all devices of the same type.


Global Action: This is a way to call or link to things outside of foundry such as lambda functions


Lambda ARN: This is a unique identifier for a lambda function.  It can be found on the top right of the lambda editor page


Syntax: Notice that variables in the formula field are referenced by ${variable} and that payloads are JSON messages formatted {“key_one”: “Value 1”, “key_two”: “Value 2”}


Put It All Together

Let’s say that Device A is created with X = 3 and Y = 5.  The ternary evaluates to false and Action C is executed.  This will publish a MQTT message on the topic ‘com.yoursite/customer’ with the payload shown in the action. AWS IOT rules are perfect for listening for and handling these messages.


Now, let’s say a message with the MQTT topic ‘com.yoursite/devices/Device_A’ and the payload {“x”: “5”} is published.  This automatically updates the value of X in Device A. The Formula field is re-evaluated because there was a change in data.  This time, the condition evaluates to true, and Global Action B is executed.  The lambda function with the given ARN is executed and is passed the shown payload.  This will be passed in through the request or event field of the Lambda function.


Example: 

This example will cover a self-filling cookie jar.  The jar will have an infrared sensor in it to tell how many cookies are left in the jar.  There will be an attached wifi-chip that constantly ‘chirps’ or sends MQTT messages on the topic com.cookies/123.  When the server detects that there are less than 5 cookies in the jar, it will trigger a lambda function to create an Amazon order of 15 cookies to fill the jar back up.  This is all demonstrated in the diagram below.


This example will go over how to simulate the physical cookie jar using an MQTT message


The order of the following steps is not essential but highly recommended for first- timers as it makes linking parts together easier.  More skillful foundry architects will probably not follow this order.



Step 1:  Creating Your Lambda Function

Create an AWS lambda function to place an order. The function should expect parameters “num_cookies” and “type_cookies” in the event or request.  For more on lambda function creation click here. Once you have created your function, copy the ARN from the top left corner of the editor page.



Step 2: Creating Your Global Action 

Log into your foundry instance and navigate https://[instance].thinglogix.com/#!/devices, which is usually named the ‘Assets’ or 'Objects' tab on the left hand grey tool bar. If you do not have the Assets tab or cannot find it, go to the “Adding Pages to a Foundry Instance” tutorial at the end of this example.



Click create new object.



Select the appropriate account for this object for which you want this action associated with and select Object Template to be Global Action.


Now add attributes to your global action by selecting the desired attribute, typing a value and clicking the turquoise ‘Add Attribute’ button.


Add four attributes as shown in the diagram below.  Paste the Lambda ARN on your clipboard when adding the Lambda ARN attribute.


For more on Global Actions click here.




The syntax for the payload is in JSON and is {“lambda_key”: “[foundry_key]”}   It is important to note that Lambda keys are snake case by good convention but foundry keys are generated as snake case and must use this convention.

Click the ‘Create’ button.


Step 3   Creating Yor Object Template: Basics

In the side-bar, click ‘Device Types’ or 'Object Types'. You can also navigate to this page using https://[instance].thinglogix.com/#!/deviceTypeManager. From here click ‘New Object Type Template’.  If you cannot find ‘Device Types’, go to the “Adding Pages to a Foundry Instance” tutorial at the end of this example.



Make the name Cookie Jar, the account the same as the global action account.


Add an attribute named Num Cookies.  Notice that a JSON key called num_cookies is automatically created.  Change the Data Type to Integer and click the ‘Add Field’ button.  No default value or characteristics need to be added.


Add another attribute called 'Type Cookies' that is a string. As of now your current object type attributes should look like this.


Remember that a device type is like an abstract class, so specific instances of the type will be implemented with their own attribute values.  The only thing that stays common across all objects of the same type are the formula fields.


For More on Object Type click here.


Step 4   Object Template: Formula Field

Add a field with name Check Cookies.  Go down to the ‘Data Type’ pick list and select ‘Formula’.


Click the ‘Add/Edit’ button.


In the Formula Type picklist you will see many options. The ‘Conditional Action’ is most common and is what is used in this example.  The other types are mainly used for conversions between different units.

Some of the basic syntax Thinglogix uses for Formulas are:

  • All expressions are evaluated in Java, all Java expressions are valid
  • Strings are compared by    equals(“string”, “string”)
  • Variables are referenced by placing the key inside braces:   ${key}
  • Variables can be cast as strings by encapsulating the variable in quotations: “${key}”
  • For More Syntax Click Here


After you select ‘Formula Type’ to be ‘Conditional Action’, a pre-formatted If statement will appear.  This will automatically be translated into a ternary as can be seen under ‘Formula*’.


The ‘Action’ drop-down menu will include all global actions that have already been created which is why this example created the global action before the formula field.  The ‘Add Row’ button will add ‘else if’ lines to the statement.


In the Conditional Action editor, notice the check box next to ‘Execute Formula Only On Insert’.  This will only evaluate the formula when the object is created. Using this check box in conjunction with and ‘if true’ can be very useful when creating formulas that you always want to execute upon creation.


For this example write ${num_cookies}<5 in the ‘Conditional Expression’ field and in the ‘Action field’ select ‘Order’ or whatever you named the global action that was created in step 2.


Add a description to the formula.


Click the ‘Add’ button at the bottom left to add the attribute to the device type.


Click the ‘Add Field’ button to add the attribute to the device type.


Lastly click the ‘Create Object Type’


Step 5   Instantiating a device

Go back to the ‘Assets’ tab and click the ‘New Object’ button.

Select the same account that you have been using for this tutorial.

For the Object Type, select the type cookie jar.

Add the attribute ‘Name’ as “Kitchen Jar”.

Add the attribute ‘MQTT Topic’ as “com.cookies/123”.

Add the attribute ‘Type Cookies’ as “Chocolate Chip”.

Add the attribute ‘Num Cookies’ as 20.  This will represent a full jar.



Click the ‘Create’ Button.


Step 6   Testing using MQTT

To see how this object can update real-time, you can publish MQTT messages on the Object’s MQTT Topic.  This will simulate how a real device will send MQTT messages to a Foundry representation of itself on a specific channel.

Click on “Kitchen Jar” in the ‘Assets’ tab. From here you can see the current state of the object.

Open a new Foundry instance and navigate to the ‘MQTT Client’ tab on the far left then click the ‘Connect’ button.  If the MQTT Client tab is not visible in your Foundry instance, go to the “Adding Pages to a Foundry Instance” tutorial at the end of this example.

In the ‘Publish’ box, type the Topic and Message as shown below.



Before clicking the ‘Publish’ button, note that the device’s formula is set up to call the order lambda function as long as num_cookies is less than 5, so the order lambda function will get called many times a second until the value is changed to above 5.  In a real-world Scenario, there would be a variable to keep track of when the last order was placed to prevent thousands of cookies from being ordered.

Click the ‘Publish’ button.

Navigate back to the tab left open with the device info (Assets -> Kitchen Jar)

Click the refresh button.  The new value of num_cookies should show as 4 and the order lambda function should be getting called continuously.


Adding Pages to a Foundry Instance

If your gray sidebar is not fully visible, like below, click the button in the red circle below.

Click the name of your Foundry instance in the top left corner, as shown in the light blue circle to the left.

Click the ‘Page manager’ tab that just appeared.

The Page manager menu is where you can add pages to your instance of Foundry.  Check the drop-down menus displayed to see if the page you are looking for is in one of those.  If it is not, click the ‘New Page’ button. 

The ‘Menu Item’ box selects which folder the new page will get added to.

The ‘Page Name’ is what the page’s name will be displayed as on the sidebar.

Select the URL of the page that you are trying to add.

Then click ‘Create’ and your page will appear on the left bar.