Statistiques
| Branche: | Révision:

teotestbluetooth / TestXamConnections / TestXamConnections.Android / Connection / BluetoothConnectionService.cs @ 06a15704

Historique | Voir | Annoter | Télécharger (4,915 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 async Task<bool> Connect(Dictionary<string, string> param)
40
        {
41
            try
42
            {
43
                // Si jamais on est en train de scanner
44
                // On annule le scan
45
                if (bluetoothAdapter.IsDiscovering)
46
                {
47
                    _ = bluetoothAdapter.CancelDiscovery();
48
                }
49

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

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

    
65
                        CancellationTokenSource cts = new CancellationTokenSource();
66

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

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

    
75
                        listeningThread = new Thread(async delagate => await ListeningAsync());
76
                        listeningThread.Start();
77
                    }
78
                } else
79
                {
80
                    // L'addresse MAC n'a pas été spécifiée
81
                    return false;
82
                }
83
            }
84
            catch (Exception)
85
            {
86
                return false;
87
            }
88
            return true;
89
        }
90

    
91
        public EventHandler<byte[]> DataReceivedEvent { get; set; }
92

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

    
122

    
123
        private Task<bool> CloseConnection()
124
        {
125
            while (socket.IsConnected) socket.Close();
126
            return Task.FromResult(true);
127
        }
128

    
129
        public Task<bool> SendCommand(IConvertible command)
130
        {
131
            byte[] hexValues = Encoding.ASCII.GetBytes(command.ToString());
132

    
133
            if (socket.IsConnected == false)
134
            {
135
                return Task.FromResult(false);
136
            }
137
            else
138
            {
139
                // Envoi de la commande
140
                socket.OutputStream.Write(hexValues, 0, hexValues.Length);
141
                socket.OutputStream.Flush();
142
            }
143
            return Task.FromResult(true);
144
        }
145

    
146
        public Task<bool> SendCommand(string command)
147
        {
148
            throw new NotImplementedException();
149
        }
150
    }
151
}