Creating a Command Handler
About this task
To subscribe to commands, an application must register a command handler service implementing the ICommandHandler
interface. This service will be registered to the dispatcher and called when new commands are dispatched.
Procedure
The following example shows how to implement a command handler:
import com.ge.dspmicro.cloud.gateway.api.ICloudGateway;
import com.ge.dspmicro.device.api.frameworkcomm.ICommandHandler;
import com.ge.predixmachine.datamodel.commandcomm.CommandStatus;
import com.ge.predixmachine.datamodel.commandcomm.EdgeCommand;
import com.ge.predixmachine.datamodel.gateway.TaskStatus;
...
@Component
public class SampleCommandHandler implements ICommandHandler
{
public static final String HANDLER_TYPE = "SampleApplicationName";
private ICloudGateway cloudGateway;
...
@Override
public void processCommand(EdgeCommand command)
{
// Get command information from EdgeCommand protobuf object
String commandId = command.getId();
String cmd = command.getCommand();
String url = command.getUrl(); // URL to upload command output
Map<String, String> params = command.getParamsMap();
// Handle Command adding execution logs to a string buffer.
StringBuffer executionLogs = new StringBuffer();
executionLogs.append("Command execution logs");
// Build a CommandStatus Object with command execution results.
CommandStatus.Builder cmdStatusBuilder = CommandStatus.newBuilder();
cmdStatusBuilder.setTaskId(commandId);
cmdStatusBuilder.setStatus(TaskStatus.SUCCESS);
cmdStatusBuilder.setStatusMessage("Successfully finished command execution.");
cmdStatusBuilder.setStatusDetailedMessage(executionLogs.toString());
cmdStatusBuilder.setOutput("Optional String Output. Up to 1KB."); // Note: If output is returned through this status object, the output uploaded with the provided URL will be ignored.
// Submit the CommandStatus to the Cloud Gateway to upload to the cloud
this.cloudGateway.submitStatus(cmdStatusBuilder.build());
}
@Override
public String getKey()
{
return HANDLER_TYPE;
}
/**
* @param cloudGateway The Cloud Gateway
*/
@Reference
public void setCloudGateway(ICloudGateway cloudGateway)
{
this.cloudGateway = cloudGateway;
}
/**
* @param cloudGateway The Cloud Gateway
*/
public void unsetCloudGateway(ICloudGateway cloudGateway)
{
this.cloudGateway = null;
}
}