Statistiques
| Branche: | Révision:

teotestbluetooth / TestXamConnections / TestXamConnections.Android / Connection / BluetoothConnectionService.cs @ 1fd64302

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

1
using Android.App;
2
using Android.Bluetooth;
3
using Android.Content;
4
using Android.OS;
5
using Android.Runtime;
6
using Android.Views;
7
using Android.Widget;
8
using Java.Util;
9
using System;
10
using System.Collections.Generic;
11
using System.IO;
12
using System.Linq;
13
using System.Text;
14
using System.Threading;
15
using System.Threading.Tasks;
16
using TestXamConnections.Droid.Utils;
17
using TestXamConnections.Models;
18
using TestXamConnections.Connection;
19
using TestXamConnections.Helper;
20

    
21
namespace TestXamConnections.Droid.Connection
22
{
23
    /* Classe permettant d'établir une connection Bluetooth
24
     * Avec socket RFCOMM connecté au SPP
25
     */
26
    public class BluetoothConnectionService : IConnectionService
27
    {
28
        private readonly BluetoothAdapter bluetoothAdapter;
29
        private Thread listeningThread;
30
        private BluetoothSocket socket;
31
        private readonly string sppUUID = "00001101-0000-1000-8000-00805f9b34fb";
32

    
33
        public BluetoothConnectionService()
34
        { 
35
            bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
36
        }
37

    
38
        // Pour le bluetooth, le paramètre de connection est l'addresse MAC
39
        public EventHandler<string> ConnectionFailedEvent { get; set; }
40
        public async Task Connect(Dictionary<string, string> param)
41
        {
42
            try
43
            {
44
                // Si jamais on est en train de scanner
45
                // On annule le scan
46
                if (bluetoothAdapter.IsDiscovering)
47
                {
48
                    bluetoothAdapter.CancelDiscovery();
49
                }
50

    
51
                if (param.ContainsKey(ConnectionConstants.MAC_ADDR_KEY))
52
                {
53
                    BluetoothDevice droidBtDevice = bluetoothAdapter.GetRemoteDevice(param[ConnectionConstants.MAC_ADDR_KEY]);
54
                    if (droidBtDevice != null)
55
                    {
56
                        // Si le socket est occupé pour une autre connexion
57
                        // On ferme la connexion existante
58
                        if (socket != null)
59
                        {
60
                            await CloseConnection();
61
                        }
62

    
63
                        // Creation du canal RFCOMM (non sécurisé)
64
                        socket = droidBtDevice.CreateInsecureRfcommSocketToServiceRecord(UUID.FromString(sppUUID));
65

    
66
                        CancellationTokenSource cts = new CancellationTokenSource();
67

    
68
                        cts.CancelAfter(50000);
69
                        await socket.ConnectAsync().WithCancellation(cts.Token);
70

    
71
                        if (listeningThread != null)
72
                        {
73
                            listeningThread.Abort();
74
                        }
75

    
76
                        listeningThread = new Thread(async delagate => await ListeningAsync());
77
                        listeningThread.Start();
78
                    }
79
                }
80
            }
81
            catch (Exception)
82
            {
83
                Application.SynchronizationContext.Post(_ => { ConnectionFailedEvent.Invoke(this, param[ConnectionConstants.MAC_ADDR_KEY]); }, null);
84
            }
85
        }
86

    
87
        public EventHandler<byte[]> DataReceivedEvent { get; set; }
88

    
89
        // Fonction d'écoute pour le Thread d'écoute
90
        private async Task ListeningAsync()
91
        {
92
            try
93
            {
94
                byte[] buffer = new byte[1024];
95
                while (socket.IsConnected)
96
                {
97
                    int byteAvailable = await socket.InputStream.ReadAsync(buffer, 0, buffer.Length);
98
                    // Resize the byte array 
99
                    byte[] filledBuffer = buffer.Take(byteAvailable).ToArray();
100
                    // Trigger DataReceivedEvent
101
                    Application.SynchronizationContext.Post(_ => { DataReceivedEvent.Invoke(this, filledBuffer); }, null);
102
                }
103
            }
104
            catch (IOException ex)
105
            {
106
                System.Diagnostics.Debug.WriteLine(ex);
107
            }
108
            catch (ThreadAbortException taEx)
109
            {
110
                System.Diagnostics.Debug.WriteLine(taEx);
111
            }
112
            catch (Exception ex)
113
            {
114
                System.Diagnostics.Debug.WriteLine(ex);
115
            }
116
        }
117

    
118

    
119
        private Task<bool> CloseConnection()
120
        {
121
            while (socket.IsConnected) socket.Close();
122
            return Task.FromResult(true);
123
        }
124

    
125
        public Task<bool> SendCommand(byte[] hexValues)
126
        {
127
            if (socket.IsConnected == false)
128
            {
129
                return Task.FromResult(false);
130
            }
131
            else
132
            {
133
                // Envoi de la commande
134
                socket.OutputStream.Write(hexValues, 0, hexValues.Length);
135
                socket.OutputStream.Flush();
136
            }
137
            return Task.FromResult(true);
138
        }
139

    
140
        public Task<bool> SendCommand(string command)
141
        {
142
            throw new NotImplementedException();
143
        }
144
    }
145
}