Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.ArrayList;
- import java.util.UUID;
- import android.os.Bundle;
- import android.os.Handler;
- import android.speech.RecognizerIntent;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.ArrayAdapter;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- import android.app.Activity;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothSocket;
- import android.content.Intent;
- import android.util.Log;
- public class Menu extends Activity implements OnClickListener{
- //Variavel do Sintetizador de Voz---------------
- private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
- //Tag para o log d do android
- private static final String TAG = "Thiago";
- //Variaveis da Conexao Bluetooth--------------
- private BluetoothAdapter mBluetoothAdapter = null;
- private BluetoothSocket btSocket = null;
- private OutputStream outStream = null;
- //endereco de conexao BT a ser pareado do arduino
- private static String address = "20:13:01:24:02:08";
- //meu id do android
- private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
- //inputStream para armazenar as entradas
- private InputStream inStream = null;
- //Thread do Android
- Handler handler = new Handler();
- //delimitador fr Bits a serem enviados
- byte delimiter = 10;
- boolean stopWorker = false;
- //ponteiro para leitura do Buffer
- int readBufferPosition = 0;
- //Buffer de Bits
- byte[] readBuffer = new byte[1024];
- //boolean para conexão
- boolean conetado =false;
- //Variavel que armazena o dado a ser enviado
- String dadoEnviarSintetizador = "";
- //variavel que armazena o dado apos o tratamento (validação)
- String dadoSintetizado ="";
- //Componentes Android
- Button botaoConectar;
- Button botaoSintetizador;
- EditText edit;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- //chama o XML da Activity
- setContentView(R.layout.menu);
- //cria o Alias para os componentes do XML
- edit = (EditText) findViewById(R.id.editText1);
- botaoConectar = (Button) findViewById(R.id.botaoConectar);
- botaoSintetizador = (Button) findViewById(R.id.botaoSintetizador);
- //Implementa On Click Listenner para o botão de conexao
- //por ser mais estavel para esta tarefa de conexão
- botaoConectar.setOnClickListener(this);
- //seta o botão Sintetizador como desativado
- //para não tentar enviar os dados antes de conectar
- botaoSintetizador.setEnabled(false);
- edit.setEnabled(false);
- try{
- //checa o bluetooth
- CheckBt();
- //inicia a paridade
- BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
- Log.e("Teste", device.toString());
- }catch (Exception e) {
- // TODO: handle exception
- }
- try{
- //Listener do botao do Sintetizador de Voz
- botaoSintetizador.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- //chama o metodo que é responsavel pela sintetização
- startVoiceRecognitionActivity();
- }
- });
- }catch (Exception e) {
- // TODO: handle exception
- }
- try{
- //Evento para Enviar o dado via BT pelo edit (Sem Sintetizador)
- edit.setOnLongClickListener(new View.OnLongClickListener() {
- public boolean onLongClick(View v) {
- //Captura o Conteudo do edit
- String enviaDadoEdit = edit.getText().toString();
- //envia para o metodo de validação antes de enviar para o proximo dispositivo
- validaDados(enviaDadoEdit);
- //envia o dado para o dispositivo Client
- writeData(dadoEnviarSintetizador);
- return true;
- }
- });
- }catch (Exception e) {
- // TODO: handle exception
- }
- }
- //Metodos para input de Voz
- //*************************************************
- /**
- * Fire an intent to start the speech recognition activity.
- */
- private void startVoiceRecognitionActivity() {
- try{
- Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
- intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
- RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
- intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
- startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
- }catch (Exception e) {
- Toast.makeText(getApplicationContext(), "Bluetooth Desativado ou não Pareado!",
- Toast.LENGTH_SHORT).show();
- }
- }
- /**
- * Handle the results from the recognition activity.
- */
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
- // Fill the list view with the strings the recognizer thought it could have heard
- ArrayList<String> matches = data.getStringArrayListExtra(
- RecognizerIntent.EXTRA_RESULTS);
- dadoEnviarSintetizador =" ";
- //verifica String Salva no Sintezador de Voz
- for(int index =0; index < matches.size(); index++){
- if(!dadoEnviarSintetizador.equalsIgnoreCase("1") && !dadoEnviarSintetizador.equalsIgnoreCase("0")
- && !dadoEnviarSintetizador.equalsIgnoreCase("3") && !dadoEnviarSintetizador.equalsIgnoreCase("4")
- && !dadoEnviarSintetizador.equalsIgnoreCase("5")){
- edit.setText(matches.get(index).toString());
- validaDados(matches.get(index).toString());
- }
- }
- }
- super.onActivityResult(requestCode, resultCode, data);
- writeData(dadoEnviarSintetizador);
- }
- //Metodos para input de Voz
- //*************************************************
- //trata os dado para posteriormente enviar para o dispositivo (arduino)
- //o arduino le os dados byte por byte, a maneira mais viavel é tratalo e enviar apenas 1 carater
- public void validaDados(String dadoBruto){
- //se a frase falada ou digitada, for algumas dessas abaixo, é gravado a condição na variavel envia
- // dadoEnviarSintetizador que posteriormente é enviado para o arduino
- if(dadoBruto.equalsIgnoreCase("Ligar") || dadoBruto.equalsIgnoreCase("Ativar") || dadoBruto.equalsIgnoreCase("Acender")){
- dadoEnviarSintetizador ="1";
- }else if(dadoBruto.equalsIgnoreCase("Desligar")|| dadoBruto.equalsIgnoreCase("Desativar") || dadoBruto.equalsIgnoreCase("Apagar")){
- dadoEnviarSintetizador ="0";
- }else if(dadoBruto.equalsIgnoreCase("Mario")|| dadoBruto.equalsIgnoreCase("Mario Bross")|| dadoBruto.equalsIgnoreCase("Mario Bros")){
- dadoEnviarSintetizador ="3";
- }else if(dadoBruto.equalsIgnoreCase("Piratas do Caribe")|| dadoBruto.equalsIgnoreCase("Piratas do Karibe")|| dadoBruto.equalsIgnoreCase("Piratas") || dadoBruto.equalsIgnoreCase("Medo do Escuro")){
- dadoEnviarSintetizador ="5";
- }else {
- dadoEnviarSintetizador ="";
- }
- }
- //metodo do Listenner do botao de conexao bluetooth
- @Override
- public void onClick(View control) {
- switch (control.getId()) {
- case R.id.botaoConectar:
- try{
- conetado = Connect();
- if(conetado){
- botaoConectar.setEnabled(false);
- botaoSintetizador.setEnabled(true);
- edit.setEnabled(true);
- }else{
- botaoConectar.setEnabled(true);
- botaoSintetizador.setEnabled(false);
- edit.setEnabled(true);
- }
- }catch(Exception ex){
- }
- break;
- }
- }
- //Metodos para Conexao Bluetooth----------------------------------------
- //*************************************************
- //checa se o BT esta ligado
- private void CheckBt() {
- mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- if (!mBluetoothAdapter.isEnabled()) {
- Toast.makeText(getApplicationContext(), "Bluetooth Desativado !",
- Toast.LENGTH_SHORT).show();
- mBluetoothAdapter.enable();
- }
- if (mBluetoothAdapter == null) {
- Toast.makeText(getApplicationContext(),
- "Bluetooth null !", Toast.LENGTH_SHORT)
- .show();
- }
- }
- //metodo de conexão
- public boolean Connect() {
- try{
- Log.d(TAG, address);
- //pega o adress do bluetooth para iniciar a pariedade
- BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
- Log.d(TAG, "Connecting to ... " + device);
- //cancela a busca apos armazenar no BluetoothDevice
- mBluetoothAdapter.cancelDiscovery();
- try {
- //envia para o Socket a ID do dispositivo local
- btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
- //requisita a conexão
- btSocket.connect();
- Log.d(TAG, "Conexão Realizada!.");
- //chama o metodo que inicia a transferencia dos dados
- beginListenForData();
- } catch (IOException e) {
- try {
- //fecha o socket caso ocorra algum erro
- btSocket.close();
- return false;
- } catch (IOException e2) {
- Log.d(TAG, "Unable to end the connection");
- return false;
- }
- }
- return true;
- }catch (Exception e) {
- return false;
- }
- }
- //metodo para escreve no BT
- private void writeData(String data) {
- try {
- outStream = btSocket.getOutputStream();
- } catch (IOException e) {
- Log.d(TAG, "Bug BEFORE Sending stuff", e);
- }
- try {
- String message = data;
- byte[] msgBuffer = message.getBytes();
- outStream.write(msgBuffer);
- } catch (IOException e) {
- Log.d(TAG, "Bug while sending stuff", e);
- }
- }
- @Override
- //encerra a conexao apos o envio dos dados
- //(Não é necessario) mais é padrao do Android
- protected void onDestroy() {
- super.onDestroy();
- try {
- btSocket.close();
- } catch (IOException e) {
- }
- }
- // inicia a transferencia dos dados
- public void beginListenForData() {
- try {
- inStream = btSocket.getInputStream();
- } catch (IOException e) {
- }
- Thread workerThread = new Thread(new Runnable()
- {
- public void run()
- {
- while(!Thread.currentThread().isInterrupted() && !stopWorker)
- {
- try
- {
- int bytesAvailable = inStream.available();
- if(bytesAvailable > 0)
- {
- byte[] packetBytes = new byte[bytesAvailable];
- inStream.read(packetBytes);
- for(int i=0;i<bytesAvailable;i++)
- {
- byte b = packetBytes[i];
- if(b == delimiter)
- {
- byte[] encodedBytes = new byte[readBufferPosition];
- System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
- final String data = new String(encodedBytes, "US-ASCII");
- readBufferPosition = 0;
- handler.post(new Runnable()
- {
- public void run()
- {
- }
- });
- }
- else
- {
- readBuffer[readBufferPosition++] = b;
- }
- }
- }
- }
- catch (IOException ex)
- {
- stopWorker = true;
- }
- }
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement