Skip to content

Adding new resources

mstn edited this page Sep 14, 2010 · 10 revisions

NXTServer can be extended adding new resources. We tried to DRY the code as soon as possible. Thus, if you want to add a new resource, you have to define a resource extending GenericResource and add the newly created resource to the ResourceManager.

New resources are created extending the abstract class GenericResource. The class GenericResource offers a generic implementation of interface Resource. You could define your own implementation of Resource, but (in theory) GenericResource should be suitable for the most common scenarios. See Javadoc for details.

A class extending GenericResource must define the properties of the resource. For example, a resource of type motor has a boolean property forward. Then we add to propertyMap (from GenericResource) a new property with name "forward" and behavior defined by an implementation of PropertyDescriptor interface. An implementation of PropertyDescriptor defines the meta-information about resource properties. Moreover it defines the set and get methods of a resource. In the example below, when the value of the property named "forward" is set to a value, the motor is started or stopped depending if the setting value is true or false. Instead, when the property named "forward" is read, true is returned if the motor is running forward, false otherwise. Note that variable motor is a reference to a LeJOS class Motor.

propertyMap.put("forward", new PropertyDescriptor() {
	@Override
	public void setPropertyValue(Object value) {
		if ((Boolean) value) {
			motor.forward();
		} else {
		        motor.stop();
		}
	}
       @Override
       public Object getPropertyValue() {
	      return new Boolean(motor.isForward());
	}
}); 

Finally, we need to tell ResourceManager that a new resource has been created. I am going to improve how ResourceManager is implemented. For now, ResourceManager contains a map between resource names and resource objects initialized statically.

// create a resource of type motor
Resource motorA = new MotorResource("A", Motor.A);
// create a resource for NXT
ListResource root = new ListResource("/");
// add resource motorA to NXT
root.add(motorA);
// register the name of every resource
resourceInfoMap.put(root.getResourceFullName(), root );
resourceInfoMap.put(motorA.getResourceFullName(), motorA );

That’s all.

Clone this wiki locally