Partage
  • Partager sur Facebook
  • Partager sur Twitter

Envoie et réception de donnée par Bluetooth HC05

Android Studio

Sujet résolu
    4 juin 2018 à 11:59:10

    Bonjour à tous,

    Je réalise une application Android qui communique par Bluetooth avec un module HC05. En fouillant un peu partout j'ai réussi à bien avancer.

    J'arrive à me connecter à mon module sans problème :) ! Maintenant j'aimerais  envoyer une information, comme un bit que j'enverrais pour faire vibrer un vibreur (perspicace). Seulement je n'arrive pas à réaliser cette commande..

    De même j'aimerais savoir où récupérer une information que le module HC05 m'envoie, ce serait également un bit.

    En plus clair j'aimerais configurer mon canal d'émission et de réception (OutStream / InStream)

    Voici mon code :

    public class Enfant1 extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_enfant1);
    
      ...
            mHandler = new Handler(){
                public void handleMessage(android.os.Message msg){
                    if(msg.what == MESSAGE_READ){
                        String readMessage = null;
                        try {
                            readMessage = new String((byte[]) msg.obj, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        mReadBuffer.setText(readMessage);
                    }
    
                    if(msg.what == CONNECTING_STATUS){
                        if(msg.arg1 == 1)
                            mBluetoothStatus.setText("Connecté à l'appareil : " + (String)(msg.obj));
                        else
                            mBluetoothStatus.setText("Echec de connexion");
                    }
                }
            };
    
            if (mBTArrayAdapter == null) {
                // Device does not support Bluetooth
                mBluetoothStatus.setText("Status: Bluetooth non trouvé");
                Toast.makeText(getApplicationContext(),"Appareil Bluetooth non trouvé!",Toast.LENGTH_SHORT).show();
            }
            else {
    
                mLED1.setOnClickListener(new View.OnClickListener(){...}
                });
    
    
                mScanBtn.setOnClickListener(new View.OnClickListener() {...});
    
                mOffBtn.setOnClickListener(new View.OnClickListener(){...});
    
                mListPairedDevicesBtn.setOnClickListener(new View.OnClickListener() {...});
    
                mDiscoverBtn.setOnClickListener(new View.OnClickListener(){...});
            }
        }
    
        private void bluetoothOn(View view){...}
            else{
                Toast.makeText(getApplicationContext(),"Le Bluetooth est déjà en activé.", Toast.LENGTH_SHORT).show();
            }
        }
    
        // Enter here after user selects "yes" or "no" to enabling radio
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent Data){
            // Check which request we're responding to
            if (requestCode == REQUEST_ENABLE_BT) {
                // Make sure the request was successful
                if (resultCode == RESULT_OK) {
                    // The user picked a contact.
                    // The Intent's data Uri identifies which contact was selected.
                    mBluetoothStatus.setText("Activé");
                }
                else
                    mBluetoothStatus.setText("Désactivé");
            }
        }
    
        private void bluetoothOff(View view){...}
    
        private void discover(View view){...}
    
        final BroadcastReceiver blReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if(BluetoothDevice.ACTION_FOUND.equals(action)){
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    // add the name to the list
                    mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    mBTArrayAdapter.notifyDataSetChanged();
                }
            }
        };
    
        private void listPairedDevices(View view){...}
    
        private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
    
                if(!mBTAdapter.isEnabled()) {
                    Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
                    return;
                }
    
                mBluetoothStatus.setText("Connexion...");
                // Get the device MAC address, which is the last 17 chars in the View
                String info = ((TextView) v).getText().toString();
                final String address = info.substring(info.length() - 17);
                final String name = info.substring(0,info.length() - 17);
    
                // Spawn a new thread to avoid blocking the GUI one
                new Thread()
                {
                    public void run() {
                        boolean fail = false;
    
                        BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
    
                        try {
                            mBTSocket = createBluetoothSocket(device);
                        } catch (IOException e) {
                            fail = true;
                            Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                        }
                        // Establish the Bluetooth socket connection.
                        try {
                            mBTSocket.connect();
                        } catch (IOException e) {
                            try {
                                fail = true;
                                mBTSocket.close();
                                mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
                                        .sendToTarget();
                            } catch (IOException e2) {
                                //insert code to deal with this
                                Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                            }
                        }
                        if(fail == false) {
                            mConnectedThread = new ConnectedThread(mBTSocket);
                            mConnectedThread.start();
    
                            mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
                                    .sendToTarget();
                        }
                    }
                }.start();
            }
        };
    
        private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
            return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
            //creates secure outgoing connection with BT device using UUID
        }
    
        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 = new byte[1024];  // 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
                        bytes = mmInStream.available();
                        if(bytes != 0) {
                            SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
                            bytes = mmInStream.available(); // how many bytes are ready to be read?
                            bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
                            mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                                    .sendToTarget(); // Send the obtained bytes to the UI activity
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
    
                        break;
                    }
                }
            }
    
            /* Call this from the main activity to send data to the remote device */
            public void write(String input) {
                byte[] bytes = input.getBytes();           //converts entered String into bytes
                try {
                    mmOutStream.write(bytes);
                } catch (IOException e) { }
            }
    
            /* Call this from the main activity to shutdown the connection */
            public void cancel() {
                try {
                    mmSocket.close();
                } catch (IOException e) { }
            }
        }
    }
     
    Je pensais que c'était dans mon run() ou peut être dans le write() ? 

    Merci d'avance ! :) 

    -
    Edité par Stafy 5 juin 2018 à 8:56:44

    • Partager sur Facebook
    • Partager sur Twitter
      4 juin 2018 à 14:22:08

      Salut, j’ai aucune idée de la nature de ton problème. Cependant je voudrais faire une petite remarque sur la forme de ta question :

      Les 1000 lignes de codes sans retour a la ligne c’est sur et certain que personne ne vas les lire. Essaie de donner que du code pertinent et lisible. Je doute que ll’ensemble des 1000 lignes aient un rapport avec ton problème. 

      Je comprend que tu veuilles donner le plus d’infos possible mais c’est assez décourageant pour les gens. Fais le tri ;)

      • Partager sur Facebook
      • Partager sur Twitter
        4 juin 2018 à 17:11:05

        Salut Geda, merci du conseil je viens de modifier de ça :) !

        J'espère avoir fait suffisamment le tri

        • Partager sur Facebook
        • Partager sur Twitter
          6 juin 2018 à 8:58:42

          J'ai maintenant réussi à envoyer des données mais je n'arrive juste pas à recevoir de données... personne pour m'aider sur mon OutStream ?
          • Partager sur Facebook
          • Partager sur Twitter

          Envoie et réception de donnée par Bluetooth HC05

          × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
          × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
          • Editeur
          • Markdown