2014-02-07 2 views
1

Я делаю приложение Bluetooth, которое подключается к передатчику/приемнику Bluetooth, который передает последовательные данные. Устройство Bluetooth в конечном итоге будет подключено к датчикам, и эти датчики будут предоставлять данные, которые должны отображаться на моем телефоне. На данный момент я использую симуляторное ПО CoolTerm для отправки данных назад и вперед между моим приложением и внешним устройством Bluetooth. В настоящее время я успешно обнаружил приложение и подключился к устройствам. Но я бегу в некоторых проблем:Последовательные данные связи приложений Android

  1. Во-первых, это любой знает, как установить CoolTerm (ее доступны на Mac и окна с технической точки зрения), но когда я пытаюсь установить его на Ubuntu он не дает исполняемый файл, как это было на окнах. Любой, кто знает, как установить это на ubuntu, пожалуйста, предоставьте мне шаги, которые я уже загрузил с сайта веб-сайта для версии Linux, и разархивировал его.

  2. Хотя при успешном подключении мое приложение отправляет строку, полученную устройством Bluetooth, я не могу получить данные обратно. То, как у меня сейчас настроено настроение, я ожидаю, что всплывающее сообщение, сообщающее мне, что я получил данные, когда внешнее устройство Bluetooth передает мне. Программное обеспечение CoolTerm позволяет отправлять данные, но по какой-то причине это не отображается в моем приложении. Есть идеи?

  3. Наконец-то кто-нибудь знает хороший виджет текстового окна или что-то, что я могу использовать в своем приложении для отправки данных на внешнее устройство Bluetooth. Прямо сейчас у меня есть приложение, которое отправляет строку, как только она подключается.

Ссылка на YouTube: Я внесла некоторые незначительные изменения в это, как будет показано в коде.

Нажмите [здесь] (http://www.youtube.com/watch?v=r55C77_ohi8 «youtube video of app»)! Нажмите [здесь] (https://drive.google.com/?tab=mo&authuser=0#folders/0BwRY4KO_k7sUSGpLX0o4TDFCOFk "более чистый код formmatt")!

Вот код

package com.example.intellicyclemobileside; 

import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.ArrayList; 
import java.util.HashSet; 
import java.util.Set; 
import java.util.UUID; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothSocket; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.view.Menu; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.CompoundButton; 
import android.widget.ListView; 
import android.widget.Toast; 
import android.widget.ToggleButton; 


public class MainActivity extends Activity { 
    ToggleButton toggle_discovery; 
    Button button; 
    ListView listView; 
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    ArrayAdapter<String> mArrayAdapter; 
    ArrayAdapter<String> adapter; 
    ArrayList<String> pairedDevicesList; 
    ArrayList<String> unpairedDevicesList; 
    ArrayList<String> combinedDevicesList; 
    Set<BluetoothDevice> pairedDevices; 
    Set<String> unpairedDevices; 
    BroadcastReceiver mReceiver; 
    String selectedFromList; 
    String selectedFromListName; 
    String selectedFromListAddress; 
    BluetoothDevice selectedDevice; 

/* 
    public BluetoothSocket mmSocket; 
    public BluetoothDevice mmDevice;*/ 
    protected static final int SUCCESS_CONNECT = 0; 
    protected static final int MESSAGE_READ = 1; 
    final int STATE_CONNECTED = 2; 
    final int STATE_CONNECTING = 1; 
    final int STATE_DISCONNECTED = 0; 
    private final UUID MY_UUID = UUID.fromString("0001101-0000-1000-8000-00805F9B34FB"); 
    private static final int REQUEST_ENABLE_BT = 1; 


    Handler mHandler = new Handler(){   
    public void handleMessage(Message msg){ 
     super.handleMessage(msg); 
     switch(msg.what){ 
      case SUCCESS_CONNECT: 
       // Do Something; 
       ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj); 
       Toast.makeText(getApplicationContext(),"CONNECTED",0).show(); 
       String s = "This string proves a socket connection has been established!!"; 
       connectedThread.write(s.getBytes()); 
       break; 
      case MESSAGE_READ: 
       byte[] readBuf = (byte[])msg.obj; 
       String string = new String(readBuf); 
       Toast.makeText(getApplicationContext(),string,0).show(); 

     break; 
     }  
    } 
}; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    button = (Button) findViewById(R.id.findDevices); 
    toggle_discovery = (ToggleButton) findViewById(R.id.deviceDiscoverable); 
    pairedDevicesList = new ArrayList<String>(); 
    unpairedDevicesList = new ArrayList<String>(); 
    unpairedDevices = new HashSet<String>(); 
    listView = (ListView)findViewById(R.id.listView); 

    // Sets up Bluetooth 
    enableBT(); 

    button.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
      // Perform action on click 
      Toast.makeText(getApplicationContext(), "Searching for devices, please wait... ",Toast.LENGTH_SHORT).show(); 
      // Checks for known paired devices 
      pairedDevices = mBluetoothAdapter.getBondedDevices(); 
      displayCominedDevices(); 
      //mBluetoothAdapter.cancelDiscovery(); 
      } 
     }); 

toggle_discovery.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
    if (isChecked) { 
    makeDicoverable(1); 
    } else { 
     // The toggle is disabled 
     makeDicoverable(0); 
     } 
    } 
}); 

listView.setOnItemClickListener(new OnItemClickListener() { 
    public void onItemClick(AdapterView<?> parent, View view,int position, long id) { 
    // When clicked, show a toast with the TextView text 
    selectedFromList = (String) (listView.getItemAtPosition(position)); 
    /*Debugging 
    Toast.makeText(getApplicationContext(), selectedFromList,Toast.LENGTH_SHORT).show();*/ 
     String[] parts = selectedFromList.split(" "); 
    selectedFromListName = parts[0]; 
    selectedFromListAddress = parts[1]; 
    BluetoothDevice selectedDevice = selectedDevice(selectedFromListAddress); 
    mBluetoothAdapter.cancelDiscovery(); 
    ConnectThread ct = new ConnectThread(selectedDevice); 
    ct.start(); 
    //ConnectThread ConnectThread = new ConnectThread(selectedDevice); 
    //connectDevice(); 
    /* Debug Help 
    Toast.makeText(getApplicationContext(), selectedFromListName,Toast.LENGTH_SHORT).show(); 
    Toast.makeText(getApplicationContext(), selectedFromListAddress,Toast.LENGTH_SHORT).show(); 
            Toast.makeText(getApplicationContext(),selectedDevice.getAddress(), Toast.LENGTH_SHORT).show();*/ 
     } 
    }); 
} 


public void displayCominedDevices(){ 
    displayPairedDevices(); 
    displayDetectedDevices(); 
    mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,removeDuplicates(unpairedDevicesList,pairedDevicesList)); 
    listView.setAdapter(mArrayAdapter); 
} 

public BluetoothDevice selectedDevice(String deviceAddress){ 
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    BluetoothDevice device;  
    device = mBluetoothAdapter.getRemoteDevice(deviceAddress); 
    return device; 
} 

@SuppressLint("NewApi") 
public String checkState(BluetoothSocket mmSocket2){ 
    String state = "NOT_KNOWN"; 

    if (mmSocket2.isConnected() == true){ 
     state = "STATE_CONNECTED"; 
    } 
     state = "STATE_DISCONNECTED"; 

    Toast.makeText(getApplicationContext(), state, Toast.LENGTH_SHORT).show(); 

    return state; 
} 


@SuppressWarnings("unchecked") 
public ArrayList<String> removeDuplicates(ArrayList<String> s1, ArrayList<String> s2){ 
    /*Debugging 
    Toast.makeText(getApplication(), "unpairedList " + s1.toString(),Toast.LENGTH_LONG).show(); 
    Toast.makeText(getApplication(), "pairedList " + s2.toString(),Toast.LENGTH_LONG).show(); */ 
    combinedDevicesList = new ArrayList<String>(); 
    combinedDevicesList.addAll(s1); 
    combinedDevicesList.addAll(s2); 
    @SuppressWarnings("unchecked") 
    Set Unique_set = new HashSet(combinedDevicesList); 
    combinedDevicesList = new ArrayList<String>(Unique_set); 
    /*Debugging 
    Toast.makeText(getApplication(),"Combined List" + combinedDevicesList.toString(),Toast.LENGTH_LONG).show(); */ 
    return combinedDevicesList; 
} 

public void enableBT(){ 
    if (mBluetoothAdapter == null) { 
     // Device does not support Bluetooth 
     Toast.makeText(getApplicationContext(), "Bluetooth is not suppourted on Device",Toast.LENGTH_SHORT).show(); 
    } 

    if (!mBluetoothAdapter.isEnabled()) { 
     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
     int resultCode = Activity.RESULT_OK; 
     if(resultCode < 1){ 
      Toast.makeText(getApplicationContext(), "Please Accept Enabling Bluetooth Request!", Toast.LENGTH_LONG).show(); 
     } 
     else{ 
      Toast.makeText(getApplicationContext(), "Enabling Bluetooth FAILED!", Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 

public void displayPairedDevices(){ 
    // If there are paired devices 
    enableBT(); 
    if (pairedDevices.size() > 0) { 
     //Toast.makeText(getApplicationContext(),"in loop",Toast.LENGTH_SHORT).show(); 
     // Loop through paired devices 
     for (BluetoothDevice device : pairedDevices) { 
      // Add the name and address to an array adapter to show in a ListView 
      String s = " "; 
      String deviceName = device.getName(); 
      String deviceAddress = device.getAddress(); 
      pairedDevicesList.add(deviceName + s + deviceAddress +" \n"); 
      //listView.setAdapter(mArrayAdapter); 
      //Toast.makeText(getApplicationContext(), device.getName(),Toast.LENGTH_SHORT).show(); 
     } 


     /* 
     mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,pairedDevicesList); 
     listView.setAdapter(mArrayAdapter);*/ 
    } 
} 

public void displayDetectedDevices(){ 
    mBluetoothAdapter.startDiscovery(); 

    // Create a BroadcastReceiver for ACTION_FOUND 
    mReceiver = new BroadcastReceiver() { 
     @SuppressWarnings("static-access") 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      /* Debugging help 
      Toast.makeText(getApplicationContext(),action,Toast.LENGTH_SHORT).show();*/ 
      // When discovery finds a device 
      if(BluetoothDevice.ACTION_FOUND.equals(action)){ 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       /* Debugging help 
       Toast.makeText(getApplicationContext(),device.getName(),Toast.LENGTH_SHORT).show();*/ 
       String deviceName = device.getName(); 
       String deviceAddress = device.getAddress(); 
       String s = " "; 
       unpairedDevices.add(deviceName + s + deviceAddress +" \n"); 
       //unpairedDevicesList.add(deviceName + s + deviceAddress +" (un-paired)\n"); 
       unpairedDevicesList = new ArrayList<String>(unpairedDevices); 
      } 
     } 
    }; 
    /*adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,unpairedDevicesList); 
    listView.setAdapter(adapter);*/ 
    // Register the BroadcastReceiver  
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
    registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy 
    //Toast.makeText(getApplicationContext(), unpairedDevicesList.toString(), Toast.LENGTH_LONG).show(); 

} 

public void makeDicoverable(int option){ 
    Intent discoverableIntent; 
    if (option == 1){ 
     discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
     discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,120); 
     startActivity(discoverableIntent); 


     Toast.makeText(getApplicationContext(), "Open discovery for 2mins", Toast.LENGTH_SHORT).show(); 
    } else { 
     discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
     discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1); 
     startActivity(discoverableIntent); 
     Toast.makeText(getApplicationContext(), "Open discovery is OFF!", Toast.LENGTH_SHORT).show(); 
    } 
} 
/*Un-used Method 
public void compareAddress(BluetoothDevice checkDevice,String address){ 
    if((checkDevice.getAddress().equals(address))){ 

     selectedDevice = checkDevice; 
    } 

}*/ 

@SuppressLint("NewApi") 
public class ConnectThread extends Thread { 
    private final BluetoothSocket mmSocket; 
    private final BluetoothDevice mmDevice; 
    public ConnectThread(BluetoothDevice device) { 
     // Use a temporary object that is later assigned to mmSocket, 
     // because mmSocket is final 
     BluetoothSocket tmp = null; 

     mmDevice = device; 

     // Get a BluetoothSocket to connect with the given BluetoothDevice 
     try { 
      // MY_UUID is the app's UUID string, also used by the server code 
      tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 
     } catch (IOException e) { } 
     mmSocket = tmp; 
    } 

    public void run() { 
     // Cancel discovery because it will slow down the connection 
     mBluetoothAdapter.cancelDiscovery(); 

     try { 
     // Connect the device through the socket. This will block 
      // until it succeeds or throws an exception 
      mmSocket.connect(); 
     } catch (IOException connectException) { 
      // Unable to connect; close the socket and get out 
      try { 
       mmSocket.close(); 
      } catch (IOException closeException) { 
       Toast.makeText(getApplicationContext(), "Connecting to device failed!", Toast.LENGTH_LONG).show(); 
      } 
       return; 
     } 

      // Do work to manage the connection (in a separate thread) 
      mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget(); 
    } 

    /** Will cancel an in-progress connection, and close the socket */ 
    public void cancel() { 
     try { 
      mmSocket.close(); 
      } catch (IOException e) { } 
    } 

} 
private class ConnectedThread extends Thread { 


    private final BluetoothSocket mmSocket; 
    private final InputStream mmInStream; 
    private final OutputStream mmOutStream; 

    public ConnectedThread(BluetoothSocket socket) { 
     mmSocket = socket; 
     InputStream tmpIn = null; 
     OutputStream tmpOut = null; 

     // Get the input and output streams, using temp objects because 
     // member streams are final 
     try { 
      tmpIn = socket.getInputStream(); 
      tmpOut = socket.getOutputStream(); 
     } catch (IOException e) { } 

     mmInStream = tmpIn; 
     mmOutStream = tmpOut; 
    } 

    public void run() { 
     byte[] buffer; // buffer store for the stream 
     int bytes; // bytes returned from read() 

     // Keep listening to the InputStream until an exception occurs 
     while (true) { 
      try { 
       // Read from the InputStream 
       buffer = new byte[1024]; 
       bytes = mmInStream.read(buffer); 

       // Send the obtained bytes to the UI activity 
       mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget(); 
      } catch (IOException e) { 
       break; 
      } 
     } 
    } 

    /* Call this from the main activity to send data to the remote device */ 
    public void write(byte[] bytes) { 
     try { 
      mmOutStream.write(bytes); 


     } catch (IOException e) { } 
    } 
} 

} 

ответ

0

Если устройство является «Bluetooth в UART преобразователь» модуль, то сделайте петлю обратного соединения на модуле (т.е. короткие TXD RXD с). Отправьте тестовые строки из вашего приложения в модуль и ожидайте получить его обратно. В зависимости от результатов такой проверки ваше приложение и/или модуль могут быть исследованы дальше, чтобы восстановить реальную проблему, если таковая имеется.

Смежные вопросы