Révision be694ed4

Voir les différences:

TestXamConnections/TestXamConnections.Android/Connection/BluetoothConnectionService.cs
31 31
        private readonly string sppUUID = "00001101-0000-1000-8000-00805f9b34fb";
32 32

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

  
38 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)
39
        public async Task<bool> Connect(Dictionary<string, string> param)
41 40
        {
42 41
            try
43 42
            {
......
45 44
                // On annule le scan
46 45
                if (bluetoothAdapter.IsDiscovering)
47 46
                {
48
                    bluetoothAdapter.CancelDiscovery();
47
                    _ = bluetoothAdapter.CancelDiscovery();
49 48
                }
50 49

  
51 50
                if (param.ContainsKey(ConnectionConstants.MAC_ADDR_KEY))
......
57 56
                        // On ferme la connexion existante
58 57
                        if (socket != null)
59 58
                        {
60
                            await CloseConnection();
59
                            _ = await CloseConnection();
61 60
                        }
62 61

  
63 62
                        // Creation du canal RFCOMM (non sécurisé)
......
76 75
                        listeningThread = new Thread(async delagate => await ListeningAsync());
77 76
                        listeningThread.Start();
78 77
                    }
78
                } else
79
                {
80
                    // L'addresse MAC n'a pas été spécifiée
81
                    return false;
79 82
                }
80 83
            }
81 84
            catch (Exception)
82 85
            {
83
                Application.SynchronizationContext.Post(_ => { ConnectionFailedEvent.Invoke(this, param[ConnectionConstants.MAC_ADDR_KEY]); }, null);
86
                return false;
84 87
            }
88
            return true;
85 89
        }
86 90

  
87 91
        public EventHandler<byte[]> DataReceivedEvent { get; set; }
TestXamConnections/TestXamConnections.Android/Connection/InternConnectionService.cs
23 23
    public class InternConnectionService : IConnectionService
24 24
    {
25 25
        public EventHandler<byte[]> DataReceivedEvent { get; set; }
26
        public EventHandler<string> ConnectionFailedEvent { get; set; }
27 26

  
28 27
        private readonly IntentReceiver intentReceiver;
29 28
        private readonly Context appContext;
......
31 30
        /* La fonction connect dans le cas du connexion en interne
32 31
        *  Est en fait, la configuration de l'IntentReceiver
33 32
        */
34
        public async Task Connect(Dictionary<string, string> param)
33
        public Task<bool> Connect(Dictionary<string, string> param)
35 34
        {
36 35
            if (param.ContainsKey(ConnectionConstants.RECEIVABLE_INTENTS_KEY))
37 36
            {
......
42 41
                IntentFilter intentFilter = new IntentFilter();
43 42
                intents.ForEach(intent => intentFilter.AddAction(intent));
44 43

  
45
                await Task.Run( () => appContext.RegisterReceiver(intentReceiver, intentFilter) );
44
                appContext.RegisterReceiver(intentReceiver, intentFilter);
46 45
            }
47 46
            else
48 47
            {
49
                ConnectionFailedEvent.Invoke(this, null);
48
                return Task.FromResult(false);
50 49
            }
51
            return;
50
            return Task.FromResult(true);
52 51
        }
53 52

  
54 53
        public Task<bool> SendCommand(string command)
......
80 79
                    break;
81 80

  
82 81
                case AgridentConstants.ACTION_AGRIDENT_ERROR:
83
                    DataReceivedEvent.Invoke(this, Encoding.ASCII.GetBytes("ERROR"));
82
                    DataReceivedEvent.Invoke(this, Encoding.ASCII.GetBytes(AgridentConstants.ACTION_AGRIDENT_ERROR));
83
                    break;
84

  
85
                case AgridentConstants.ACTION_AGRIDENT_SERVICE_START:
86
                    DataReceivedEvent.Invoke(this, Encoding.ASCII.GetBytes(AgridentConstants.ACTION_AGRIDENT_SERVICE_START));
87
                    break;
88

  
89
                case AgridentConstants.ACTION_AGRIDENT_SERVICE_STOP:
90
                    DataReceivedEvent.Invoke(this, Encoding.ASCII.GetBytes(AgridentConstants.ACTION_AGRIDENT_SERVICE_STOP));
84 91
                    break;
85 92

  
86 93
                default:
TestXamConnections/TestXamConnections.Android/Connection/WifiConnectionService.cs
20 20
    public class WifiConnectionService : IConnectionService
21 21
    {
22 22
        public EventHandler<byte[]> DataReceivedEvent { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
23
        public EventHandler<string> ConnectionFailedEvent { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
24 23

  
25
        public Task<bool> SendCommand(byte[] hexValues)
24
        public Task<bool> Connect(Dictionary<string, string> connectParam)
26 25
        {
27 26
            throw new NotImplementedException();
28 27
        }
29 28

  
30
        public Task<bool> SendCommand(string command)
29
        public Task<bool> SendCommand(byte[] hexValues)
31 30
        {
32 31
            throw new NotImplementedException();
33 32
        }
34 33

  
35
        public Task Connect(Dictionary<string, string> connectParam)
34
        public Task<bool> SendCommand(string command)
36 35
        {
37 36
            throw new NotImplementedException();
38 37
        }
TestXamConnections/TestXamConnections.Android/Receivers/IntentReceiver.cs
18 18

  
19 19
        public override void OnReceive(Context context, Intent intent)
20 20
        {
21
            OnIntentReceived(this, intent);
21
            OnIntentReceived.Invoke(this, intent);
22 22
        }
23 23
    }
24 24
}
TestXamConnections/TestXamConnections/Connection/IConnectionService.cs
16 16
         * --> Ajout à un IntentFilter
17 17
         * Déclenche ConnectionFailedEvent si la connection échoue
18 18
         */
19
        Task Connect(Dictionary<string, string> connectParam);
19
        Task<bool> Connect(Dictionary<string, string> connectParam);
20 20

  
21 21
        /*
22 22
         * Fonction d'envoi de commande
......
31 31
         * Renvoi les données sur forme d'un tableau d'octets
32 32
         */
33 33
        EventHandler<byte[]> DataReceivedEvent { get; set; }
34

  
35
        /* Evenement déclenché quand la connexion échoue
36
         */
37
        EventHandler<string> ConnectionFailedEvent { get; set; }
38 34
    }
39 35
}
TestXamConnections/TestXamConnections/Models/AgridentReader.cs
23 23
    {
24 24
        private IConnectionService ConnectionService { get; set; }
25 25
        public EventHandler<string> AgridentDataReceivedEvent { get; set; }
26
        public EventHandler<string> AgridentNORFIDEvent { get; set; }
27
        public EventHandler AgridentConnectionFailedEvent { get; set; }
26
        public EventHandler AgridentNORFIDEvent { get; set; }
27
        public EventHandler<bool> AgridentScanStatusChangedEvent { get; set; }
28 28

  
29 29
        public AgridentReader()
30 30
        {
31 31
            ConnectionService = DependencyService.Get<IConnectionServiceProvider>().GetConnectionInstance(ConnectionType.Intern);
32
            ConnectionService.DataReceivedEvent += (s, args) => InternDataReceived(args);
33
            ConnectionService.ConnectionFailedEvent += AgridentConnectionFailed;
32
            ConnectionService.DataReceivedEvent += InternDataReceived;
34 33
        }
35 34

  
36 35
        ~AgridentReader()
37 36
        {
38
            ConnectionService.DataReceivedEvent -= (s, args) => InternDataReceived(args);
39
            ConnectionService.ConnectionFailedEvent += AgridentConnectionFailed;
40
        }
41

  
42
        /* Fonction déclenchée à l'échec de la connexion
43
         */
44
        private void AgridentConnectionFailed(object sender, string e)
45
        {
46
            AgridentConnectionFailedEvent.Invoke(this, null);
37
            ConnectionService.DataReceivedEvent -= InternDataReceived;
47 38
        }
48 39

  
49 40
        /* Fonction déclenchée à la reception de données Agrident
50 41
         * Trigger l'évènement AgridentDataReceivedEvent
51 42
         */
52
        private void InternDataReceived(byte[] intent)
43
        private void InternDataReceived(object sender, byte[] intent)
53 44
        {
54 45
            string data = Encoding.ASCII.GetString(intent);
55
            // Si pas de valeur scannée
56
            // Evenement error
57
            if (data.Equals("ERROR"))
58
            {
59
                AgridentNORFIDEvent.Invoke(this, null);
60
            } 
61
            // Sinon c'est une valeur rfid -- NON, TODO
62
            else
46

  
47
            switch (data)
63 48
            {
64
                AgridentDataReceivedEvent.Invoke(this, data);
49
                case AgridentConstants.ACTION_AGRIDENT_ERROR:
50
                    AgridentNORFIDEvent.Invoke(this, null);
51
                    break;
52

  
53
                case AgridentConstants.ACTION_AGRIDENT_SERVICE_START:
54
                    AgridentScanStatusChangedEvent.Invoke(this, true);
55
                    break;
56

  
57
                case AgridentConstants.ACTION_AGRIDENT_SERVICE_STOP:
58
                    AgridentScanStatusChangedEvent.Invoke(this, false);
59
                    break;
60

  
61
                default:
62
                    AgridentDataReceivedEvent.Invoke(this, data);
63
                    break;
65 64
            }
66 65
        }
67 66

  
68 67
        public async Task<bool> EnableServiceAsync()
69 68
        {
69
            bool ret;
70 70
            // Enregistrement des intents recevable par Agrident
71 71
            List<string> intentsList = new List<string>()
72 72
            {
73 73
                AgridentConstants.ACTION_AGRIDENT_SUCCESS,
74
                AgridentConstants.ACTION_AGRIDENT_ERROR
74
                AgridentConstants.ACTION_AGRIDENT_ERROR,
75
                AgridentConstants.ACTION_AGRIDENT_SERVICE_START,
76
                AgridentConstants.ACTION_AGRIDENT_SERVICE_STOP
75 77
            };
76 78
            string intents = string.Join(',', intentsList);
77 79

  
......
81 83
                { ConnectionConstants.RECEIVABLE_INTENTS_KEY, intents }
82 84
            };
83 85

  
84
            await ConnectionService.Connect(param);
85
            return true;
86
            ret = await ConnectionService.Connect(param);
87
            return ret;
86 88
        }
87 89

  
88 90
        public async Task<bool> StartScanAsync()
TestXamConnections/TestXamConnections/Models/TeoBalance.cs
33 33
        private IConnectionService ConnectionService { get; set; }
34 34
        public EventHandler<string> TeoDataReceivedEvent { get; set; }
35 35
        public EventHandler<ReponsePesee> TeoPeseeReceivedEvent { get; set; }
36
        public EventHandler TeoConnectionFailedEvent { get; set; }
37 36

  
38 37
        public TeoBalance(Device device)
39 38
        {
40 39
            Name = device.Name;
41 40
            MACAddress = device.MACAddress;
42 41
            ConnectionService = DependencyService.Get<IConnectionServiceProvider>().GetConnectionInstance(ConnectionType.Bluetooth);
43
            ConnectionService.DataReceivedEvent += (s, args) => TeoDataReceived(args);
44
            ConnectionService.ConnectionFailedEvent += TeoConnectionFailed;
42
            ConnectionService.DataReceivedEvent += TeoDataReceived;
45 43
        }
46 44

  
47 45
        ~TeoBalance()
48 46
        {
49
            ConnectionService.DataReceivedEvent -= (s, args) => TeoDataReceived(args);
50
            ConnectionService.ConnectionFailedEvent -= TeoConnectionFailed;
47
            ConnectionService.DataReceivedEvent -= TeoDataReceived;
51 48
        }
52 49

  
53 50
        /* 
......
59 56
         * nommé _bufferedData
60 57
         */
61 58
        private string _bufferedData;
62
        
63
        // Fonction appelée si la connexion échoue
64
        private void TeoConnectionFailed(object sender, string e)
65
        {
66
            TeoConnectionFailedEvent.Invoke(this, null) ;
67
        }
68 59

  
69 60
        // Fonction appelée lors de la reception de données par le ConnectionService
70
        private void TeoDataReceived(byte[] buffer)
61
        private void TeoDataReceived(object sender, byte[] buffer)
71 62
        {
72 63
            // Si le premier character est 2 (ASCII: STX)
73 64
            // Alors c'est le début de la trame.
TestXamConnections/TestXamConnections/ViewModels/InternServiceViewModel.cs
10 10
{
11 11
    public class InternServiceViewModel : ViewModelBase
12 12
    {
13
        private bool isScanning;
13 14
        private bool showRFID;
14 15
        private bool showError;
15 16
        private readonly AgridentReader agridentReader;
......
28 29
            set { SetProperty( ref showError, value); }
29 30
        }
30 31

  
32
        public bool IsScanning
33
        {
34
            get { return isScanning; }
35
            set { SetProperty(ref isScanning, value); }
36
        }
37

  
31 38
        public string RFIDResult
32 39
        {
33 40
            get { return rfidResult; }
......
42 49

  
43 50
        private async Task StartScan()
44 51
        {
45
            ShowError = false;
46
            ShowRFID = false;
52
            IsScanning = true;
47 53
            if (await agridentReader.StartScanAsync() == false)
48 54
            {
49 55
                ShowError = true;
......
62 68
            agridentReader = new AgridentReader();
63 69
            agridentReader.AgridentDataReceivedEvent += OnRFIDResultReceived;
64 70
            agridentReader.AgridentNORFIDEvent += OnNoRFIDReceived;
65
            agridentReader.EnableServiceAsync().Wait();
71
            agridentReader.AgridentScanStatusChangedEvent += OnScanStatusChanged;
72
            bool err = agridentReader.EnableServiceAsync().Result;
66 73
            StartScanCommand = new Command(async () => await StartScan());
67 74
        }
68 75

  
69
        private void OnNoRFIDReceived(object sender, string e)
76
        private void OnScanStatusChanged(object sender, bool e)
77
        {
78
            IsScanning = e;
79
            if (e == false)
80
            {
81
                ShowError = true;
82
                ShowRFID = true;
83
            }
84
        }
85

  
86
        private void OnNoRFIDReceived(object sender, EventArgs e)
70 87
        {
71 88
            ShowError = true;
72 89
            ErrorMessage = "Pas de TAG RFID detecté";
90
            IsScanning = false;
73 91
        }
74 92

  
75 93
        private void OnRFIDResultReceived(object sender, string e)
76 94
        {
77 95
            ShowRFID = true;
78 96
            RFIDResult = e;
97
            IsScanning = false;
79 98
        }
80 99
    }
81 100
}
TestXamConnections/TestXamConnections/ViewModels/TeoDeviceViewModel.cs
83 83
            IsVisibleData = false;
84 84
            ConnectToDeviceCommand = new Command(async () => await ConnectToDevice());
85 85
            SendValueCommand = new Command(async (cmd) => await teoScale.SendTeoCommandAsync((TeoCommandType)cmd));
86
            TeoScale.TeoDataReceivedEvent = (s, args) => DataReceived(args);
87
            TeoScale.TeoPeseeReceivedEvent = (s, args) => PeseeReceived(args);
88
            TeoScale.TeoConnectionFailedEvent = ConnectionFailed;
86
            TeoScale.TeoDataReceivedEvent = DataReceived;
87
            TeoScale.TeoPeseeReceivedEvent = PeseeReceived;
89 88

  
90 89
            // Ajout manuel des commandes
91 90
            AvailableCommandsList = new ObservableCollection<CommandItemViewModel>();
......
95 94
            }
96 95
        }
97 96

  
98
        private void ConnectionFailed(object sender, EventArgs e)
99
        {
100
            IsConnected = false;
101
            ShowError = true;
102
            ErrorMessage = "La connexion a échoué";
103
        }
104

  
105
        public void DataReceived(string args)
97
        public void DataReceived(object sender, string args)
106 98
        {
107 99
            IsVisibleData = true;
108 100
            Data += args.Trim() + "\n";
109 101
        }
110 102

  
111
        public void PeseeReceived(ReponsePesee args)
103
        public void PeseeReceived(object sender, ReponsePesee args)
112 104
        {
113 105
            Data = args.PoidsMesure;
114 106
        }
TestXamConnections/TestXamConnections/Views/InternServiceView.xaml
7 7
    <ContentPage.Content>
8 8

  
9 9
        <StackLayout BackgroundColor="#001729" VerticalOptions="FillAndExpand">
10
            <StackLayout Spacing="15" VerticalOptions="CenterAndExpand">
10
            <Grid VerticalOptions="FillAndExpand">
11
                <StackLayout Spacing="15" VerticalOptions="CenterAndExpand">
11 12

  
12
                <xe:BorderView
13
                    Margin="0,20,0,0"
14
                    xe:Commands.Tap="{Binding StartScanCommand}"
15
                    xe:TouchEffect.Color="#0060a8"
16
                    BackgroundColor="#003266"
17
                    CornerRadius="65"
18
                    HorizontalOptions="Center">
19
                    <StackLayout Padding="15,10">
20
                        <Label
21
                            FontSize="Medium"
22
                            HorizontalOptions="Center"
23
                            HorizontalTextAlignment="Center"
24
                            Text="Scan RFID"
25
                            TextColor="#34a9ff" />
26
                    </StackLayout>
27
                </xe:BorderView>
13
                    <xe:BorderView
14
                        Margin="0,20,0,0"
15
                        xe:Commands.Tap="{Binding StartScanCommand}"
16
                        xe:TouchEffect.Color="#0060a8"
17
                        BackgroundColor="#003266"
18
                        CornerRadius="65"
19
                        HorizontalOptions="Center">
20
                        <StackLayout Padding="15,10">
21
                            <Label
22
                                FontSize="Medium"
23
                                HorizontalOptions="Center"
24
                                HorizontalTextAlignment="Center"
25
                                Text="Scan RFID"
26
                                TextColor="#34a9ff" />
27
                        </StackLayout>
28
                    </xe:BorderView>
28 29

  
29
                <Frame
30
                    Padding="0"
31
                    BackgroundColor="Transparent"
32
                    BorderColor="#4f5a64"
33
                    CornerRadius="5"
34
                    HasShadow="False"
35
                    HorizontalOptions="Center"
36
                    IsVisible="{Binding ShowRFID}"
37
                    VerticalOptions="CenterAndExpand"
38
                    WidthRequest="200">
39
                    <StackLayout Spacing="0">
40
                        <Label
41
                            Margin="15"
42
                            FontSize="15"
43
                            HorizontalTextAlignment="Center"
44
                            Text="RFID Scanné"
45
                            TextColor="#34a9ff" />
30
                    <Frame
31
                        Padding="0"
32
                        BackgroundColor="Transparent"
33
                        BorderColor="#4f5a64"
34
                        CornerRadius="5"
35
                        HasShadow="False"
36
                        HorizontalOptions="Center"
37
                        IsVisible="{Binding ShowRFID}"
38
                        VerticalOptions="CenterAndExpand"
39
                        WidthRequest="200">
40
                        <StackLayout Spacing="0">
41
                            <Label
42
                                Margin="15"
43
                                FontSize="15"
44
                                HorizontalTextAlignment="Center"
45
                                Text="RFID Scanné"
46
                                TextColor="#34a9ff" />
46 47

  
47
                        <BoxView
48
                            HeightRequest="1"
49
                            HorizontalOptions="FillAndExpand"
50
                            Color="#4f5a64" />
48
                            <BoxView
49
                                HeightRequest="1"
50
                                HorizontalOptions="FillAndExpand"
51
                                Color="#4f5a64" />
51 52

  
52
                        <Label
53
                            FontAttributes="Bold"
54
                            HorizontalTextAlignment="Center"
55
                            Text="{Binding RFIDResult}"
56
                            TextColor="White" />
57
                    </StackLayout>
58
                </Frame>
53
                            <Label
54
                                FontAttributes="Bold"
55
                                HorizontalTextAlignment="Center"
56
                                Text="{Binding RFIDResult}"
57
                                TextColor="White" />
58
                        </StackLayout>
59
                    </Frame>
59 60

  
60
                <Frame
61
                    Padding="0"
62
                    BackgroundColor="Transparent"
63
                    BorderColor="#4f5a64"
64
                    CornerRadius="5"
65
                    HasShadow="False"
66
                    HorizontalOptions="Center"
67
                    IsVisible="{Binding ShowError}"
68
                    VerticalOptions="CenterAndExpand"
69
                    WidthRequest="200">
70
                    <StackLayout Spacing="0">
71
                        <Label
72
                            Margin="10"
73
                            FontSize="Medium"
74
                            HorizontalTextAlignment="Center"
75
                            Text="Erreur"
76
                            TextColor="#34a9ff" />
61
                    <Frame
62
                        Padding="0"
63
                        BackgroundColor="Transparent"
64
                        BorderColor="#4f5a64"
65
                        CornerRadius="5"
66
                        HasShadow="False"
67
                        HorizontalOptions="Center"
68
                        IsVisible="{Binding ShowError}"
69
                        VerticalOptions="CenterAndExpand"
70
                        WidthRequest="200">
71
                        <StackLayout Spacing="0">
72
                            <Label
73
                                Margin="10"
74
                                FontSize="Medium"
75
                                HorizontalTextAlignment="Center"
76
                                Text="Erreur"
77
                                TextColor="#34a9ff" />
78

  
79
                            <BoxView
80
                                HeightRequest="1"
81
                                HorizontalOptions="FillAndExpand"
82
                                Color="#4f5a64" />
77 83

  
78
                        <BoxView
79
                            HeightRequest="1"
80
                            HorizontalOptions="FillAndExpand"
81
                            Color="#4f5a64" />
84
                            <Label
85
                                Margin="5,10"
86
                                FontAttributes="Bold"
87
                                FontSize="18"
88
                                HorizontalTextAlignment="Center"
89
                                Text="{Binding ErrorMessage}"
90
                                TextColor="RED" />
91
                        </StackLayout>
92
                    </Frame>
82 93

  
94
                </StackLayout>
95
                <Grid
96
                    HorizontalOptions="FillAndExpand"
97
                    IsVisible="{Binding IsScanning}"
98
                    VerticalOptions="FillAndExpand">
99
                    <StackLayout VerticalOptions="Center">
100
                        <ActivityIndicator IsRunning="True" Color="Orange" />
83 101
                        <Label
84
                            Margin="5,10"
85 102
                            FontAttributes="Bold"
86
                            FontSize="18"
103
                            FontSize="Medium"
87 104
                            HorizontalTextAlignment="Center"
88
                            Text="{Binding ErrorMessage}"
89
                            TextColor="RED" />
105
                            Text="Scanning"
106
                            TextColor="Orange" />
90 107
                    </StackLayout>
91
                </Frame>
92

  
93
            </StackLayout>
108
                    <BoxView
109
                        BackgroundColor="White"
110
                        Opacity="0.2"
111
                        VerticalOptions="FillAndExpand" />
112
                </Grid>
113
            </Grid>
94 114
        </StackLayout>
95 115

  
96 116
    </ContentPage.Content>
TestXamConnections/TestXamConnections/Views/InternServiceView.xaml.cs
17 17
            InitializeComponent();
18 18
            BindingContext = new InternServiceViewModel();
19 19
        }
20

  
21
        protected override void OnDisappearing()
22
        {
23
            base.OnDisappearing();
24
        }
20 25
    }
21 26
}

Formats disponibles : Unified diff