Je dois faire un projet pour mon BTS où en gros je dois connecter un télémètre et un dynamomètre au téléphone en même temps. Le problème c'est que je bloque depuis plus de 2 semaines et que je dois rendre le projet dans une semaine. J'ai besoin de votre aide parce que je suis extrêmement nul en programmation JAVA ! (je fais un projet qui ne me servira même pas dans le domaine professionnel où je souhaite travailler)
private void bluetoothOn(View view) { Log.i(spp_libraries.TAG, "Bluetooth ON : "); if (!mBTAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, spp_libraries.REQUEST_ENABLE_BT); mBluetoothStatus.setText("Bluetooth enabled"); Toast.makeText(getApplicationContext(), "Bluetooth turned on", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Bluetooth is already on", 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) { Log.i(spp_libraries.TAG, "Enter Activity for Result"); // Check which request we're responding to super.onActivityResult(requestCode, resultCode, Data); if (requestCode == spp_libraries.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("Enabled"); Toast.makeText(getApplicationContext(), "Yes 4 BT", Toast.LENGTH_SHORT).show(); } else { mBluetoothStatus.setText("Disabled"); Toast.makeText(getApplicationContext(), "No 2 BT", Toast.LENGTH_SHORT).show(); } } }
//Désactivation Bluetooth private void bluetoothOff(View view) { Log.i(spp_libraries.TAG, "Bluetooth OFF : "); mBTAdapter.disable(); // turn off mBluetoothStatus.setText("Bluetooth disabled"); Toast.makeText(getApplicationContext(), "Bluetooth turned Off", Toast.LENGTH_SHORT).show(); }
//Détection de nouveaux phériphériques private void discover(View view) { // Vérification si périphérique est déjà découvert if (mBTAdapter.isDiscovering()) { mBTAdapter.cancelDiscovery(); Toast.makeText(getApplicationContext(), "Discovery stopped", Toast.LENGTH_SHORT).show(); } else { if (mBTAdapter.isEnabled()) { mBTArrayAdapter.clear(); // clear items mBTAdapter.startDiscovery(); Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show(); registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); } else { Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show(); } } }
// Réception du nom du périphérique et son adresse MAC final BroadcastReceiver blReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(spp_libraries.TAG, "Enter Broadcast Receiver"); String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // add the name to the list Log.i(spp_libraries.TAG, "Device name & Adresse " + device.getName() + device.getAddress()); mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress()); mBTArrayAdapter.notifyDataSetChanged(); } } }; // Liste des périphériques appairés private void listPairedDevices(View view) { mPairedDevices = mBTAdapter.getBondedDevices(); if (mBTAdapter.isEnabled()) { // put it's one to the adapter for (BluetoothDevice device : mPairedDevices) mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress()); Toast.makeText(getApplicationContext(), "Show Paired Devices", Toast.LENGTH_SHORT).show(); } else Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show(); }
// Connexion au périphérique choisit dans la liste des nouveaux périphériques découverts private final 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("Connecting..."); // 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(); mHandlerTelemetre.obtainMessage(spp_libraries.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 TelemetreConnectedThread(mBTSocket, mHandlerTelemetre); mConnectedThread.start(); mHandlerTelemetre.obtainMessage(spp_libraries.CONNECTING_STATUS, 1, -1, name) .sendToTarget(); } } }.start(); } }; private final AdapterView.OnItemClickListener mDeviceClickListener2 = 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("Connecting..."); // 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(); mHandlerTelemetre.obtainMessage(spp_libraries.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 DynamConnectedThread(mBTSocket, mHandlerDynam); mConnectedThread.start(); mHandlerTelemetre.obtainMessage(spp_libraries.CONNECTING_STATUS, 1, -1, name) .sendToTarget(); } } }.start(); } }; // Etablit une connexion RFCOMM en bluetooth private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException { Log.i(spp_libraries.TAG, "Create Bluetooth Socket " + BTMODULEUUID); return device.createRfcommSocketToServiceRecord(BTMODULEUUID); } }
DynamConnectedThread.java:
package com.example.ND_bt_spp; import android.bluetooth.BluetoothSocket; import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import android.util.Log; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class DynamConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; private final DynamConnectedThread mHandlerDynam; public DynamConnectedThread(@org.jetbrains.annotations.NotNull BluetoothSocket socket, DynamConnectedThread mHandlerDynam) { Looper.prepare(); mmSocket = socket; this.mHandlerDynam = mHandlerDynam; this.mHandlerDynam.setmConnectedThreadDynam(this); 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; }
@Override 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) { buffer = new byte[30]; 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 mHandlerDynam.obtainMessage(spp_libraries.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) { } }
@Override public void onActivityPaused(@NonNull Activity activity) {
}
@Override public void onActivityStopped(@NonNull Activity activity) {
}
@Override public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
}
@Override public void onActivityDestroyed(@NonNull Activity activity) {
} }
spp_libraries.java:
package com.example.ND_bt_spp; import android.os.Build; import androidx.annotation.RequiresApi; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class spp_libraries {
public final static int REQUEST_ENABLE_BT = 1; // utilisé pour identifier l'ajout de noms bluetooth public final static int CONNECTING_STATUS = 3; // public final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update public final static String TAG = "ND_BT_SPP"; final protected static char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; // Conversion caractères héxadécimal en string public static String byteArrayToHexString(byte[] bytes) { char[] hexChars = new char[bytes.length*2]; int v; for(int j=0; j < bytes.length; j++) { v = bytes[j] & 0xFF; hexChars[j*2] = hexArray[v>>>4]; hexChars[j*2 + 1] = hexArray[v & 0x0F]; }
return new String(hexChars); }
// Méthode Little Endian (invertion des caractères hexadécimal) @RequiresApi(api = Build.VERSION_CODES.O) public static int swapEndian(String hex){ int value = Integer.parseUnsignedInt(hex, 16); ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(ByteOrder.BIG_ENDIAN); buffer.asIntBuffer().put(value); buffer.order(ByteOrder.LITTLE_ENDIAN); int flipped = buffer.asIntBuffer().get(); return flipped; }
// Méthode pour réduire le nombre de chiffre significatif public static float round(float d, int decimalPlace) { BigDecimal bd = new BigDecimal(Float.toString(d)); bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP); return bd.floatValue(); }
}
TelemetreConnectedThread.java:
package com.example.ND_bt_spp; import android.bluetooth.BluetoothSocket; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.SystemClock; import android.util.Log; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class TelemetreConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; private telemetre btTelemetre; // Connexion au télémètre à l'aide de la classe BluetoothSocket public TelemetreConnectedThread(@org.jetbrains.annotations.NotNull BluetoothSocket socket, telemetre btTelemetre) { Looper.prepare(); this.btTelemetre = btTelemetre; this.btTelemetre.setmConnectedThread(this); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Obtention les flux d'entrée et de sortie à l'aide d'objets temporaires try { tmpIn = socket.getInputStream(); Log.i(spp_libraries.TAG, "Input Stream OK " + tmpIn); Log.i(spp_libraries.TAG, "Input Stream socket.getConnectionType() " + socket.getConnectionType()); Log.i(spp_libraries.TAG, "Input Stream socket.getRemoteDevice() " + socket.getRemoteDevice()); Log.i(spp_libraries.TAG, "Input Stream socket.isConnected() " + socket.isConnected()); Log.i(spp_libraries.TAG, "Input Stream socket.getMaxReceivePacketSize() " + socket.getMaxReceivePacketSize()); } catch (IOException e) { Log.e(spp_libraries.TAG, "Error occurred when creating input stream", e); } try { tmpOut = socket.getOutputStream(); Log.i(spp_libraries.TAG, "Output Stream OK " + tmpOut); } catch (IOException e) { Log.e(spp_libraries.TAG, "Error occurred when creating output stream", e); }
mmInStream = tmpIn; mmOutStream = tmpOut; }
public telemetre getBtTelemetre() { return btTelemetre; }
public void write(String input) { byte[] bytes = input.getBytes(); // Convertit la chaine en octets try { mmOutStream.write(bytes); } catch (IOException e) { Log.e(spp_libraries.TAG, "Error occurred when sending data", e); } }
// Permet de convertir en hexa public void writeHex(char[] test) { try { Log.i(spp_libraries.TAG, "Write to bT " + test); for(int k=0; k < test.length; k++){ new DataOutputStream(mmOutStream).write(test[k]); } } catch (IOException e) { Log.e(spp_libraries.TAG, "Error occurred when sending data", e); } }
// Annulation de la communication entre les périphériques public void cancel() { try { mmSocket.close(); } catch (IOException e) { } }
@Override public void run() { super.run(); byte[] buffer = new byte[22]; // mémoire tampon pour le flux int bytes; // Ecoute InputStream jusqu'à ce qu'une exception se produise while (true) { try { // Read from the InputStream bytes = mmInStream.available(); // Log.i(TAG, "Thread mConnectedThread run & num bytes" + bytes); if (bytes != 0) { SystemClock.sleep(100); //pause and wait for rest of data bytes = mmInStream.available(); // how many bytes are ready to be read? bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read Log.i(spp_libraries.TAG, "Input Stream Receive msg !" + buffer); Log.i(spp_libraries.TAG, "Input Stream Receive msg length!" + bytes); String tmp = spp_libraries.byteArrayToHexString(buffer); Log.i(spp_libraries.TAG, "Input Stream Receive msg in String " + tmp); btTelemetre.obtainMessage(spp_libraries.MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); // Send the obtained bytes to the UI activity } } catch (IOException e) { e.printStackTrace(); break; } } } }
public void setmConnectedThread(TelemetreConnectedThread mConnectedThread) { this.mConnectedThread = mConnectedThread; // }
// Découpage de la trame reçu par le télémètre (sélection des bits 14 à 22) @RequiresApi(api = Build.VERSION_CODES.O) @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); Log.i(spp_libraries.TAG, "Enter handleMessage"); if (msg.what == spp_libraries.MESSAGE_READ) {
realDistance = spp_libraries.round(realDistance, 3); Log.i(spp_libraries.TAG, "Distance : " + realDistance + " m"); mValeurTelemetre.setText(String.valueOf(realDistance + " m")); // affichage de la valeur en décimal }
if (msg.what == spp_libraries.CONNECTING_STATUS) { Log.i(spp_libraries.TAG, "msg.what " + msg.what); if (msg.arg1 == 1) mBluetoothStatus.setText("Connected to Device: " + (String) (msg.obj)); char[] data = { 0xC0, 0x55, 0x02, 0x01,0x00,0x1a}; // Commande en héxa du télémètre pour faire une mesure if (mConnectedThread != null) { //Vérif si thread est créé mConnectedThread.writeHex(data); } else mBluetoothStatus.setText("Connection Failed"); } } }
× 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.