1. 准备工作
1.1 注册阿里云账号
使用个人淘宝账号或手机号,开通阿里云账号,并通过__实名认证(可以用支付宝认证)__
1.2 免费开通IoT物联网套件
产品官网 https://www.aliyun.com/product/iot
1.3 软件环境
JDK安装
编辑器 IDEA
2. 开发步骤
2.1 云端开发
1) 创建高级版产品
2) 功能定义,产品物模型添加属性
添加产品属性定义
属性名 | 标识符 | 数据类型 | 范围 |
温度 | temperature | float | -50~100 |
湿度 | humidity | float | 0~100 |
物模型对应属性上报topic
/sys/替换为productKey/替换为deviceName/thing/event/property/post
物模型对应的属性上报payload
{
id: 123452452,
params: {
temperature: 26.2,
humidity: 60.4
},
method: "thing.event.property.post"
}
3) 设备管理>注册设备,获得身份三元组
2.2 设备端开发
我们以java程序来模拟设备,建立连接,上报数据。
1) build.gradle添加sdk依赖
dependencies {
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0'
}
2) AliyunIoTSignUtil工具类
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Map;
/**
* AliyunIoTSignUtil
*/
public class AliyunIoTSignUtil {
public static String sign(Map<String, String> params, String deviceSecret, String signMethod) {
//将参数Key按字典顺序排序
String[] sortedKeys = params.keySet().toArray(new String[] {});
Arrays.sort(sortedKeys);
//生成规范化请求字符串
StringBuilder canonicalizedQueryString = new StringBuilder();
for (String key : sortedKeys) {
if ("sign".equalsIgnoreCase(key)) {
continue;
}
canonicalizedQueryString.append(key).append(params.get(key));
}
try {
String key = deviceSecret;
return encryptHMAC(signMethod,canonicalizedQueryString.toString(), key);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* HMACSHA1加密
*
*/
public static String encryptHMAC(String signMethod,String content, String key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key.getBytes("utf-8"), signMethod);
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
byte[] data = mac.doFinal(content.getBytes("utf-8"));
return bytesToHexString(data);
}
public static final String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2) {
sb.append(0);
}
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
}
3) 模拟设备MainActivity.java代码
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private TextView msgTextView;
private String productKey = "";// 高级版产品key
private String deviceName = "";//已经注册的设备id
private String deviceSecret = "";//设备秘钥
//property post topic
private final String payloadJson = "{\"id\":%s,\"params\":{\"temperature\": %s,\"humidity\": %s},\"method\":\"thing.event.property.post\"}";
private MqttClient mqttClient = null;
final int POST_DEVICE_PROPERTIES_SUCCESS = 1002;
final int POST_DEVICE_PROPERTIES_ERROR = 1003;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case POST_DEVICE_PROPERTIES_SUCCESS:
showToast("发送数据成功");
break;
case POST_DEVICE_PROPERTIES_ERROR:
showToast("post数据失败");
break;
}
}
};
private String responseBody = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgTextView = findViewById(R.id.msgTextView);
findViewById(R.id.activate_button).setOnClickListener((l) -> {
new Thread(() -> initAliyunIoTClient()).start();
});
findViewById(R.id.post_button).setOnClickListener((l) -> {
mHandler.postDelayed(() -> postDeviceProperties(), 1000);
});
findViewById(R.id.quit_button).setOnClickListener((l) -> {
try {
mqttClient.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
});
}
/**
* 使用 productKey,deviceName,deviceSecret 三元组建立IoT MQTT连接
*/
private void initAliyunIoTClient() {
try {
String clientId = "androidthings" + System.currentTimeMillis();
Map<String, String> params = new HashMap<String, String>(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.cn-shanghai.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) {
e.printStackTrace();
responseBody = e.getMessage();
mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_ERROR);
}
}
public 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(true);
connOpts.setCleanSession(true);
connOpts.setUserName(mqttUsername);
connOpts.setPassword(mqttPassword.toCharArray());
connOpts.setKeepAliveInterval(60);
mqttClient.connect(connOpts);
Log.d(TAG, "connected " + url);
}
/**
* post 数据
*/
private void postDeviceProperties() {
try {
Random random = new Random();
//上报数据
String payload = String.format(payloadJson, String.valueOf(System.currentTimeMillis()), 10 + random.nextInt(20), 50 + random.nextInt(50));
responseBody = payload;
MqttMessage message = new MqttMessage(payload.getBytes("utf-8"));
message.setQos(1);
String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
mqttClient.publish(pubTopic, message);
Log.d(TAG, "publish topic=" + pubTopic + ",payload=" + payload);
mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_SUCCESS);
mHandler.postDelayed(() -> postDeviceProperties(), 5 * 1000);
} catch (Exception e) {
e.printStackTrace();
responseBody = e.getMessage();
mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_ERROR);
Log.e(TAG, "postDeviceProperties error " + e.getMessage(), e);
}
}
private void showToast(String msg) {
msgTextView.setText(msg + "\n" + responseBody);
}
}
3. 启动运行
3.1 设备启动
3.2 云端查看设备运行状态
物联网平台产品介绍详情:https://www.aliyun.com/product/iot/iot_instc_public_cn
阿里云物联网平台客户交流群