使用语音命令通过蓝牙将数据从Android应用发送到arduino时出现问题

时间:2018-06-24 01:18:40

标签: java android bluetooth arduino-uno

我想通过蓝牙hc06将数据从我的Android应用发送到arduino。我使用Android TTS发出语音命令。如果语音命令匹配,则发送功能将向与arduino代码上写入的现有字符串匹配的特定字符串发送到arduino。问题是,无论何时发出语音命令,它都无法发送发送函数的字符串,并且蓝牙连接也会失败。但是,每当我使用按钮发送相同的字符串时,它都有效!请帮忙。这是我的代码。

package com.makers.alsakif.easyon;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Locale;
import java.util.UUID;

public class SwitchBoard extends AppCompatActivity implements TextToSpeech.OnInitListener{



ToggleButton SW1;
Button SW0;
private TextView BufferIN;
private ImageButton btnSpeak;
private TextToSpeech tts;
private String ttsText;

private final int REQ_CODE_SPEECH_INPUT = 100;
Handler bluetoothIn;
final int handlerState = 0;

private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder DataStringIN = new StringBuilder ();
//User defined private class for bluetooth connection and background work... !<<DEFINED AT THE END OF THIS SCRIPT>>!
private ConnectedThread MyBTCon;
// Service unique identifier - SPP UUID
private static final UUID BTMODULEUUID = UUID.fromString ("00001101-0000-1000-8000-00805F9B34FB");
// String for the MAC address
private static String address = null;

//****************************************************************
//TTS properties
private static final String[] commands = {"on", "off", "turn on the light", "turn off the light"};
boolean foundCommand;


@SuppressLint("HandlerLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_switch_board);

    SW1 = findViewById(R.id.ID_SW1);
    SW0 = findViewById(R.id.ID_SW0);


    tts = new TextToSpeech(this, this);
    BufferIN = findViewById(R.id.ID_status);
    btnSpeak = findViewById(R.id.btnSpeak);


    bluetoothIn = new Handler () {
        public void handleMessage (android.os.Message msg) {
            if (msg.what == handlerState) {
                String readMessage = (String) msg.obj;
                DataStringIN.append (readMessage);

                int endOfLineIndex = DataStringIN.indexOf ("#");

                if (endOfLineIndex> 0) {
                    String dataInPrint = DataStringIN.substring (0, endOfLineIndex);
                    BufferIN.setText (dataInPrint); // <- <- PART A MODIFY> -> ->
                    DataStringIN.delete (0, DataStringIN.length ());
                }
            }
        }
    };

    btAdapter = BluetoothAdapter.getDefaultAdapter (); // get Bluetooth adapter
    VerifyBTStatus();


    btnSpeak.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            promptSpeechInput();
        }
    });

    SW1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                MyBTCon.write("jjol0");
            }else{
                MyBTCon.write("niv0");
            }
        }
    });


    SW0.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (btSocket != null)
            {
                try {btSocket.close ();}
                catch (IOException e)
                {Toast.makeText (getBaseContext (), "Error", Toast.LENGTH_SHORT) .show () ;;}
            }
            finish ();
        }
    });
}

/**
 * Showing google speech input dialog
 * */
private void promptSpeechInput() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            getString(R.string.speech_prompt));
    try {
        startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
    } catch (ActivityNotFoundException a) {
        Toast.makeText(getApplicationContext(),
                getString(R.string.speech_not_supported),
                Toast.LENGTH_SHORT).show();
    }
}

/**
 * Receiving speech input
 * */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);


    switch (requestCode) {
        case REQ_CODE_SPEECH_INPUT: {
            if (resultCode == RESULT_OK && null != data) {

                ArrayList<String> result = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                foundCommand = false;
                for(String command : commands) {
                    if(result.contains(command)) {
                        foundCommand = true;
                        if(command == "on") {
                            BufferIN.setText("You say -on-");
                            ttsText = "The light is turn on now.";
                            speak();
                            btAdapter = BluetoothAdapter.getDefaultAdapter (); // get Bluetooth adapter
                            VerifyBTStatus();
                            MyBTCon.write("jjol0");
                        }
                    }
                }

                if (!foundCommand) {
                    BufferIN.setText("Unknown what you say");
                    ttsText = "I don't know what you want!";
                    speak();
                }
                //txtSpeechInput.setText(result.get(0));
            }
            break;
        }

    }
}

private void speak() {
    String text = ttsText;

    if(Build.VERSION.SDK_INT >= 21){
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
    }else{
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
}

private BluetoothSocket createBluetoothSocket (BluetoothDevice device) throws IOException
{
    // create a secure output connection for the device
    // using the UUID service
    return device.createRfcommSocketToServiceRecord (BTMODULEUUID);
}

@Override
public void onResume(){
    super.onResume ();
    // Get the MAC address from DeviceListActivity via intent
    Intent intent = getIntent ();
    // Get the MAC address from DeviceListActivity via EXTRA
    address = intent.getStringExtra (DeviceList.EXTRA_DEVICE_ADDRESS); // <- <- PART A MODIFY> -> ->
    // Set the MAC address
    BluetoothDevice device = btAdapter.getRemoteDevice (address);

    try
    {
        btSocket = createBluetoothSocket (device);
    } catch (IOException e) {
        Toast.makeText (getApplicationContext (), "The Socket Creation failed", Toast.LENGTH_LONG) .show ();
    }
    // Establish the connection with the Bluetooth socket.
    try
    {
        btSocket.connect ();
    } catch (IOException e) {
        try {
            btSocket.close ();
        } catch (IOException e2) {}
    }
    MyBTCon = new ConnectedThread (btSocket);
    MyBTCon.start ();
}

@Override
public void onPause ()
{
    super.onPause ();
    tts.shutdown();
    try
    {// When you exit the application this part allows
        // that the socket is not left open
        btSocket.close ();
    } catch (IOException e2) {}
}

private void VerifyBTStatus () {

    if (btAdapter == null) {
        Toast.makeText (getBaseContext (), "The device does not support bluetooth", Toast.LENGTH_LONG) .show ();
    } else {
        if (btAdapter.isEnabled()) {
            //Do nothing
        } else {
            Intent enableBtIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult (enableBtIntent,1);
        }
    }
}

@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {

        int result = tts.setLanguage(Locale.US);


        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "Language is not supported");
        } else {

            speak();
        }

    } else {
        Log.e("TTS", "Init Failed");
    }

}


private class ConnectedThread extends Thread
{
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread (BluetoothSocket socket)
    {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try
        {
            tmpIn = socket.getInputStream ();
            tmpOut = socket.getOutputStream ();
        } catch (IOException e) {}
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run ()
    {
        byte [] buffer = new byte [256];
        int bytes;

        // It stays in listening mode to determine the data entry
        while (true) {
            try {
                bytes = mmInStream.read (buffer);
                String readMessage = new String (buffer, 0, bytes);
                // Send the data obtained to the event via handler
                bluetoothIn.obtainMessage (handlerState, bytes, -1, readMessage) .sendToTarget ();
            } catch (IOException e) {
                break;
            }
        }
    }
    // Frame Send
    public void write (String input)
    {
        byte[] msgBuffer = input.getBytes();
        try {
            mmOutStream.write (msgBuffer);
        }
        catch (IOException e)
        {
            // if it is not possible to send data the connection is closed
            Toast.makeText (getBaseContext (), "Connection failed", Toast.LENGTH_LONG) .show ();
            finish ();
        }
    }
}

}

0 个答案:

没有答案