连续接收传感器输出

时间:2015-06-21 09:54:41

标签: android android-asynctask

我正试图从Android手机控制一个arduino微控制器。 我需要帮助来连续接收温度传感器的输出并将其显示在文本视图中。

以下是代码:

package com.war10ck6001gmail.finalproject;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends ActionBarActivity {
    public ToggleButton fan, light, manauto;
    public Button inc, dec;
    public TextView temp;
    public Toolbar mToolbar;
    TCPClient mTcpClient = null;
    public connectTask conctTask = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        // connect to the server

        temp = (TextView) findViewById(R.id.temprature);
        fan = (ToggleButton) findViewById(R.id.fanbutton);
        light = (ToggleButton) findViewById(R.id.lightbutton);
        manauto = (ToggleButton) findViewById(R.id.manauto);
        inc = (Button) findViewById(R.id.increment);
        dec = (Button) findViewById(R.id.decrement);

        Automatic(light);
        Automatic(fan);
        Automatic(inc);
        Automatic(dec);
        conctTask = new connectTask();

        conctTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        mTcpClient = null;

        manauto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Manual(light);
                    Manual(fan);
                    Manual(inc);
                    Manual(dec);
                    mTcpClient.sendMessage("Man");
                }
                else {
                    Automatic(light);
                    Automatic(fan);
                    Automatic(inc);
                    Automatic(dec);
                    mTcpClient.sendMessage("Auto");
                }
            }
        });
        light.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mTcpClient.sendMessage("0");
                }
                else {
                    mTcpClient.sendMessage("1");
                }
            }
        });
        fan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mTcpClient.sendMessage("2");
                }
                else {
                    mTcpClient.sendMessage("3");
                }
            }
        });
        inc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTcpClient.sendMessage("4");

            }
        });
        dec.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTcpClient.sendMessage("5");
            }
        });
    }

    public void Automatic(Button btn) {
        btn.setEnabled(false);
        btn.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
    }

    public void Manual(Button btn) {
        btn.setEnabled(true);
        btn.getBackground().setColorFilter(null);
    }

    public class connectTask extends AsyncTask<String, String, TCPClient> {
        String finalmessage;

        @Override
        protected TCPClient doInBackground(final String... message) {
            //we create a TCPClient object and
            mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {

                @Override
                //here the messageReceived method is implemented
                public void messageReceived(final String message) {

                    try {
                        //this method calls the onProgressUpdate
                        //publishProgress(message);

                        if (message != null) {
                            //finalmessage = message;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    temp.setText(message);
                                }
                            });
                            System.out.println("Return Message from Socket::::: >>>>> " + message);
                        }
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            mTcpClient.run();
            if (mTcpClient != null) {
                mTcpClient.sendMessage("Initial Message when connected with Socket Server");
            }

               /* runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        temp.setText(finalmessage);
                    }
                });*/
            return null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
            return true;
        }
        if (id == R.id.action_master) {
            return true;
        }
        if (id == R.id.action_bedroom) {
            Intent intent = new Intent(getApplicationContext(), Bedroom.class);
            startActivity(intent);
            return true;
        }
        if (id == R.id.action_Cbedroom) {
            Intent intent = new Intent(getApplicationContext(), Cbedroom.class);
            startActivity(intent);
            return true;
        }
        if (id == R.id.action_diningroom) {
            Intent intent = new Intent(getApplicationContext(), Diningroom.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

这是收到onmessage的课程

public class TCPClient {

    public String serverMessage;
    /**
     * Specify the Server Ip Address here. Whereas our Socket Server is started.
     */
    public static final String SERVERIP = "10.5.38.148"; // your computer IP address
    public static final int SERVERPORT = 8888;
    private OnMessageReceived mMessageListener = null;
    private boolean mRun = false;

    private PrintWriter out = null;
    private BufferedReader in = null;
    MainActivity mainActivity = null;

    /**
     * Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TCPClient(final OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     *
     * @param message text entered by client
     */
    public void sendMessage(String message) {
        if (out != null && !out.checkError()) {
            System.out.println("message: " + message);
            out.println(message);
            out.flush();
        }
    }


    public void stopClient() {
        mRun = false;
    }

    public void run() {
        mRun = true;
        while (mRun) {
            try {
                //here you must put your computer's IP address.
                InetAddress serverAddr = InetAddress.getByName(SERVERIP);

                Log.e("TCP SI Client", "SI: Connecting...");

                //create a socket to make the connection with the server
                Socket socket = new Socket(serverAddr, SERVERPORT);
                try {
                    //send the message to the server
                    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                    Log.e("TCP SI Client", "SI: Sent.");
                    Log.e("TCP SI Client", "SI: Done.");

                    //receive the message which the server sends back
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    //in this while the client listens for the messages sent by the server

                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);

                        Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
                    }
                    serverMessage = null;
                }
                catch (Exception e) {
                    Log.e("TCP SI Error", "SI: Error", e);
                    e.printStackTrace();
                }
                finally {
                    //the socket must be closed. It is not possible to reconnect to this socket
                    // after it is closed, which means a new socket instance has to be created.
                    socket.close();
                }
            }
            catch (Exception e) {
                Log.e("TCP SI Error", "SI: Error", e);
            }
        }
    }

    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}

0 个答案:

没有答案