Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: first section on simple persistence

...

Picos Represent State

Picos (Persistent Compute Objects) contain state that can be changed in response to events. Picos persist their state using entity variables.

We will learn more about entity variables by adding persistence to our hello_world ruleset from node pico-engine quickstart.

Add Persistence to hello_world

Let's change the hello_world ruleset to know your name by default.

To do this we will need:

  1. An entity variable to store your name in. 
  2. A new rule that stores your name in that entity variable.

Before starting, visit the "Rulesets" tab for your Pico, and notice that your Pico has no entity variables for the "hello_world" ruleset.

Image Added

Create a rule and name it store_name. Have it select on event domain hello and event type name.

We'll have the rule expect an event attribute named "name". We will declare a variable for the name (also named "name") and log it in the prelude. 

The rule store_name will send a directive named store_name with option name assigned giving the passed parameter name we are going to set.  The directive will allow us to know that the rule is working without having to look at the logs.


Entity variables can only be set in the postlude. We use the always form of the postlude so that this postlude is always evaluated. Just mentioning the name of the entity variable (yet another "name") will cause it to be created when the rule fires.


Code Block
  rule store_name {
    select when hello name
    pre{
      passed_name = event:attr("name").klog("our passed in Name: ")
    }
    send_directive("store_name") with
      name = passed_name
    always{
      ent:name := passed_name
    }
  }

Also include this entry in the "events" section of your "__testing" shared name:

Code Block
{ "domain": "hello", "type": "name", "attrs": [ "name" ] }

With an entry for the hello/name event in place, when you refresh your Pico's "Testing" tab, there will be a UI for sending the event which will trigger the new rule. Use this UI to sent the event. Notice the directive returned by the rule, named "store_name".

Image Added

Refresh the "Rulesets" tab for your Pico, and you'll see the entity variable named "ent:name", which was created the first time it was used.

Image Added

Now change hello_world rule to default to our persistent name.


Code Block
  rule hello_world {
    select when echo hello
    pre{
      name = event:attr("name").defaultsTo(ent:name,"use stored name")
    }
    send_directive("say") with
      something = "Hello " + name
  }

Test your persistence by raising an event to store_name without providing a value. This will cause the "defaultsTo" operator to provide the persisted name, which will be mentioned in the directive.

Image Added

You have now created and used a simple entity variable to give your Pico persistent state.