1.pom文件引入物联网平台的 java SDK
阿里云 IoT java SDK:
<!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-iot -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-iot</artifactId>
<version>7.8.0</version>
</dependency>
阿里云 java SDK公共包:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.5.1</version>
</dependency>
2.远程信息发送方法
public void sendTopicTODevice() {
//初始化SDK===================================================================
String accessKey = "your accessKey";
String accessSecret = "your accessSecret";
String regionId = "cn-shanghai";
String uid = "your uid";
String deviceName = "your deviceName ";
String productKey = "your productKey ";
try {
DefaultProfile.addEndpoint(
"cn-shanghai",
regionId,
"Iot",
"iot.cn-shanghai.aliyuncs.com");
}
catch (com.aliyuncs.exceptions.ClientException e)
{
e.printStackTrace();
}
IClientProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
DefaultAcsClient client = new DefaultAcsClient(profile); //初始化SDK客户端
//调用物联网平台的API(以Pub方式发布消息到topic--即绑定相应topic的设备)====================
PubRequest request = new PubRequest();
request.setProductKey(productKey);
request.setMessageContent(Base64.encodeBase64String("哈罗,我的".getBytes()));
request.setTopicFullName("你的设备下topic路径");
request.setQos(0); //目前支持QoS0和QoS1
try
{
PubResponse response = client.getAcsResponse(request);
System.out.println(response.getSuccess());
System.out.println(response.getErrorMessage());
}
catch (com.aliyuncs.exceptions.ServerException e)
{
e.printStackTrace();
}
catch (com.aliyuncs.exceptions.ClientException e)
{
e.printStackTrace();
}
}
以上代码直接放在spring boot的test类能直接发送消息。
3. lamp_control网页代码片段
<script>
layui.use(['form', 'layedit', 'laydate','layer'], function(){
$(document).on('click','#open_btn',function() {
layer.msg("打开")
openControlMessage(); //发送控制消息到队列
});
});
function openControlMessage(){
$.ajax({
url:"/lamp/open_message",
type: "GET",
});
}
</script>
4.对应Controller代码片段
@Controller
@RequestMapping("/lamp")
public class LampController {
@Resource
private IControlMessageProducer controlMessageProducer;
@RequestMapping("/lamp_control")
public String lampControl(){
return "lamp_control";
}
@RequestMapping("/open_message")
public String openControl(){
controlMessageProducer.sendTopicTODevice(); //调用发送消息的方法
return "lamp_control";
// return null;
}
}