Révision 1fd64302

Voir les différences:

TestXamConnections/TestXamConnections.Android/Connection/BluetoothConnectionService.cs
16 16
using TestXamConnections.Droid.Utils;
17 17
using TestXamConnections.Models;
18 18
using TestXamConnections.Connection;
19
using TestXamConnections.Helper;
19 20

  
20 21
namespace TestXamConnections.Droid.Connection
21 22
{
......
34 35
            bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
35 36
        }
36 37

  
37
        public async Task<bool> Connect(Device btDevice)
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)
38 41
        {
39 42
            try
40 43
            {
......
45 48
                    bluetoothAdapter.CancelDiscovery();
46 49
                }
47 50

  
48
                BluetoothDevice droidBtDevice = bluetoothAdapter.GetRemoteDevice(btDevice.MACAddress);
49
                if (droidBtDevice != null)
51
                if (param.ContainsKey(ConnectionConstants.MAC_ADDR_KEY))
50 52
                {
51
                    // Si le socket est occupé pour une autre connexion
52
                    // On ferme la connexion existante
53
                    if (socket != null)
53
                    BluetoothDevice droidBtDevice = bluetoothAdapter.GetRemoteDevice(param[ConnectionConstants.MAC_ADDR_KEY]);
54
                    if (droidBtDevice != null)
54 55
                    {
55
                        await CloseConnection();
56
                    }
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
                        }
57 62

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

  
61
                    CancellationTokenSource cts = new CancellationTokenSource();
66
                        CancellationTokenSource cts = new CancellationTokenSource();
62 67

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

  
66
                    if (listeningThread != null)
67
                    {
68
                        listeningThread.Abort();
69
                    }
71
                        if (listeningThread != null)
72
                        {
73
                            listeningThread.Abort();
74
                        }
70 75

  
71
                    listeningThread = new Thread(async delagate => await ListeningAsync());
72
                    listeningThread.Start();
73

  
74
                    return true;
76
                        listeningThread = new Thread(async delagate => await ListeningAsync());
77
                        listeningThread.Start();
78
                    }
75 79
                }
76 80
            }
77
            catch (Exception ex)
81
            catch (Exception)
78 82
            {
79
                System.Diagnostics.Debug.WriteLine(ex);
83
                Application.SynchronizationContext.Post(_ => { ConnectionFailedEvent.Invoke(this, param[ConnectionConstants.MAC_ADDR_KEY]); }, null);
80 84
            }
81

  
82
            return false;
83 85
        }
84 86

  
85 87
        public EventHandler<byte[]> DataReceivedEvent { get; set; }
......
135 137
            return Task.FromResult(true);
136 138
        }
137 139

  
140
        public Task<bool> SendCommand(string command)
141
        {
142
            throw new NotImplementedException();
143
        }
138 144
    }
139 145
}
TestXamConnections/TestXamConnections.Android/Connection/InternConnectionService.cs
11 11
using System.Threading.Tasks;
12 12
using TestXamConnections.Models;
13 13
using TestXamConnections.Connection;
14
using TestXamConnections.Droid.Receivers;
15
using TestXamConnections.Helper;
14 16

  
15 17
namespace TestXamConnections.Droid.Connection
16 18
{
......
20 22
     */
21 23
    public class InternConnectionService : IConnectionService
22 24
    {
23
        public EventHandler<byte[]> DataReceivedEvent { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
25
        public EventHandler<byte[]> DataReceivedEvent { get; set; }
26
        public EventHandler<string> ConnectionFailedEvent { get; set; }
24 27

  
25
        public Task<bool> Connect(Device device)
28
        private readonly IntentReceiver intentReceiver;
29
        private readonly Context appContext;
30

  
31
        /* La fonction connect dans le cas du connexion en interne
32
        *  Est en fait, la configuration de l'IntentReceiver
33
        */
34
        public Task Connect(Dictionary<string, string> param)
26 35
        {
27
            throw new NotImplementedException();
36
            if (param.ContainsKey(ConnectionConstants.RECEIVABLE_INTENTS_KEY))
37
            {
38
                // Récupérations des intents recevable
39
                List<string> intents = new List<string>();
40
                intents.AddRange(param[ConnectionConstants.RECEIVABLE_INTENTS_KEY].Split(","));
41
                // Ajout des intents recevable au IntentFilter
42
                IntentFilter intentFilter = new IntentFilter();
43
                intents.ForEach(intent => intentFilter.AddAction(intent));
44

  
45
                appContext.RegisterReceiver(intentReceiver, intentFilter);
46
            } else
47
            {
48
                ConnectionFailedEvent.Invoke(this, null);
49
            }
50
            return null;
51
        }
52

  
53
        public Task<bool> SendCommand(string command)
54
        {
55
            Intent launchIntent = appContext.PackageManager.GetLaunchIntentForPackage(command);
56
            if (launchIntent != null)
57
            {
58
                appContext.StartActivity(launchIntent);
59
                return Task.FromResult(true);
60
            }
61
            return Task.FromResult(false);
62
        }
63

  
64
        public InternConnectionService()
65
        {
66
            intentReceiver = new IntentReceiver();
67
            intentReceiver.OnInternDataReceived += OnInternDataReceived;
68
            IntentFilter intentFilter = new IntentFilter();
69
            appContext = Application.Context.ApplicationContext;
70
        }
71

  
72
        private void OnInternDataReceived(object sender, string value)
73
        {
74
            DataReceivedEvent.Invoke(this, new byte[] { 0x06 });
28 75
        }
29 76

  
30 77
        public Task<bool> SendCommand(byte[] hexValues)
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(); }
23 24

  
24
        public Task<bool> Connect(Device device)
25
        public Task<bool> Connect(Dictionary<string, string> connectParam)
25 26
        {
26 27
            throw new NotImplementedException();
27 28
        }
......
30 31
        {
31 32
            throw new NotImplementedException();
32 33
        }
34

  
35
        public Task<bool> SendCommand(string command)
36
        {
37
            throw new NotImplementedException();
38
        }
33 39
    }
34 40
}
TestXamConnections/TestXamConnections.Android/Helper/ConnectionServiceProvider.cs
34 34
                    break;
35 35

  
36 36
                case ConnectionType.Wifi:
37
                    instance = new WifiConnectionService ();
37
                    instance = new WifiConnectionService();
38 38
                    break;
39 39

  
40 40
                default:
TestXamConnections/TestXamConnections.Android/MainActivity.cs
14 14

  
15 15
namespace TestXamConnections.Droid
16 16
{
17
    [Activity(Label = "TestXamConnections", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
17
    [Activity(Label = "TestXamConnections", Icon = "@mipmap/myicon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
18 18
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
19 19
    {
20 20
        protected override void OnCreate(Bundle savedInstanceState)
TestXamConnections/TestXamConnections.Android/Properties/AndroidManifest.xml
1 1
<?xml version="1.0" encoding="utf-8"?>
2
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.testble" android:installLocation="auto">
2
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.testxamconnections" android:installLocation="auto">
3 3
	<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="30" />
4
	<application android:label="TestBLE.Android" android:theme="@style/MainTheme"></application>
4
	<application android:label="TestXamConnections.Android" android:theme="@style/MainTheme"></application>
5 5
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
6 6
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
7 7
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
TestXamConnections/TestXamConnections.Android/Receivers/IntentReceiver.cs
1
using Android.App;
2
using Android.Content;
3
using Android.OS;
4
using Android.Runtime;
5
using Android.Views;
6
using Android.Widget;
7
using System;
8
using System.Collections.Generic;
9
using System.Linq;
10
using System.Text;
11

  
12
namespace TestXamConnections.Droid.Receivers
13
{
14
    public class IntentReceiver : BroadcastReceiver
15
    {
16

  
17
        public EventHandler<string> OnInternDataReceived;
18

  
19
        public override void OnReceive(Context context, Intent intent)
20
        {
21
            StringBuilder sb = new StringBuilder();
22
            sb.Append("Action:  " + intent.Action + "\n");
23
            sb.Append("URI: " + intent.ToUri(IntentUriType.Scheme).ToString() + "\n");
24
            string log = sb.ToString();
25
            OnInternDataReceived.Invoke(this, log);
26
        }
27
    }
28
}
TestXamConnections/TestXamConnections.Android/Resources/Resource.designer.cs
20565 20565
			// aapt resource value: 0x7F0C0002
20566 20566
			public const int launcher_foreground = 2131492866;
20567 20567
			
20568
			// aapt resource value: 0x7F0C0003
20569
			public const int myicon = 2131492867;
20570
			
20568 20571
			static Mipmap()
20569 20572
			{
20570 20573
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
TestXamConnections/TestXamConnections.Android/Resources/mipmap-anydpi-v26/icon_round.xml
1 1
<?xml version="1.0" encoding="utf-8"?>
2 2
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
3 3
    <background android:drawable="@color/launcher_background" />
4
    <foreground android:drawable="@mipmap/launcher_foreground" />
4
    <foreground android:drawable="@mipmap/myicon" />
5 5
</adaptive-icon>
TestXamConnections/TestXamConnections.Android/TestXamConnections.Android.csproj
68 68
    <Compile Include="Connection\WifiConnectionService.cs" />
69 69
    <Compile Include="MainActivity.cs" />
70 70
    <Compile Include="Receivers\BluetoothReceiver.cs" />
71
    <Compile Include="Receivers\IntentReceiver.cs" />
71 72
    <Compile Include="Resources\Resource.designer.cs" />
72 73
    <Compile Include="Properties\AssemblyInfo.cs" />
73 74
    <Compile Include="Services\BluetoothService.cs" />
......
103 104
      <Name>TestXamConnections</Name>
104 105
    </ProjectReference>
105 106
  </ItemGroup>
107
  <ItemGroup>
108
    <AndroidResource Include="Resources\mipmap-hdpi\myicon.png" />
109
  </ItemGroup>
106 110
  <Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />
107 111
</Project>
TestXamConnections/TestXamConnections/Connection/IConnectionService.cs
9 9
{
10 10
    public interface IConnectionService
11 11
    {
12
        Task<bool> Connect(Device device);
12
        /* Fonction de connexion à la fonctionnalité cible
13
         * connectParam : paramètre de connection
14
         * Pour Bluetooth, addresse MAC
15
         * Pour connexion interne, les intents recevables
16
         * --> Ajout à un IntentFilter
17
         * Déclenche ConnectionFailedEvent si la connection échoue
18
         */
19
        Task Connect(Dictionary<string, string> connectParam);
20

  
21
        /*
22
         * Fonction d'envoi de commande
23
         * byte[] pour le bluetooth
24
         * string pour intern
25
         * Retourne True si la commande s'est bien envoyée
26
         */
13 27
        Task<bool> SendCommand(byte[] hexValues);
28
        Task<bool> SendCommand(string command);
29

  
30
        /* Evenement déclenché à la reception de données
31
         * Renvoi les données sur forme d'un tableau d'octets
32
         */
14 33
        EventHandler<byte[]> DataReceivedEvent { get; set; }
34

  
35
        /* Evenement déclenché quand la connexion échoue
36
         */
37
        EventHandler<string> ConnectionFailedEvent { get; set; }
15 38
    }
16 39
}
TestXamConnections/TestXamConnections/Helper/ConnectionConstants.cs
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4

  
5
namespace TestXamConnections.Helper
6
{
7
    public static class ConnectionConstants
8
    {
9
        public static readonly string MAC_ADDR_KEY = "mac_address";
10
        public static readonly string LAUNCH_INTENT_KEY = "launch_intent";
11
        public static readonly string RECEIVABLE_INTENTS_KEY = "receivable_intents";
12

  
13
    }
14
}
TestXamConnections/TestXamConnections/MainPage.xaml
1
<?xml version="1.0" encoding="utf-8" ?>
2
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
3
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
4
             x:Class="TestXamConnections.MainPage">
5

  
6
    <StackLayout>
7
        <Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
8
            <Label Text="Welcome to Xamarin.Forms!" HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/>
9
        </Frame>
10
        <Label Text="Start developing now" FontSize="Title" Padding="30,10,30,10"/>
11
        <Label Text="Make changes to your XAML file and save to see your UI update in the running app with XAML Hot Reload. Give it a try!" FontSize="16" Padding="30,0,30,0"/>
12
        <Label FontSize="16" Padding="30,24,30,0">
13
            <Label.FormattedText>
14
                <FormattedString>
15
                    <FormattedString.Spans>
16
                        <Span Text="Learn more at "/>
17
                        <Span Text="https://aka.ms/xamarin-quickstart" FontAttributes="Bold"/>
18
                    </FormattedString.Spans>
19
                </FormattedString>
20
            </Label.FormattedText>
21
        </Label>
22
    </StackLayout>
23

  
24
</ContentPage>
TestXamConnections/TestXamConnections/MainPage.xaml.cs
1
using System;
2
using System.Collections.Generic;
3
using System.ComponentModel;
4
using System.Linq;
5
using System.Text;
6
using System.Threading.Tasks;
7
using Xamarin.Forms;
8

  
9
namespace TestXamConnections
10
{
11
    public partial class MainPage : ContentPage
12
    {
13
        public MainPage()
14
        {
15
            InitializeComponent();
16
        }
17
    }
18
}
TestXamConnections/TestXamConnections/Models/AgridentReader.cs
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.Threading.Tasks;
5
using TestXamConnections.Connection;
6
using TestXamConnections.Helper;
7
using Xamarin.Forms;
8

  
9
namespace TestXamConnections.Models
10
{
11
    public class AgridentConstants
12
    {
13
        public const string ACTION_AGRIDENT_SUCCESS = "fr.coppernic.intent.agridentsuccess";
14
        public const string ACTION_AGRIDENT_ERROR = "fr.coppernic.intent.agridentfailed";
15
        public const string ACTION_AGRIDENT_SERVICE_STOP = "fr.coppernic.intent.action.stop.agrident.service";
16
        public const string ACTION_AGRIDENT_SERVICE_START = "fr.coppernic.intent.action.start.agrident.service";
17
        public const string ACTION_AGRIDENT_READ = "fr.coppernic.tools.agrident.wedge.READ";
18
        public const string KEY_BARCODE_DATA = "BarcodeData";
19
        public const string AGRIDENT_WEDGE = "fr.coppernic.tools.cpcagridentwedge";
20
    }
21

  
22
    public class AgridentReader
23
    {
24

  
25
        private IConnectionService ConnectionService { get; set; }
26
        public EventHandler<string> AgridentDataReceivedEvent { get; set; }
27
        public EventHandler<string> AgridentNORFIDEvent { get; set; }
28

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

  
35
        ~AgridentReader()
36
        {
37
            ConnectionService.DataReceivedEvent -= (s, args) => AgridentDataReceived(args);
38
        }
39

  
40
        /* Fonction déclenchée à la reception de données Agrident
41
         * Trigger l'évènement AgridentDataReceivedEvent
42
         */
43
        private void AgridentDataReceived(byte[] args)
44
        { 
45
            // Si pas de valeur scannée
46
            // Evenement error
47
            if (args[0] == 0x6)
48
            {
49
                AgridentNORFIDEvent.Invoke(this, null);
50
            } 
51
            // Sinon c'est une valeur rfid
52
            else
53
            {
54
                AgridentDataReceivedEvent.Invoke(this, Encoding.ASCII.GetString(args));
55
            }
56
        }
57

  
58
        public async Task<bool> EnableService()
59
        {
60
            // Enregistrement des intents recevable par Agrident
61
            List<string> intentsList = new List<string>()
62
            {
63
                AgridentConstants.ACTION_AGRIDENT_SUCCESS,
64
                AgridentConstants.ACTION_AGRIDENT_ERROR
65
            };
66
            string intents = string.Join(',', intentsList);
67

  
68
            // Encapuslation des intents recevables pour envoyer au service de connexion
69
            Dictionary<string, string> param = new Dictionary<string, string>()
70
            {
71
                { ConnectionConstants.RECEIVABLE_INTENTS_KEY, intents }
72
            };
73

  
74
            await ConnectionService.Connect(param);
75
            return true;
76
        }
77

  
78
        public async Task<bool> StartScan()
79
        {
80
            return await ConnectionService.SendCommand(AgridentConstants.AGRIDENT_WEDGE);
81
        }
82

  
83
    }
84
}
TestXamConnections/TestXamConnections/Models/TeoBalance.cs
30 30

  
31 31
    public class TeoBalance : Device
32 32
    {
33
        public IConnectionService ConnectionService { get; set; }
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; }
36 37

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

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

  
50 53
        /* 
......
56 59
         * nommé _bufferedData
57 60
         */
58 61
        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
        }
59 68

  
69
        // Fonction appelée lors de la reception de données par le ConnectionService
60 70
        private void TeoDataReceived(byte[] buffer)
61 71
        {
62 72
            // Si le premier character est 2 (ASCII: STX)
......
100 110
            }
101 111
        }
102 112

  
113
        // Connexion à l'appareil en fonction de son addr MAC
114
        public async Task<bool> ConnectToTeoAsync()
115
        {
116
            Dictionary<string, string> param = new Dictionary<string, string>()
117
            {
118
                { ConnectionConstants.MAC_ADDR_KEY, MACAddress }
119
            };
120
            await ConnectionService.Connect(param);
121
            return true;
122
        }
123

  
124
        // Envoi d'une commande passée en argument
125
        public async Task<bool> SendTeoCommand(TeoCommandType c)
126
        {
127
            return await ConnectionService.SendCommand(GetCommandCode(c));
128
        }
129

  
103 130
        // Retourne la chaine d'octets d'une commande Teo (prog INRAE)
104 131
        public static byte[] GetCommandCode(TeoCommandType c)
105 132
        {
TestXamConnections/TestXamConnections/TestXamConnections.csproj
31 31
    <EmbeddedResource Update="Views\AccueilView.xaml">
32 32
      <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
33 33
    </EmbeddedResource>
34
    <EmbeddedResource Update="Views\InternServiceView.xaml">
35
      <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
36
    </EmbeddedResource>
34 37
    <EmbeddedResource Update="Views\TeoDeviceView.xaml">
35 38
      <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
36 39
    </EmbeddedResource>
TestXamConnections/TestXamConnections/ViewModels/AccueilViewModel.cs
9 9
using TestXamConnections.Helper;
10 10
using TestXamConnections.Models;
11 11
using TestXamConnections.Services;
12
using TestXamConnections.Views;
12 13
using Xamarin.Essentials;
13 14
using Xamarin.Forms;
14 15

  
......
68 69
        {
69 70
            await CheckAndRequestLocationPermission();
70 71
        }
71
        
72

  
73
        public async Task NavigateToInternService()
74
        {
75
            await Application.Current.MainPage.Navigation.PushAsync(new InternServiceView());
76
        }
77

  
78
        public ICommand NavigateToInternServiceCommand { private set; get; }
79

  
72 80
        // *** CTOR ***
73 81
        public AccueilViewModel()
74 82
        {
......
76 84
            LoadBondedDevicesCommand = new Command(() => LoadBondedDevices());
77 85
            BondedDevicesList = new ObservableCollection<DeviceItemViewModel>();
78 86
            ShowBondedDevices = false;
87
            NavigateToInternServiceCommand = new Command(async () => await NavigateToInternService());
79 88
        }
80 89
    }
81 90
}
TestXamConnections/TestXamConnections/ViewModels/CommandItemViewModel.cs
12 12
    {
13 13
        private string name;
14 14
        private TeoCommandType toSendCommand;
15
        private IConnectionService ConnectionService;
16 15
        private string commandBytes;
17 16

  
18 17
        public string CommandBytes
......
33 32
            set { SetProperty( ref toSendCommand, value); }
34 33
        }
35 34

  
36
        private async Task<bool> SendValue()
37
        {
38
            await ConnectionService.SendCommand(TeoBalance.GetCommandCode(ToSendCommand));
39
            return true;
40
        }
41

  
42
        public ICommand SendValueCommand { private set; get; }
43

  
44
        public CommandItemViewModel(TeoCommandType cmd, IConnectionService cs)
35
        public CommandItemViewModel(TeoCommandType cmd)
45 36
        {
46 37
            ToSendCommand = cmd;
47
            ConnectionService = cs;
48 38
            Name = TeoBalance.GetCommandName(cmd);
49 39
            CommandBytes = string.Join("-", TeoBalance.GetCommandCode(cmd));
50
            SendValueCommand = new Command(async () => await SendValue());
51 40
        }
52 41

  
53 42
    }
TestXamConnections/TestXamConnections/ViewModels/DeviceItemViewModel.cs
24 24

  
25 25
        private async Task NavigateToDevice()
26 26
        {
27
            await Application.Current.MainPage.Navigation.PushAsync(new TeoDeviceView(Device));
27
            // Si c'est le teo du bureau
28
            if (Device.MACAddress == "60:A4:23:EB:FB:5C")
29
            {
30
                await Application.Current.MainPage.Navigation.PushAsync(new TeoDeviceView(Device));
31
            }
28 32
        }
29 33

  
30 34
        public ICommand NavigateToDeviceViewCommand { private set; get; }
TestXamConnections/TestXamConnections/ViewModels/DeviceViewModel.cs
1
using System;
2
using System.Collections.Generic;
3
using System.Collections.ObjectModel;
4
using System.Text;
5
using System.Threading.Tasks;
6
using System.Windows.Input;
7
using TestXamConnections.Connection;
8
using TestXamConnections.Helper;
9
using TestXamConnections.Models;
10
using TestXamConnections.Services;
11
using Xamarin.Forms;
12
using static TestXamConnections.Models.TeoBalance;
13

  
14
namespace TestXamConnections.ViewModels
15
{
16
    public class TeoDeviceViewModel : ViewModelBase
17
    {
18
        private bool isConnected;
19
        private string data;
20
        private TeoBalance teoScale;
21

  
22
        private bool isVisibleData;
23

  
24
        public bool IsVisibleData
25
        {
26
            get { return isVisibleData; }
27
            set { SetProperty(ref isVisibleData, value); }
28
        }
29

  
30
        public bool IsConnected
31
        {
32
            get { return isConnected; }
33
            set { SetProperty(ref isConnected, value); }
34
        }
35

  
36
        public TeoBalance TeoScale
37
        {
38
            get { return teoScale; }
39
            set { SetProperty(ref teoScale, value); }
40
        }
41

  
42
        public string Data
43
        {
44
            get { return data; }
45
            set { SetProperty(ref data, value); }
46
        }
47
        
48
        public ObservableCollection<CommandItemViewModel> AvailableCommandsList { get; set; }
49

  
50
        public async Task<bool> ConnectToDevice()
51
        {
52
            IsConnected = await teoScale.ConnectionService.Connect(TeoScale);
53
            return IsConnected;
54
        }
55

  
56
        public void DataReceived(string args)
57
        {
58
            IsVisibleData = true;
59
            Data += args.Trim() + "\n";
60
        }
61

  
62
        public void PeseeReceived(ReponsePesee args)
63
        {
64
            Data = args.PoidsMesure;
65
        }
66

  
67
        public ICommand ConnectToDeviceCommand { private set; get; }
68

  
69
        public TeoDeviceViewModel(Models.Device device)
70
        {
71
            TeoScale = new TeoBalance(device);
72
            IsConnected = false;
73
            IsVisibleData = false;
74
            ConnectToDeviceCommand = new Command(async () => await ConnectToDevice());
75
            TeoScale.TeoDataReceivedEvent = (s, args) => DataReceived(args);
76
            TeoScale.TeoPeseeReceivedEvent = (s, args) => PeseeReceived(args);
77

  
78
            // Ajout manuel des commandes
79
            AvailableCommandsList = new ObservableCollection<CommandItemViewModel>();
80
            foreach (TeoCommandType _cmd in Enum.GetValues(typeof(TeoCommandType)))
81
            {
82
                AvailableCommandsList.Add(new CommandItemViewModel(_cmd, TeoScale.ConnectionService));
83
            }
84
        }
85

  
86
        
87

  
88
    }
89
}
TestXamConnections/TestXamConnections/ViewModels/InternServiceViewModel.cs
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.Threading.Tasks;
5
using System.Windows.Input;
6
using TestXamConnections.Models;
7
using Xamarin.Forms;
8

  
9
namespace TestXamConnections.ViewModels
10
{
11
    public class InternServiceViewModel : ViewModelBase
12
    {
13
        private bool showRFID;
14
        private bool showError;
15
        private AgridentReader agridentReader;
16
        private string rfidResult;
17
        private string errorMessage;
18

  
19
        public bool ShowRFID
20
        {
21
            get { return showRFID; }
22
            set { SetProperty(ref showRFID, value); }
23
        }
24

  
25
        public bool ShowError
26
        {
27
            get { return showError; }
28
            set { SetProperty( ref showError, value); }
29
        }
30

  
31
        public string RFIDResult
32
        {
33
            get { return rfidResult; }
34
            set { SetProperty(ref rfidResult, value); }
35
        }
36

  
37
        public string ErrorMessage
38
        {
39
            get { return errorMessage; }
40
            set { SetProperty(ref errorMessage, value); }
41
        }
42

  
43
        private async Task StartScan()
44
        {
45
            ShowError = false;
46
            ShowRFID = false;
47
            if (await agridentReader.StartScan() == false)
48
            {
49
                ErrorMessage = "Echec du Scan RFID";
50
            }
51
        }
52

  
53
        public ICommand StartScanCommand { private set; get; }
54

  
55
        public InternServiceViewModel()
56
        {
57
            ShowRFID = false;
58
            ShowError = false;
59
            agridentReader = new AgridentReader();
60
            agridentReader.EnableService().Wait();
61
            agridentReader.AgridentDataReceivedEvent += OnRFIDResultReceived;
62
            agridentReader.AgridentNORFIDEvent += OnNoRFIDReceived;
63
            StartScanCommand = new Command(async () => await StartScan());
64
        }
65

  
66
        private void OnNoRFIDReceived(object sender, string e)
67
        {
68
            ShowError = true;
69
            ErrorMessage = "Pas de TAG RFID detecté";
70
        }
71

  
72
        private void OnRFIDResultReceived(object sender, string e)
73
        {
74
            ShowRFID = true;
75
            RFIDResult = e;
76
        }
77
    }
78
}
TestXamConnections/TestXamConnections/ViewModels/TeoDeviceViewModel.cs
1
using System;
2
using System.Collections.Generic;
3
using System.Collections.ObjectModel;
4
using System.Text;
5
using System.Threading.Tasks;
6
using System.Windows.Input;
7
using TestXamConnections.Connection;
8
using TestXamConnections.Helper;
9
using TestXamConnections.Models;
10
using TestXamConnections.Services;
11
using Xamarin.Forms;
12
using static TestXamConnections.Models.TeoBalance;
13

  
14
namespace TestXamConnections.ViewModels
15
{
16
    public class TeoDeviceViewModel : ViewModelBase
17
    {
18
        private bool isConnected;
19
        private string data;
20
        private TeoBalance teoScale;
21
        private bool isVisibleData;
22
        private bool showError;
23
        private string errorMessage;
24

  
25
        public bool IsVisibleData
26
        {
27
            get { return isVisibleData; }
28
            set { SetProperty(ref isVisibleData, value); }
29
        }
30

  
31
        public bool IsConnected
32
        {
33
            get { return isConnected; }
34
            set { SetProperty(ref isConnected, value); }
35
        }
36

  
37
        public TeoBalance TeoScale
38
        {
39
            get { return teoScale; }
40
            set { SetProperty(ref teoScale, value); }
41
        }
42

  
43
        public string Data
44
        {
45
            get { return data; }
46
            set { SetProperty(ref data, value); }
47
        }
48

  
49
        public bool ShowError
50
        {
51
            get { return showError; }
52
            set { SetProperty(ref showError, value); }
53
        }
54

  
55
        public string ErrorMessage
56
        {
57
            get { return errorMessage; }
58
            set { SetProperty(ref errorMessage, value); }
59
        }
60

  
61
        public ObservableCollection<CommandItemViewModel> AvailableCommandsList { get; set; }
62

  
63
        public async Task<bool> ConnectToDevice()
64
        {
65
            ShowError = false;
66
            IsConnected = await teoScale.ConnectToTeoAsync();
67
            return IsConnected;
68
        }
69

  
70
        public async Task<bool> SendValue(TeoCommandType cmd)
71
        {
72
            return await teoScale.SendTeoCommand(cmd);
73
        }
74

  
75
        public ICommand ConnectToDeviceCommand { private set; get; }
76
        public ICommand SendValueCommand { private set; get; }
77

  
78
        public TeoDeviceViewModel(Models.Device device)
79
        {
80
            TeoScale = new TeoBalance(device);
81
            ShowError = false;
82
            IsConnected = false;
83
            IsVisibleData = false;
84
            ConnectToDeviceCommand = new Command(async () => await ConnectToDevice());
85
            SendValueCommand = new Command(async (cmd) => await teoScale.SendTeoCommand((TeoCommandType)cmd));
86
            TeoScale.TeoDataReceivedEvent = (s, args) => DataReceived(args);
87
            TeoScale.TeoPeseeReceivedEvent = (s, args) => PeseeReceived(args);
88
            TeoScale.TeoConnectionFailedEvent = ConnectionFailed;
89

  
90
            // Ajout manuel des commandes
91
            AvailableCommandsList = new ObservableCollection<CommandItemViewModel>();
92
            foreach (TeoCommandType _cmd in Enum.GetValues(typeof(TeoCommandType)))
93
            {
94
                AvailableCommandsList.Add(new CommandItemViewModel(_cmd));
95
            }
96
        }
97

  
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)
106
        {
107
            IsVisibleData = true;
108
            Data += args.Trim() + "\n";
109
        }
110

  
111
        public void PeseeReceived(ReponsePesee args)
112
        {
113
            Data = args.PoidsMesure;
114
        }
115
    }
116
}
TestXamConnections/TestXamConnections/Views/AccueilView.xaml
4 4
    xmlns="http://xamarin.com/schemas/2014/forms"
5 5
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
6 6
    xmlns:xe="clr-namespace:XamEffects;assembly=XamEffects"
7
    Title="Teo Test Bluetooth - Bienvenue">
7
    Title="TestXamConnection">
8 8
    <ContentPage.Content>
9

  
9 10
        <StackLayout BackgroundColor="#001729" VerticalOptions="FillAndExpand">
10 11
            <StackLayout VerticalOptions="CenterAndExpand">
11 12
                <Frame
......
107 108

  
108 109
                    </StackLayout>
109 110
                </Frame>
111

  
112
                <xe:BorderView
113
                    Margin="0,20,0,0"
114
                    xe:Commands.Tap="{Binding NavigateToInternServiceCommand}"
115
                    xe:TouchEffect.Color="#0060a8"
116
                    BackgroundColor="#003266"
117
                    CornerRadius="65"
118
                    HorizontalOptions="Center">
119
                    <StackLayout Padding="15,10">
120
                        <Label
121
                            FontSize="16"
122
                            HorizontalOptions="Center"
123
                            HorizontalTextAlignment="Center"
124
                            Text="Service interne"
125
                            TextColor="#34a9ff" />
126
                    </StackLayout>
127
                </xe:BorderView>
128

  
110 129
            </StackLayout>
111 130
        </StackLayout>
131

  
112 132
    </ContentPage.Content>
113 133
</ContentPage>
TestXamConnections/TestXamConnections/Views/InternServiceView.xaml
1
<?xml version="1.0" encoding="UTF-8" ?>
2
<ContentPage
3
    x:Class="TestXamConnections.Views.InternServiceView"
4
    xmlns="http://xamarin.com/schemas/2014/forms"
5
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
6
    xmlns:xe="clr-namespace:XamEffects;assembly=XamEffects">
7
    <ContentPage.Content>
8

  
9
        <StackLayout BackgroundColor="#001729" VerticalOptions="FillAndExpand">
10
            <StackLayout VerticalOptions="CenterAndExpand">
11

  
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="16"
22
                            HorizontalOptions="Center"
23
                            HorizontalTextAlignment="Center"
24
                            Text="Scan RFID"
25
                            TextColor="#34a9ff" />
26
                    </StackLayout>
27
                </xe:BorderView>
28

  
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" />
46

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

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

  
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="15"
73
                            FontSize="15"
74
                            HorizontalTextAlignment="Center"
75
                            Text="Erreur"
76
                            TextColor="#34a9ff" />
77

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

  
83
                        <Label
84
                            FontAttributes="Bold"
85
                            FontSize="Medium"
86
                            HorizontalTextAlignment="Center"
87
                            Text="{Binding ErrorMessage}"
88
                            TextColor="RED" />
89
                    </StackLayout>
90
                </Frame>
91

  
92
            </StackLayout>
93
        </StackLayout>
94

  
95
    </ContentPage.Content>
96
</ContentPage>
TestXamConnections/TestXamConnections/Views/InternServiceView.xaml.cs
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Threading.Tasks;
6
using TestXamConnections.ViewModels;
7
using Xamarin.Forms;
8
using Xamarin.Forms.Xaml;
9

  
10
namespace TestXamConnections.Views
11
{
12
    [XamlCompilation(XamlCompilationOptions.Compile)]
13
    public partial class InternServiceView : ContentPage
14
    {
15
        public InternServiceView()
16
        {
17
            InitializeComponent();
18
            BindingContext = new InternServiceViewModel();
19
        }
20
    }
21
}
TestXamConnections/TestXamConnections/Views/TeoDeviceView.xaml
46 46
                        CornerRadius="5"
47 47
                        HasShadow="False"
48 48
                        HorizontalOptions="Center"
49
                        IsVisible="{Binding ShowError}"
50
                        VerticalOptions="CenterAndExpand"
51
                        WidthRequest="200">
52
                        <StackLayout Spacing="0">
53
                            <Label
54
                                Margin="15"
55
                                FontSize="15"
56
                                HorizontalTextAlignment="Center"
57
                                Text="Erreur"
58
                                TextColor="#34a9ff" />
59

  
60
                            <BoxView
61
                                HeightRequest="1"
62
                                HorizontalOptions="FillAndExpand"
63
                                Color="#4f5a64" />
64

  
65
                            <Label
66
                                FontAttributes="Bold"
67
                                FontSize="Medium"
68
                                HorizontalTextAlignment="Center"
69
                                Text="{Binding ErrorMessage}"
70
                                TextColor="RED" />
71
                        </StackLayout>
72
                    </Frame>
73

  
74
                    <Frame
75
                        Padding="0"
76
                        BackgroundColor="Transparent"
77
                        BorderColor="#4f5a64"
78
                        CornerRadius="5"
79
                        HasShadow="False"
80
                        HorizontalOptions="Center"
49 81
                        VerticalOptions="CenterAndExpand"
50 82
                        WidthRequest="250">
51 83
                        <StackLayout Spacing="0">
......
102 134
                                        <DataTemplate>
103 135
                                            <StackLayout
104 136
                                                Padding="0,5"
105
                                                xe:Commands.Tap="{Binding SendValueCommand}"
137
                                                xe:Commands.Tap="{Binding SendValueCommand, Source={Reference commandsList}}"
138
                                                xe:Commands.TapParameter="{Binding ToSendCommand}"
106 139
                                                xe:TouchEffect.Color="#34a9ff"
107 140
                                                Spacing="0">
108 141
                                                <Label

Formats disponibles : Unified diff