Statistiques
| Branche: | Révision:

teotestbluetooth / TestTeoBluetooth / TestTeoBluetooth.Android / Connection / BluetoothConnectionService.cs @ d14bc0b1

Historique | Voir | Annoter | Télécharger (4,305 ko)

1 58c56df1 Martin Toutant
using Android.App;
2 0875d625 Martin Toutant
using Android.Bluetooth;
3 58c56df1 Martin Toutant
using Android.Content;
4
using Android.OS;
5
using Android.Runtime;
6
using Android.Views;
7
using Android.Widget;
8 0875d625 Martin Toutant
using Java.Util;
9 58c56df1 Martin Toutant
using System;
10
using System.Collections.Generic;
11 0875d625 Martin Toutant
using System.IO;
12 58c56df1 Martin Toutant
using System.Linq;
13
using System.Text;
14 0875d625 Martin Toutant
using System.Threading;
15
using System.Threading.Tasks;
16 91ef3e8c Martin Toutant
using TestXamConnections.Droid.Utils;
17
using TestXamConnections.Models;
18
using TestXamConnections.Connection;
19 58c56df1 Martin Toutant
20 91ef3e8c Martin Toutant
namespace TestXamConnections.Droid.Connection
21 58c56df1 Martin Toutant
{
22
    /* Classe permettant d'établir une connection Bluetooth
23
     * Avec socket RFCOMM connecté au SPP
24
     */
25 91ef3e8c Martin Toutant
    public class BluetoothConnectionService : IConnectionService
26 58c56df1 Martin Toutant
    {
27 0875d625 Martin Toutant
        private readonly BluetoothAdapter bluetoothAdapter;
28
        private Thread listeningThread;
29
        private BluetoothSocket socket;
30
        private readonly string sppUUID = "00001101-0000-1000-8000-00805f9b34fb";
31
32 91ef3e8c Martin Toutant
        public BluetoothConnectionService()
33 0875d625 Martin Toutant
        { 
34
            bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
35
        }
36 91ef3e8c Martin Toutant
37 0875d625 Martin Toutant
        public async Task<bool> Connect(Device btDevice)
38
        {
39
            try
40
            {
41
                // Si jamais on est en train de scanner
42
                // On annule le scan
43
                if (bluetoothAdapter.IsDiscovering)
44
                {
45
                    bluetoothAdapter.CancelDiscovery();
46
                }
47
48
                BluetoothDevice droidBtDevice = bluetoothAdapter.GetRemoteDevice(btDevice.MACAddress);
49
                if (droidBtDevice != null)
50
                {
51
                    // Si le socket est occupé pour une autre connexion
52
                    // On ferme la connexion existante
53
                    if (socket != null)
54
                    {
55
                        await CloseConnection();
56
                    }
57
58
                    // Creation du canal RFCOMM (non sécurisé)
59
                    socket = droidBtDevice.CreateInsecureRfcommSocketToServiceRecord(UUID.FromString(sppUUID));
60
61
                    CancellationTokenSource cts = new CancellationTokenSource();
62
63
                    cts.CancelAfter(50000);
64
                    await socket.ConnectAsync().WithCancellation(cts.Token);
65
66 d14bc0b1 Martin Toutant
                    if (listeningThread != null)
67
                    {
68
                        listeningThread.Abort();
69
                    }
70
71 0875d625 Martin Toutant
                    listeningThread = new Thread(async delagate => await ListeningAsync());
72
                    listeningThread.Start();
73
74
                    return true;
75
                }
76
            }
77
            catch (Exception ex)
78
            {
79
                System.Diagnostics.Debug.WriteLine(ex);
80
            }
81
82
            return false;
83
        }
84
85 d14bc0b1 Martin Toutant
        public EventHandler<byte[]> DataReceivedEvent { get; set; }
86
87 0875d625 Martin Toutant
        // Fonction d'écoute pour le Thread d'écoute
88
        private async Task ListeningAsync()
89
        {
90
            try
91
            {
92
                byte[] buffer = new byte[1024];
93
                while (socket.IsConnected)
94
                {
95
                    int byteAvailable = await socket.InputStream.ReadAsync(buffer, 0, buffer.Length);
96
                    // Resize the byte array 
97
                    byte[] filledBuffer = buffer.Take(byteAvailable).ToArray();
98 d14bc0b1 Martin Toutant
                    // Trigger DataReceivedEvent
99
                    Application.SynchronizationContext.Post(_ => { DataReceivedEvent.Invoke(this, filledBuffer); }, null);
100 0875d625 Martin Toutant
                }
101
            }
102
            catch (IOException ex)
103
            {
104
                System.Diagnostics.Debug.WriteLine(ex);
105
            }
106
            catch (ThreadAbortException taEx)
107
            {
108
                System.Diagnostics.Debug.WriteLine(taEx);
109
            }
110
            catch (Exception ex)
111
            {
112
                System.Diagnostics.Debug.WriteLine(ex);
113
            }
114
        }
115
116
117
        private Task<bool> CloseConnection()
118
        {
119
            while (socket.IsConnected) socket.Close();
120
            return Task.FromResult(true);
121
        }
122
123
        public Task<bool> SendCommand(byte[] hexValues)
124
        {
125
            if (socket.IsConnected == false)
126
            {
127
                return Task.FromResult(false);
128
            }
129
            else
130
            {
131
                // Envoi de la commande
132
                socket.OutputStream.Write(hexValues, 0, hexValues.Length);
133
                socket.OutputStream.Flush();
134
            }
135
            return Task.FromResult(true);
136
        }
137
138 58c56df1 Martin Toutant
    }
139
}