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);
}
}