上下文
RobotContext提供了关于 Cruzr 系统全局信息的接口,RobotContext的执行是由Cruzr系统提供的。RobotContext 允许获取 Cruzr 系统的服务资源同时支持应用级别的操作如发布订阅、发送指令。它描述了一个应用程序环境信息, Cruzr 系统提供了该接口的具体实现类。
Cruzr 有三种类型的上下文:
RobotSkill描述技能的上下文,RobotSkill.this返回当前技能的上下文, 它的作用域跟随技能的生命周期RobotService描述服务的上下文,RobotService.this返回当前服务的上下文, 它的作用域跟随服务的生命周期GlobalContext全局上下文,Robot.globalContext()返回全局上下文,它的作用域跟随进程的生命周期
获取系统服务
/** * Get the robot system service by service name. * like SpeechManager, SkillManager, MotionManager and so on. * * @param serviceName the name of manager * @return the Manager which match the service name */ <T> T getSystemService(String serviceName);
SpeechManager manager = robotContext.getSystemService(SpeechManager.SERVICE);
注: 通过服务的 SERVICE 常量可以获取对应的系统服务
订阅事件
/** * subscribe the action publish by MasterService * * @param receiver the event receiver * @param parameterClass the class of parameter * @param topic the topic of event */ <T> void subscribe(EventReceiver<T> receiver, Class<T> parameterClass, String topic); /** * cancel the subscribe * * @param receiver the event receiver */ void unsubscribe(EventReceiver<?> receiver);
private class BatteryEventReceiver implements EventReceiver<BatteryProperties> { @Override public void onReceive(RobotContext robotContext, String action, final BatteryProperties batteryProperties) { // get BatteryProperties } } mReceiver = new BatteryEventReceiver(); robotContext.subscribe(mReceiver, BatteryProperties.class, "event.action.power.BATTERY_CHANGE"); robotContext.unsubscribe(mReceiver);
注:
subscribe通过EventReceiver<T>可以接收发布的事件, 其中parameterClass是事件的参数类型,Cruzr 内部会根据发布事件的参数类型自动反序列化得到最终参数, 详情请见 序列化与反序列化
指令分发
/** * Dispatch a inProcess directive to skill with a param. * * @param skillAction the action of directive * @param paramObj the param to dispatch to the directive * @return the promise of the result */ Promise<Void, DispatchException> dispatchDirective(String skillAction, Object paramObj); /** * Dispatch a inProcess directive to skill with no param. * * @param skillAction he action of directive * @return the promise of the result */ Promise<Void, DispatchException> dispatchDirective(String skillAction);
通过 RobotContext 可以实现进程内的指令分发, 进程间指令分发参考 技能管理 。
- 进程内无参数指令分发
java
robotContext.dispatchDirective("music.PLAY")
.done(new DoneCallback<Void>() {
@Override
public void onDone(Void aVoid) {
// 分发成功执行到此处
}
})
.fail(new FailCallback<DispatchException>() {
@Override
public void onFail(DispatchException e ) {
// 分发失败执行到此处
}
});
- 进程内带参数指令分发
java
Music music = new Music();
robotContext.dispatchDirective("music.PLAY", music);
注: 进程内带参数分发不需要考虑序列化问题