Persisting device state - GideonLeGrange/panstamp-java GitHub Wiki

Application developers may want to save device state (register values) for a panStamp to allow the state a device was in to be kept between application restarts. This is especially true for devices that go to sleep, for example battery powered devices; the library becomes aware of a device when it receives a message from it, but unless the message happens to be the "Product code" register, it will not know what kind of device it is.

The DeviceStateStore interface is provided to give an application developer the option to supply the panStamp library with a way of loading and storing register values. The library uses this interface internally to configure a the PanStamp object for a newly detected device using previously stored values.

The DeviceStateStore has three methods to implement:

  • hasRegisterValue() - This allows the panStamp library to test if a value for the specific register is available.
  • getRegisterValue() - This is used by the panStamp library to retrieve the perviously stored value.
  • setRegisterValue() - The panStamp library will call this when it wants to save the current register value.

How these methods are implemented depends on what the application requires. It is possible to implement different kinds of persistent storage, for example SQL, Java Properties or file storage.

It is also possible to use this interface to provide the library with values from a configuration file. Here is a partial example where the application knows (presumably from it's configuration file) the product code for the panStamps on the network:

java public class ConfigDeviceStateStore implements DeviceStateStore {

// assume productCodes is filled in from the config file by the application
private Map<Integer, byte[]> productCodes;

@Override
public boolean hasRegisterValue(Register reg) {
    return (reg.getId() == 0) && (productCodes.get(reg.getDevice().getAddress()) != null);
}

@Override
public byte[] getRegisterValue(Register reg) {
    return productCodes.get(reg.getId());
}

@Override
public void setRegisterValue(Register reg, byte[] value) {
    // don't have to do anything since it is a config file, but a good idea would be to log 
    // if the product code set by the library does not match the one we have in the config file
}

}


To then tell the network to use this device state store, simply call ```setDeviceStateStore()```:

```java
	// Assume we have a network nw
	ConfigDeviceStateStore store = ... // code to construct or get the store
	nw.setDeviceStore(store);