This series of IoT App development notes are the learning notes of station B video tutorials, video address:

  • Day1 How does Android project code work
  • Day2 Common controls and interface layout design (part 1)
  • Day3 Common controls and interface layout design (part 2)
  • Day4 Import of MQTT Jar package and debugging of Internet of Things
  • Day5 APP practical control of Internet of Things ESP8266
  • 【7 days Java0 basic Crash Android development 】
  • [7-day Java0 Basic Rapid Android Development] Day7 achievement Demonstration

1. Download the Jar package and import it to the AS project

Jar packages can be downloaded from my unlimited download site:

The import method is very simple, copy the JAR package into the LIbs folder in the AS directory:





Wait until gradle synchronization is complete and the import succeeds.

2. Enable network permissions

Enable permissions in androidmanifest.xml:

<! -- Allows applications to open network sockets -->
<uses-permission android:name="android.permission.INTERNET" />
<! Allow applications to obtain network status
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Copy the code

3. Write functions based on MQTT Jar package

First define the following members:

	private MqttClient client;
    private MqttConnectOptions options;

    private String host = "TCP: / / 122.51.89.94:1883";
    private String userName = "android";
    private String passWord = "android";
    private String mqtt_id = "client-0002";

    private Handler handler;
    private ScheduledExecutorService scheduler;
Copy the code

3.1. MQTT initialization function

//Mqtt initialization function
    private void Mqtt_init(a)
    {
        try {
            // Host is the host name, and test is clientid, which is the ID of the client connected to MQTT. Generally, it is represented by the unique identifier of the client. MemoryPersistence sets the storage mode of CLIentid, which is stored in memory by default
            client = new MqttClient(host, mqtt_id,
                    new MemoryPersistence());
            // Connection Settings for MQTT
            options = new MqttConnectOptions();
            If the value is set to false, the server keeps the connection record of the client. If the value is set to true, the server uses a new identity for each connection to the server
            options.setCleanSession(false);
            // Set the connection user name
            options.setUserName(userName);
            // Set the connection password
            options.setPassword(passWord.toCharArray());
            // Set the timeout period to seconds
            options.setConnectionTimeout(10);
            // Set the heartbeat time in seconds. The server sends a message to the client every 1.5 x 20 seconds to check whether the client is online. However, this method does not provide a reconnection mechanism
            options.setKeepAliveInterval(20);
            // Set the callback
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    // When a connection is lost, it is usually reconnected in this area
                    System.out.println("connectionLost----------");
                    //startReconnect();
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish will execute here
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }
                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe the message is executed here
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    if(topicName.equals("temp"))
                    {
                        // Temperature data received
                        msg.what = 3;   // Received message flag bit
                        msg.obj = message.toString() + "℃";
                        handler.sendMessage(msg);    / / hander comes back
                    }
                    else if (topicName.equals("humi"))
                    {
                        // Humidity data received
                        msg.what = 4;   // Received message flag bit
                        msg.obj = message.toString() + " %RPH";
                        handler.sendMessage(msg);    / / hander comes back
                    }
                    else if(topicName.equals("lightness"))
                    {
                        // Received brightness data
                        msg.what = 5;   // Received message flag bit
                        msg.obj = message.toString() + " Lux";
                        handler.sendMessage(msg);    / / hander comes back
                    }
                    else if(topicName.equals("gas"))
                    {
                        // Received gas data
                        msg.what = 6;   // Received message flag bit
                        msg.obj = message.toString() + "%";
                        handler.sendMessage(msg);    / / hander comes back}}}); }catch(Exception e) { e.printStackTrace(); }}Copy the code

3.2. MQTT connects to emQ-X server functions

 //MQTT connects to emq-x function
    private void Mqtt_connect(a) {
        new Thread(new Runnable() {
            @Override
            public void run(a) {
                try {
                    if(! (client.isConnected()) )// If not already connected
                    {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31; handler.sendMessage(msg); }}catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
Copy the code

3.3. MQTT reconnection function

   / / the MQTT reconnection
    private void startReconnect(a) {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run(a) {
                if(! client.isConnected()) { Mqtt_connect(); }}},0 * 1000.10 * 1000, TimeUnit.MILLISECONDS);
    }
Copy the code

3.4. MQTT publishes message functions

  //MQTT publishes messages
    private void publishmessageplus(String topic,String message2)
    {
        if (client == null| |! client.isConnected()) {return;
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            client.publish(topic,message);
        } catch(MqttException e) { e.printStackTrace(); }}Copy the code

4. Use Handle to handle MQTT receive callback logic

The MQTT function we wrote earlier is executed in the onCreate function:

 Mqtt_init();
 startReconnect();
Copy the code

The logic processing code is executed in the onCreate function:

       handler = new Handler() {
            @SuppressLint("SetTextI18n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1: // Check updates are sent back after startup
                        break;
                    case 2:  // Feedback is sent back

                        break;
                    case 3:  UTF8Buffer MSG =new UTF8Buffer(object.tostring ());
                        //Toast.makeText(MainActivity.this,msg.obj.toString() ,Toast.LENGTH_SHORT).show();
                        temp_text_view.setText(msg.obj.toString());
                        break;
                    case 4:  UTF8Buffer MSG =new UTF8Buffer(object.tostring ());
                        //Toast.makeText(MainActivity.this,msg.obj.toString() ,Toast.LENGTH_SHORT).show();
                        humi_text_view.setText(msg.obj.toString());
                        break;
                    case 5:  UTF8Buffer MSG =new UTF8Buffer(object.tostring ());
                        //Toast.makeText(MainActivity.this,msg.obj.toString() ,Toast.LENGTH_SHORT).show();
                        lightness_text_view.setText(msg.obj.toString());
                        break;
                    case 6:  UTF8Buffer MSG =new UTF8Buffer(object.tostring ());
                        //Toast.makeText(MainActivity.this,msg.obj.toString() ,Toast.LENGTH_SHORT).show();
                        gas_text_view.setText(msg.obj.toString());
                        break;
                    case 30:  // Connection failed
                        Toast.makeText(MainActivity.this."Connection failed" ,Toast.LENGTH_SHORT).show();
                        break;
                    case 31:   // The connection succeeded
                        Toast.makeText(MainActivity.this."Connection successful" ,Toast.LENGTH_SHORT).show();
                        try {
                            // Subscribe to temperature data
                            client.subscribe("temp".1);
                            // Subscribe humidity data
                            client.subscribe("humi".1);
                            // Subscribe brightness data
                            client.subscribe("lightness".1);
                            // Subscribe to gas data
                            client.subscribe("gas".1);
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break; }}};Copy the code

5. Publish JSON data

In the button’s callback function, send the value of the text box wrapped in JSON format and detect exceptions:

// Set the maximum temperature button callback function
max_temp_set_btn.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View view) {
        try{
            String max_temp_str = max_temp_edittext.getText().toString();
            int max_temp_value = Integer.valueOf(max_temp_str);
            String max_temp_json = "{\"name\":\"max_temp\",\"max_temp\":"+String.valueOf(max_temp_value)+"}";          //{"name":"max_temp","max_temp":"23"}
            publishmessageplus("sub_test",max_temp_json);
            Toast.makeText(MainActivity.this, max_temp_json,Toast.LENGTH_SHORT).show();
        }
        catch (Exception e)
        {
            Toast.makeText(MainActivity.this."Setup failed, please enter correct integer value",Toast.LENGTH_SHORT).show(); }}});Copy the code

Welcome to subscribe to my wechat official account: “McUlover666”.