Skip to content
Nathaniel Sherry edited this page Aug 13, 2015 · 3 revisions

Value Device with Accessors

This example shows how to create a simple value device, and how to set it

    public static void main(String[] args) throws InterruptedException {

        // Create an event bus to tie our nodes together
        DeviceEventBus bus = new IDeviceEventBus();

        // Create a simple value device which stores a single value with a
        // getter and setter. Set the value to "Hello"
        ValueDevice device = new IValueDevice("id", bus);
        device.setValue("Hello");

        // Create an accessor for this device
        DeviceAccessor<String> accessor = new IDeviceAccessor<>("id-accessor", "id", bus);
        Thread.sleep(50);
        // The accessor will query the device automatically on startup
        System.out.println(accessor.getState()); // "Hello"
        // Send a SET message with the payload "World"
        accessor.sendValueSet("World");

        // Messages are delivered asynchronously
        Thread.sleep(50);

        System.out.println(device.getValue()); // "World"
        System.out.println(accessor.getState()); // "World"
    }

Command Device

// Create a new device which responds to commands to add and subtract a
// value
public class MyDevice extends IValueDevice<Integer>implements CommandDevice {

    private CommandDispatcher dispatcher;

    public MyDevice(String id, DeviceEventBus bus) {
        super(id, bus);
        setValue(0);
        dispatcher = new CommandDispatcher(this, bus);
    }

    @Override
    public CommandDispatcher getCommandDispatcher() {
        return dispatcher;
    }

    @CommandMethod("add")
    public void add(@Arg int value) {
        setValue(getValue() + value);
    }

    @CommandMethod("subtract")
    public void subtract(@Arg int value) {
        setValue(getValue() - value);
    }

    @CommandMethod("add-mult")
    public void addThenMultiply(@Arg("toAdd") int add, @Arg("toMult") int mult) {
        int newValue = (getValue() + add) * mult;
        setValue(newValue);
    }

    public static void main(String[] args) throws InterruptedException {

        // Create an event bus to tie our nodes together
        DeviceEventBus bus = new IDeviceEventBus();

        MyDevice device = new MyDevice("int", bus);
        CommandsAccessor<Integer> accessor = new ICommandsAccessor<>("int-accessor", "int", bus);

        Thread.sleep(200);
        System.out.println(accessor.getState()); // 0

        accessor.sendCommand("add", 5);
        Thread.sleep(200);
        System.out.println(accessor.getState()); // 5

        accessor.sendCommand("subtract", 3);
        Thread.sleep(200);
        System.out.println(accessor.getState()); // 2

        accessor.sendCommand(new Command("add-mult").property("toAdd", 1).property("toMult", 2));
        Thread.sleep(200);
        System.out.println(accessor.getState()); // 6

    }

}
Clone this wiki locally