Partage
  • Partager sur Facebook
  • Partager sur Twitter

Connecter 2 périphériques en même temps

Sujet résolu
    21 mai 2021 à 10:41:24

    Bonjour à tous,

    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)

    Voilà mon code:

    MAINACTIVITY.java:

    package com.example.ND_bt_spp;

    import android.Manifest;
    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.content.pm.PackageManager;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Looper;
    import android.os.Message;
    import android.os.SystemClock;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;


    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.math.BigDecimal;
    import java.nio.ByteBuffer;
    import java.nio.ByteOrder;
    import java.nio.charset.StandardCharsets;
    import java.util.Set;
    import java.util.UUID;

    import androidx.annotation.RequiresApi;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;
    import com.example.ND_bt_spp.telemetre;
    import com.example.ND_bt_spp.DynamConnectedThread;

    public class MainActivity extends AppCompatActivity {

    // GUI Components
    private TextView mBluetoothStatus;
    private Button mScanBtn;
    private Button mOffBtn;
    private Button mListPairedDevicesBtn;
    private Button mDiscoverBtn;
    private BluetoothAdapter mBTAdapter;
    private Set<BluetoothDevice> mPairedDevices;
    private ArrayAdapter<String> mBTArrayAdapter;
    private ListView mListePeriph;

    private DynamConnectedThread mHandlerDynam;
    private telemetre mHandlerTelemetre; // Our main handler that will receive callback notifications
    private TelemetreConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data
    private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path

    // #defines for identifying shared types between calling spp_libraries

    private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random" unique identifier

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    Log.i(spp_libraries.TAG, "Activity started !");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mHandlerTelemetre = new telemetre();

    mBluetoothStatus = (TextView) findViewById(R.id.bluetoothStatus);
    telemetre.mValeurTelemetre = (TextView) findViewById(R.id.valeur);
    mScanBtn = (Button) findViewById(R.id.scan);
    mOffBtn = (Button) findViewById(R.id.off);
    mDiscoverBtn = (Button) findViewById(R.id.discover);
    mListPairedDevicesBtn = (Button) findViewById(R.id.PairedBtn);

    mBTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);

    mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio

    mListePeriph = (ListView) findViewById(R.id.devicesListView);
    mListePeriph.setAdapter(mBTArrayAdapter);
    mListePeriph.setOnItemClickListener(mDeviceClickListener);

    // Demande d'autorisation de localisation (si nécessaire)
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);

    if (mBTArrayAdapter == null) {
    // Device does not support Bluetooth
    mBluetoothStatus.setText("Status: Bluetooth not found");
    Toast.makeText(getApplicationContext(), "Bluetooth device not found!", Toast.LENGTH_SHORT).show();
    } else {




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

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

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

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


    }

    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) { }
    }

    class Dynamometre extends Handler{
    public TextView mValeurDynamometre;
    private TextView mBluetoothStatus2;
    private DynamConnectedThread mConnectedThread;

    public Dynamometre(){
    MyApp mApp = (MyApp)MyApp.getContext();
    if(mApp.getCurrentActivity() != null){
    Log.w(spp_libraries.TAG, "Broken");
    }
    mValeurDynamometre = (TextView) mApp.getCurrentActivity().findViewById(R.id.valeur);
    mBluetoothStatus2 = (TextView) mApp.getCurrentActivity().findViewById(R.id.bluetoothStatus);
    }

    public void setmConnectedThread(DynamConnectedThread mConnectedThread) {
    this.mConnectedThread = mConnectedThread; //
    }
    }
    }

    MyApp.java:

    package com.example.ND_bt_spp;

    import android.app.Activity;
    import android.app.Application;
    import android.content.Context;
    import android.os.Bundle;

    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;

    public class MyApp extends Application implements Application.ActivityLifecycleCallbacks {
    private static MyApp instance;
    public Activity mCurrentActivity = null;

    public static MyApp getInstance() {
    return instance;
    }

    public static Context getContext(){
    return instance;
    }

    public Activity getCurrentActivity(){
    return mCurrentActivity;
    }

    @Override
    public void onCreate() {
    instance = this;
    super.onCreate();
    registerActivityLifecycleCallbacks(this);
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
    if(mCurrentActivity != activity){
    mCurrentActivity = activity;
    }
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {
    if(mCurrentActivity != activity){
    mCurrentActivity = activity;
    }
    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
    if(mCurrentActivity != activity){
    mCurrentActivity = activity;
    }
    }

    @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;
    }
    }
    }
    }

    class telemetre extends Handler {

    public static TextView mValeurTelemetre;
    private final TextView mBluetoothStatus;
    private TelemetreConnectedThread mConnectedThread;

    public telemetre(){
    MyApp mApp = (MyApp)MyApp.getContext();
    if(mApp.getCurrentActivity() != null){
    Log.w(spp_libraries.TAG, "Broken");
    }
    mValeurTelemetre = (TextView) mApp.getCurrentActivity().findViewById(R.id.valeur);
    mBluetoothStatus = (TextView) mApp.getCurrentActivity().findViewById(R.id.bluetoothStatus);
    }

    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) {

    byte[] bbarray = (byte[]) msg.obj;
    Float realDistance = .3F;
    String readMessage = new String(spp_libraries.byteArrayToHexString(bbarray));
    if(readMessage.substring(0,4).equalsIgnoreCase("C055")) {
    Log.i(spp_libraries.TAG, "readMessage 01: " + readMessage);
    readMessage = readMessage.substring(14, 22);
    Log.i(spp_libraries.TAG, "readMessage 02: " + readMessage);
    int i = spp_libraries.swapEndian(readMessage);
    Float f = Float.intBitsToFloat(i);
    realDistance = f;
    }

    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");
    }
    }
    }

    activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ND_bt_spp.MainActivity">


    <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_marginTop="10dp"
    android:layout_height="wrap_content">
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.1"
    android:text="Valeur mesurée:"
    android:ellipsize="end"
    android:maxLines="1"
    android:textStyle="bold" />
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.9"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="..."
    android:id="@+id/valeur"
    android:layout_centerHorizontal="true" />
    </LinearLayout>

    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.1"
    android:text="Status:"
    android:ellipsize="end"
    android:maxLines="1"
    android:textStyle="bold" />
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.9"
    android:text="Bluetooth Status"
    android:id="@+id/bluetoothStatus"
    android:ellipsize="end"
    android:maxLines="1"
    android:layout_centerHorizontal="true"/>
    </LinearLayout>

    <Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Bluetooth ON"
    android:id="@+id/scan"
    android:layout_centerVertical="true"
    android:layout_toStartOf="@+id/off" />

    <Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Bluetooth OFF"
    android:id="@+id/off"
    android:layout_alignBottom="@+id/scan"
    android:layout_toEndOf="@+id/PairedBtn"
    android:layout_toRightOf="@+id/PairedBtn" />

    <Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Show paired Devices"
    android:id="@+id/PairedBtn"
    android:layout_below="@+id/scan"
    android:layout_toStartOf="@+id/discover" />

    <Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Discover New Devices"
    android:id="@+id/discover"
    android:layout_below="@+id/off"
    android:layout_toRightOf="@+id/checkboxLED1"
    android:layout_toEndOf="@+id/checkboxLED1" />

    <ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/devicesListView"
    android:choiceMode="singleChoice"
    android:layout_below="@+id/PairedBtn"
    android:layout_alignRight="@+id/off"
    android:layout_alignEnd="@+id/off" />

    </LinearLayout>

    </RelativeLayout>

    Pouvez-vous m'aider à finir mon code ?

    -
    Edité par NathanDEJONGHE 21 mai 2021 à 10:43:47

    • Partager sur Facebook
    • Partager sur Twitter
      1 juin 2021 à 18:41:50

      Merci pour ce manque de soutien...
      • Partager sur Facebook
      • Partager sur Twitter

      Connecter 2 périphériques en même temps

      × 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