cap:state - state tracking¶
The state-capability provides a way to get and update the state of a thing.
State is split into several state keys that are updated separately.
if(thing.matches('cap:state')) {
console.log('Current state:', this.state);
}
API¶
-
state()¶ Get the current overall state.
Returns: Promise that resolves to an object representing the current state. Keys represent names of the state key. Usage:
const state = await thing.state(); console.log('State is', state); console.log('Value of power is', state.power);
Events¶
-
stateChanged¶ State has changed for the thing.
thing.on('stateChanged', change => console.log('Key', change.key, 'changed to', change.value) );
Protected methods¶
-
getState(key[, defaultValue])¶ Get the current value of the given state key.
Arguments: - power (string) – The state key to get value for.
- defaultValue – Fallback to return if the state key is not set.
Returns: The value for the state key, the default value or
null.
-
updateState(key, value)¶ Update the state of the given key. This will update the state key and emit the event
stateChanged.Arguments: - key (string) – The state key to update.
- value – The new value of the state key.
Returns: Boolean indicating if the state value has changed.
-
removeState(key)¶ Remove state stored for the given key. Will emit a
stateChangedevent.Arguments: - key (string) – The state key to remove.
Implementing capability¶
The state-capability has no functions that need to be implemented.
updateState can be called at any time to update a state key.
const { Thing, State } = require('abstract-things');
class Example extends Thing.with(State) {
constructor() {
super();
this.updateState('key', true);
}
}