bonjour,
j'écris une appli qui doit se connecter à un module HC-05 relié par sa ligne à un Raspberry. Pour l'instant, le test unitaire doit émettre un string vers le Raspberry qui répond par une autre string.
Je me suis largement inspiré de l'exemple de Brian Wirsing.
Mon code:
Code Java : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //Android supporte le bluetooth? recherche de l'adaptateur bluetooth
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null) {
            //Device does not support bluetooth
            Context context = getApplicationContext();
            CharSequence text = "Device support bluetooth";
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
 
        if(!mBluetoothAdapter.isEnabled()) {
            Context context = getApplicationContext();
            CharSequence text = "BluetoothAdapter is not enable!";
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
            //lancer un Intent pour activer le bluetooth
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
 
        //Discovering devices. Register for broadcasts when a device is discovered.
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        //Enregistrer le broadcast receiver
        registerReceiver(mReceiver, filter);
        //lancer la découverte. Si on découvre, on passe dans le BroadcastReceiver
        mBluetoothAdapter.startDiscovery(); //lance un intent? Android envoie l’intention à tous les BroadCast Receiver abonnées
 
        //Querying paired devices: la requête peut être nulle si aucun appareil n'est appairé
        Set<BluetoothDevice> setpairedDevices = mBluetoothAdapter.getBondedDevices();
        BluetoothDevice[] pairedDevices = (BluetoothDevice[])setpairedDevices.toArray(new BluetoothDevice[setpairedDevices.size()]);
        if (pairedDevices.length > 0) {
            // There are paired devices. Get the name and address of each paired device.
            for(int i=0;i<pairedDevices.length;i++) {
                if (pairedDevices[i].getName().contains("HC-05-AA")) {
                    mDevice = pairedDevices[i];
                }
            }
            Log.d("BONDED TO", mDevice.getName()+" "+mDevice.getAddress());
        }
        else Log.d("QUERYING", "NO BONDED DEVICES");
 
        //A ce niveau, on connaît le device avec lequel on va travailler
        mConnectThread = new ConnectThread(mDevice);
        mConnectThread.start();
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Don't forget to unregister the ACTION_FOUND receiver.
        unregisterReceiver(mReceiver);
    }
 
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
        private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        private String TAG = "Socket";
 
        //constructeur
        public ConnectThread(BluetoothDevice device) {
            BluetoothSocket tmp = null;
            mmDevice = device;
            Method m;
            try {
                m = mDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
                tmp = (BluetoothSocket) m.invoke(mDevice, 1);
            } catch (SecurityException e) {
                Log.e(TAG, "create socket failed", e);
            } catch (NoSuchMethodException e) {
                Log.e(TAG, "create socket failed", e);
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "create socket failed", e);
            } catch (IllegalAccessException e) {
                Log.e(TAG, "create socket failed", e);
            } catch (InvocationTargetException e) {
                Log.e(TAG, "create socket failed", e);
            }
            mmSocket = tmp;
        }
 
        public void run() {
            mBluetoothAdapter.cancelDiscovery();
            try {
                mmSocket.connect();
            } catch (IOException connectException) {
                Log.e("connectException", "Run");
                connectException.printStackTrace();
                try {
                    mmSocket.close();
                } catch (IOException closeException) {
                    Log.e("closeException", "Run");
                    closeException.printStackTrace();
                }
                return;
            }
            mConnectedThread = new ConnectedThread(mmSocket);
            mConnectedThread.start();
        }
 
        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;
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e("ConnectedThread", "Stream");
            }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
 
        public void run() {
            //emettre
            String cmd = new String("Bluetooth --> ");
            write(cmd.getBytes());
        }
        public void write(byte[] bytes) {
            try {
                Log.e("Write", bytes.toString());
                mmOutStream.write(bytes);
                mmOutStream.flush();
            } catch (IOException e) { }
        }
 
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }
Sur mon téléphone, quand je lance ce code, le programme en réception côté PI ne voit rien arriver.
Je ferme et lance Bluetooth Terminal, me connecte au HC-05, entre une chaîne quelconque et appui sur send...
Côté PI je vois s'afficher Bluetooth --> suivi de ce que j'ai entré précédemment.

J'en déduis que le résultat de ma ligne write(cmd.getBytes()); est bufferisé quelque part dans le téléphone et émise par Blutooth Terminal qui s'y prend plus proprement que moi.

Bonne déduction ou mystère plus profond ???

Merci.