怎样写一个相似ROS的易用的android机器人框架(2)java
参考项目源码android
咱们实现了相似ROS系统的节点注册和消息转发机制,在这个机制中,节点自定义的消息封装在Bundle
对象中,这样每一个节点的 publish()
都统一了,可是也有很差的,用起来就没那么方便,咱们更但愿定义本身的消息类,将一些复杂的数据填入这个类对象中,而后发布,如机器人马达的数据,能够定义:git
data class MsgMotor(@JvmField var L: Int = 0, @JvmField var R: Int = 0)
转换成Bundle就得这么写app
Bundle().apply { putInt("L", xxx.L) putInt("R",xxx.R) }
其余节点接收到这个消息时又得反向解析一遍,很麻烦 可否简单解决呢?框架
apt能够扫描源码中特定的注解,并根据注解生成特定的代码,所以咱们开发apt工具库,而后在让编译脚本调用这个工具库帮咱们生成这些转换代码。源码目录下ide
dependencies { compile project(":easyAptApi") //指定 apt kapt project(":easyAptProcessor") }
@MessageType("") data class MsgMotor(@JvmField var L: Int = 0, @JvmField var R: Int = 0)
public final class ConvertMsgMotor { public static Bundle toBundle(MsgMotor msgmotor) { Bundle b = new Bundle(); try { b.putInt("L", msgmotor.L); b.putInt("R", msgmotor.R); } catch (Exception e) { e.printStackTrace(); } return b; } public static MsgMotor toMsg(Bundle b) { MsgMotor r = new MsgMotor(); try { r.L = b.getInt("L"); r.R = b.getInt("R"); } catch (Exception e) { e.printStackTrace(); } return r; } }
使用这个ConvertMsgMotor便可实现MsgMotor与Bundle之间的相互转换了。函数
dependencies { compile project(':easyAptApi') compile 'com.google.auto.service:auto-service:1.0-rc2' compile 'com.squareup:javapoet:1.9.0' }
processor的主类须要实现 AbstractProcessor
接口,并添加注解 @AutoService(Processor::class)
,这是com.google.auto.service中的注解,用来生成apt插件库工具
须要定义 resource 目录下的 META-INF/services/javax.annotation.processing.Processor文件,填写主类的完整包名和类名,不然编译脚本将没法搜索到这个插件类gradle
AbstractProcessor
的全部方法这样,一个根据注解自动生成代码的apt插件库机完成了google