您可以在物联网平台上自定义Topic类,设备将消息发送到自定义Topic中,服务端通过调用AFU SDK中的方法向设备发布指令。自定义Topic通信不使用物模型,消息的数据结构由您自定义。
使用自定义Topic进行通信
准备开发环境
本示例中,服务端使用Java版的AFU 安服优SDK,需先准备Java开发环境。在项目中添加以下Maven依赖,导入安服优SDK相关依赖。
通过在pom.xml文件中添加Maven依赖安装AFU SDK。
<!--AFU SDK核心包,AFU SDK的使用基础 -->
<dependency>
<groupId>io.gitee.afucloud</groupId>
<artifactId>afu-base-common-sdk</artifactId>
<version>1.0.0</version>
</dependency>
为了AFU SDK完整功能使用,还需要将以下依赖项添加到pom.xml文件中,否则将出现异常。
<!--其他相关依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<!-- MQTT-jar -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.fusesource.mqtt-client</groupId>
<artifactId>mqtt-client</artifactId>
<version>1.14</version>
</dependency>
<!-- http请求-jar -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.5.6</version>
</dependency>
<!-- kafka-jar -->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.8.0</version>
</dependency>
1.服务器发送消息给设备
以下是服务器通过SDK发送消息给设备示例
使用时请将如下示例中的userAccessKey、userSecret、ProductKey、DeviceName、DeviceSecret分别替换成您的accessKey 、secret、productKey、deviceName、DeviceSecret。
import com.afu.common.sdk.config.AfuConfig;
import com.afu.common.sdk.devicelink.AfuDeviceLinkMqtt;
import com.afu.common.sdk.devicelink.AfuMqttMethod;
public class TestMqttPublish {
public static void main(String[] args) throws Exception {
//连接安服优物联网云平台
AfuConfig afuConfig = new AfuConfig();
afuConfig.setMqttUrl("MqttUrl");//"tcp://xxxxx"连接安服优物联网云平台MQTT服务器
afuConfig.setMqttClientId("MqttClientId"); //"DeviceName/ProductKey"用于区分MQTT客户端,每个设备请设置唯一的ClientId
afuConfig.setProductKey("ProductKey"); //创建产品后,系统生成,在产品详情页查看
afuConfig.setDeviceName("DeviceName"); //创建设备设置的名称
afuConfig.setDeviceSecret("DeviceSecret"); //创建设备后,系统生成,在设备详情页查看
afuConfig.setUserAccessKey("UserAccessKey"); //请登录安服优物联网云平台-->个人中心查看
afuConfig.setUserSecret("UserSecret"); //请登录安服优物联网云平台-->个人中心查看
AfuDeviceLinkMqtt linkMqtt = new AfuDeviceLinkMqtt(afuConfig);
String topic="/DeviceName/ProductKey/user/get";
//实例化AfuMqttMethod对象,其中方法能直接进行相应操作
AfuMqttMethod afuMqttMethod = new AfuMqttMethod(linkMqtt);
//执行发送消息
String publish = afuMqttMethod.publish(topic, "this is test");
System.out.println("返回值是:"+publish);
}
}
发布方法:publish
请求参数:
名称 | 类型 | 是否必选 | 示例值 | 描述 |
---|---|---|---|---|
topic | String | 是 | “/7sgHs*/Pfp5*/user/get” | 发布Topic |
message | String | 是 | “mqttTest” | 发布消息 |
返回数据实体示例
{
"status":200,
"message":"success"
}
返回数据实体介绍:
名称 | 类型 | 示例值 | 描述 |
---|---|---|---|
message | String | success | 返回信息 |
model | Object | success | 返回结果实体 |
status | String | 200 | 状态码,请参见 错误码文档。 |