public class MainActivity extends AppCompatActivity {
private static IntentFilter action;
RecyclerView recycler;
private final String payloadJson1="{"ParkingState":1}";
final int POST_DEVICE_PROPERTIES_SUCCESS = 1002;
final int POST_DEVICE_PROPERTIES_ERROR = 1003;
final int UPDATE_UI = 1004;
private MqttClient mqttClient=null;
private String responseBody = "";
private static final String TAG =MainActivity.class.getSimpleName();
private ArrayList datas = new ArrayList<>();
private String temper_str="未知";
private String humdity_str="未知";
private String passwd_str="未知";
private dataBean bean = new dataBean();
MyAdapter adapter;
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;
case UPDATE_UI:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd\nHH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());
String str_time = formatter.format(curDate);
datas.clear();
bean = new dataBean("湿度",humdity_str,str_time,getResources().getDrawable(R.drawable.ic_humdity, null));
datas.add(bean);
bean = new dataBean("温度",temper_str,str_time,getResources().getDrawable(R.drawable.ic_temperature, null));
datas.add(bean);
bean = new dataBean("验证码",passwd_str,str_time,getResources().getDrawable(R.drawable.ic_temperature, null));
datas.add(bean);
adapter.notifyDataSetChanged();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recycler = findViewById(R.id.recyclerView);
RefreshLayout refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
refreshLayout.setRefreshHeader(new ClassicsHeader(this));
refreshLayout.setRefreshFooter(new ClassicsFooter(this));
refreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshlayout) {
refreshlayout.finishRefresh(2000);
mHandler.postDelayed(() -> postDeviceProperties1(), 1000);
}
});
refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore(RefreshLayout refreshlayout) {
refreshlayout.finishLoadMore(2000);
mHandler.postDelayed(() -> postDeviceProperties1(), 1000);
}
});
new Thread(() -> initMQTTClient()).start();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd\nHH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());
String str_time = formatter.format(curDate);
bean = new dataBean("湿度",temper_str,str_time,getResources().getDrawable(R.drawable.ic_humdity, null));
datas.add(bean);
bean = new dataBean("温度",humdity_str,str_time,getResources().getDrawable(R.drawable.ic_temperature, null));
datas.add(bean);
bean = new dataBean("验证码",passwd_str,str_time,getResources().getDrawable(R.drawable.ic_temperature, null));
datas.add(bean);
adapter = new MyAdapter(this, datas);
LinearLayoutManager manager = new LinearLayoutManager(this);
recycler.setLayoutManager(manager);
recycler.setItemAnimator(new DefaultItemAnimator());
recycler.setAdapter(adapter);
}
private void initMQTTClient() {
try {
String targetServer ="tcp://114.55.65.118:1883";
String mqttclientId = "RA6M5_Android1";
String mqttUsername = "RA6M5_Android_User1";
String mqttPassword = "123456";
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();
connOpts.setMqttVersion(4);
connOpts.setAutomaticReconnect(true);
connOpts.setCleanSession(true);
connOpts.setUserName(mqttUsername);
connOpts.setPassword(mqttPassword.toCharArray());
connOpts.setKeepAliveInterval(60);
mqttClient.connect(connOpts);
mqttClient.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
Log.e(TAG, "cause ---> " + cause);
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.e(TAG, "topic ---> " + topic + " message--->" + message);
if (topic.equals("RA6M5/2")){
String mqtt_str = new String(message.getPayload());
JSONObject json = new JSONObject(mqtt_str);
temper_str = json.getString("temper");
humdity_str = json.getString("humdity");
passwd_str = json.getString("passwd");
mHandler.sendEmptyMessage(UPDATE_UI);
Log.e(TAG, "update--finish ");
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.e(TAG, "token ---> " + token);
}
});
mqttClient.subscribe("RA6M5/2");
Log.d(TAG, "connected " + url);
}
private void showToast(String msg) {
Toast.makeText(MainActivity.this, msg,Toast.LENGTH_SHORT).show();
}
private void postDeviceProperties1() {
try {
Random random = new Random();
String payload = "askInfo";
responseBody = payload;
MqttMessage message = new MqttMessage(payload.getBytes("utf-8"));
message.setQos(1);
String pubTopic = "RA6M5/1";
mqttClient.publish(pubTopic, message);
Log.d(TAG, "publish topic=" + pubTopic + ",payload=" + payload);
mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_SUCCESS);
} catch (Exception e) {
e.printStackTrace();
responseBody = e.getMessage();
mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_ERROR);
Log.e(TAG, "postDeviceProperties error " + e.getMessage(), e);
}
}
}