一、需求:通过阿里云物联网平台监控温度计的温度和湿度变化
二、实践
1.创建自己的产品(温度计),并设置产品属性(温度、湿度)
1.1创建产品的具体步骤
https://help.aliyun.com/document_detail/73728.html?spm=a2c4g.11186623.6.571.11a22cf0qOFUyz
1.2设置产品属性的具体步骤 功能定义 》》 编辑草稿 》》 添加自定义功能
2.创建产品的设备(温度计)
https://help.aliyun.com/document_detail/73729.html?spm=a2c4g.11186623.6.573.670d5130O8rGlX
3.发布更新产品
点击产品 》》 功能定义 》》编辑草稿 》》发布更新
三、服务器建立与阿里云物联网平台的连接,并模拟数据上行到阿里云物联网平台
1.添加依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.2-jre</version>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.2</version>
</dependency>
2.demo
package com.company.lotdemo.core.demo;
import com.company.lotdemo.core.util.AliyunIoTSignUtil;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class IoTDemo {
public static String productKey = "温度计产品id";
public static String deviceName = "温度计设备的名称";
public static String deviceSecret = "温度计设备的秘钥";
public static String regionId = "cn-shanghai";
//物模型-属性上报topic
private static String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
//高级版 物模型-属性上报payload
//json格式的温度、湿度数据设置
private static final String payloadJson =
"{" +
" \"id\": %s," +
" \"params\": {" +
" \"temperature\": %s," +
" \"humidity\": %s" +
" }," +
" \"method\": \"thing.event.property.post\"" +
"}";
private static MqttClient mqttClient;
private static Random random = new Random();
private static DecimalFormat df = new DecimalFormat("0.#");
public static void main(String [] args) {
initAliyunIoTClient();
ScheduledExecutorService scheduledThreadPool = new ScheduledThreadPoolExecutor(1,
new ThreadFactoryBuilder().setNameFormat("thread-runner-%d").build());
scheduledThreadPool.scheduleAtFixedRate(()->postDeviceProperties(), 10,10, TimeUnit.SECONDS);
}
private static void initAliyunIoTClient() {
try {
String clientId = "java" + System.currentTimeMillis();
Map<String, String> params = new HashMap<>(16);
params.put("productKey", productKey);
params.put("deviceName", deviceName);
params.put("clientId", clientId);
String timestamp = String.valueOf(System.currentTimeMillis());
params.put("timestamp", timestamp);
// cn-shanghai
String targetServer = "tcp://" + productKey + ".iot-as-mqtt."+regionId+".aliyuncs.com:1883";
String mqttclientId = clientId + "|securemode=3,signmethod=hmacsha1,timestamp=" + timestamp + "|";
String mqttUsername = deviceName + "&" + productKey;
String mqttPassword = AliyunIoTSignUtil.sign(params, deviceSecret, "hmacsha1");
connectMqtt(targetServer, mqttclientId, mqttUsername, mqttPassword);
} catch (Exception e) {
System.out.println("initAliyunIoTClient error " + e.getMessage());
}
}
public static void connectMqtt(String url, String clientId, String mqttUsername, String mqttPassword) throws Exception {
MemoryPersistence persistence = new MemoryPersistence();
mqttClient = new MqttClient(url, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
// MQTT 3.1.1
connOpts.setMqttVersion(4);
connOpts.setAutomaticReconnect(false);
connOpts.setCleanSession(true);
connOpts.setUserName(mqttUsername);
connOpts.setPassword(mqttPassword.toCharArray());
connOpts.setKeepAliveInterval(60);
mqttClient.connect(connOpts);
}
private static void postDeviceProperties() {
try {
//上报数据
String payload = String.format(payloadJson, System.currentTimeMillis(), df.format(25+random.nextFloat()*10), df.format(50+random.nextFloat()*30));
System.out.println("post :"+payload);
MqttMessage message = new MqttMessage(payload.getBytes("utf-8"));
message.setQos(1);
mqttClient.publish(pubTopic, message);
} catch (Exception e) {
}
}
}
四、阿里云物联网平台可视化界面数据监测(可以看到温度、湿度数据的变化)
ps:记得开启实时刷新哦
五、阿里云物联网平台的在线调试功能(可以设置和获取温度、湿度的值)