aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.UI/Connectivity/DefaultConnectivityProvider.cs
blob: a55506be653c1f658b890c9139f9e9e85134738c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
using Microsoft.WindowsAPICodePack.Net;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Data;
using Tango.BL;
using Tango.Core;
using Tango.Core.Commands;
using Tango.Core.Cryptography;
using Tango.PPC.Common;
using Tango.PPC.Common.Application;
using Tango.PPC.Common.Build;
using Tango.PPC.Common.Connection;
using Tango.PPC.Common.Connectivity;
using Tango.PPC.Common.Notifications;
using Tango.Settings;
using Tango.WiFi;

namespace Tango.PPC.UI.Connectivity
{
    public class DefaultConnectivityProvider : ExtendedObject, IConnectivityProvider
    {
        private Wifi _wifi;
        private INotificationProvider _notification;
        private IMachineProvider _machineProvider;
        private Rfc2898Cryptographer _cryptographer;
        private System.Timers.Timer _updateTimer;
        private System.Timers.Timer _lanUpdateTimer;
        private WiFiNetwork _connectedNetwork;
        private PPCSettings _settings;
        private IBuildProvider _buildProvider;

        /// <summary>
        /// Occurs when the connectivity provider state has changed (e.g network connected/disconnected).
        /// </summary>
        public event EventHandler<ConnectionStateEventArgs> ConnectionStateChanged;

        private bool _isConnected;
        /// <summary>
        /// Gets a value indicating whether there is any Internet connection available.
        /// </summary>
        public bool IsConnected
        {
            get
            {
                return _buildProvider.IsEureka ? true : _isConnected;
            }
            private set { _isConnected = value; RaisePropertyChangedAuto(); }
        }

        private bool _isLanConnected;
        /// <summary>
        /// Gets a value indicating whether there is LAN connection.
        /// </summary>
        public bool IsLanConnected
        {
            get
            {
                return _buildProvider.IsEureka ? true : _isLanConnected;
            }
            private set { _isLanConnected = value; RaisePropertyChangedAuto(); }
        }

        private bool _isHotspoActive;
        /// <summary>
        /// Gets a value indicating whether the hot spot network is active.
        /// </summary>
        public bool IsHotspotActive
        {
            get { return _isHotspoActive; }
            set { _isHotspoActive = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets the available WiFi networks.
        /// </summary>
        public ObservableCollection<WiFiNetwork> AvailableWiFiNetworks { get; }

        /// <summary>
        /// Gets the available WiFi networks as a sorted view source by signal strength.
        /// </summary>
        public ICollectionView AvailableWiFiNetworksViewSource { get; set; }

        /// <summary>
        /// Gets the connect to WiFi command.
        /// </summary>
        public RelayCommand<WiFiNetwork> ConnectToWiFiCommand { get; private set; }

        /// <summary>
        /// Gets the disconnect from WiFi command.
        /// </summary>
        public RelayCommand<WiFiNetwork> DisconnectFromWiFiCommand { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        public RelayCommand RefreshAvailableWiFiNetworksCommand { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultConnectivityProvider"/> class.
        /// </summary>
        public DefaultConnectivityProvider(IPPCApplicationManager applicationManager, INotificationProvider notificationProvider, IMachineProvider machineProvider, IBuildProvider buildProvider)
        {
            _cryptographer = new Rfc2898Cryptographer();

            _buildProvider = buildProvider;
            _notification = notificationProvider;
            _machineProvider = machineProvider;

            AvailableWiFiNetworks = new ObservableCollection<WiFiNetwork>();
            AvailableWiFiNetworks.EnableCrossThreadOperations();
            AvailableWiFiNetworksViewSource = CollectionViewSource.GetDefaultView(AvailableWiFiNetworks);

            AvailableWiFiNetworksViewSource.SortDescriptions.Add(new SortDescription(nameof(WiFiNetwork.IsConnected), ListSortDirection.Descending));
            AvailableWiFiNetworksViewSource.SortDescriptions.Add(new SortDescription(nameof(WiFiNetwork.SignalStrength), ListSortDirection.Descending));

            if (!_buildProvider.IsEureka)
            {
                _wifi = new Wifi();
                applicationManager.ApplicationReady += ApplicationManager_Ready;
            }

            ConnectToWiFiCommand = new RelayCommand<WiFiNetwork>(async (x) =>
            {
                await Connect(x);
            });

            DisconnectFromWiFiCommand = new RelayCommand<WiFiNetwork>((x) =>
            {
                Disconnect(x);
            });

            RefreshAvailableWiFiNetworksCommand = new RelayCommand(async () =>
            {
                await RefreshAvailableWiFiNetworks();
            });

            _settings = SettingsManager.Default.GetOrCreate<PPCSettings>();
        }

        /// <summary>
        /// Handles the application manager ApplicationReady event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplicationManager_Ready(object sender, EventArgs e)
        {
            Task.Factory.StartNew(async () =>
            {
                Thread.Sleep(2000);

                await RefreshAvailableWiFiNetworks();
                var settings = SettingsManager.Default.GetOrCreate<PPCSettings>();

                var networks = AvailableWiFiNetworks.ToList();

                var auto_connect_network = networks.FirstOrDefault(x => x.Name == settings.AutoConnectWiFiName);

                IsConnected = networks.Exists(x => x.IsConnected);

                if (IsConnected)
                {
                    _connectedNetwork = auto_connect_network;
                }

                if (auto_connect_network != null && !auto_connect_network.IsConnected)
                {
                    auto_connect_network.AutoConnect = true;
                    await Connect(auto_connect_network, _cryptographer.Decrypt(settings.AutoConnectWiFiPassword));
                }
            });

            _updateTimer = new System.Timers.Timer(TimeSpan.FromSeconds(30).TotalMilliseconds);
            _updateTimer.Elapsed += _updateTimer_Elapsed;
            _updateTimer.Start();

            _lanUpdateTimer = new System.Timers.Timer(TimeSpan.FromSeconds(10).TotalMilliseconds);
            _lanUpdateTimer.Elapsed += _lanUpdateTimer_Elapsed;
            _lanUpdateTimer.Start();
        }

        private void _lanUpdateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            foreach (NetworkInterface net in NetworkInterface.GetAllNetworkInterfaces())
            {
                if ((net.NetworkInterfaceType == NetworkInterfaceType.Ethernet
                    || net.NetworkInterfaceType == NetworkInterfaceType.Ethernet3Megabit
                    || net.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx
                    || net.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT
                    || net.NetworkInterfaceType == NetworkInterfaceType.GigabitEthernet) && net.Name.ToStringOrEmpty().StartsWith("Ethernet") && net.OperationalStatus == OperationalStatus.Up)
                {
                    IsLanConnected = true;
                    return;
                }
            }

            IsLanConnected = false;
        }

        /// <summary>
        /// Periodically checks if WiFI network is gone/disconnected.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Timers.ElapsedEventArgs"/> instance containing the event data.</param>
        private void _updateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (IsConnected && _connectedNetwork != null)
            {
                var networks = GetAvailableWiFiNetworks().Result;
                var matching_network = networks.FirstOrDefault(x => x.Name == _connectedNetwork.Name);

                if (matching_network == null || !matching_network.AccessPoint.IsConnected)
                {
                    OnConnectionStateChanged(false);
                }
            }
        }

        /// <summary>
        /// Gets the available WiFi networks.
        /// </summary>
        /// <returns></returns>
        public Task<List<WiFiNetwork>> GetAvailableWiFiNetworks()
        {
            return Task.Factory.StartNew<List<WiFiNetwork>>(() =>
            {
                var accessPoints = _wifi.GetAccessPoints();

                AvailableWiFiNetworks.Where(x => !accessPoints.ToList().Exists(y => y.Name == x.Name)).ToList().ForEach(x => AvailableWiFiNetworks.Remove(x));

                foreach (var ap in accessPoints.ToList())
                {
                    var network = AvailableWiFiNetworks.FirstOrDefault(x => x.Name == ap.Name);

                    if (network == null)
                    {
                        network = new WiFiNetwork(ap, _wifi);
                        AvailableWiFiNetworks.Add(network);
                    }
                    else
                    {
                        network.AccessPoint = ap;
                    }
                }

                return AvailableWiFiNetworks.ToList();
            });
        }

        /// <summary>
        /// Resets the available WiFi networks collection.
        /// </summary>
        public Task RefreshAvailableWiFiNetworks()
        {
            return Task.Factory.StartNew(() =>
            {
                AvailableWiFiNetworks.Clear();

                if (!_buildProvider.IsEureka)
                {
                    GetAvailableWiFiNetworks().Wait();
                }
            });
        }

        /// <summary>
        /// Checks the Internet connection.
        /// </summary>
        /// <returns></returns>
        public Task<bool> CheckInternetConnection()
        {
            if (_settings.BypassInternetConnectivityCheck)
            {
                return Task.FromResult(true);
            }

            return Task.Factory.StartNew<bool>(() =>
            {
                try
                {
                    return NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected).Any(x => x.IsConnectedToInternet);
                }
                catch
                {
                    return true;
                }
            });
        }

        /// <summary>
        /// Connects the specified network.
        /// </summary>
        /// <param name="network">The network.</param>
        /// <returns></returns>
        public async Task<bool> Connect(WiFiNetwork network, String password = null)
        {
            var auth = network.CreateAuthenticationRequest();

            bool result = false;

            if (password == null)
            {
                if ((auth.IsPasswordRequired || auth.IsUserNameRequired) && !network.HasProfile)
                {
                    var vm = await _notification.ShowDialog<WiFiAuthenticationViewVM>(new WiFiAuthenticationViewVM(auth, network));

                    if (vm.DialogResult)
                    {
                        result = await network.Connect(auth, true);

                        if (!result)
                        {
                            await _notification.ShowError("Could not connect to the specified network. Please check your password.");
                            await network.Forget();
                        }

                        await RefreshAvailableWiFiNetworks();
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    result = await network.Connect(auth, false);
                    await RefreshAvailableWiFiNetworks();
                }
            }
            else
            {
                auth.Password = password;
                result = await network.Connect(auth, true);
                await RefreshAvailableWiFiNetworks();
            }

            if (result)
            {
                OnConnectionStateChanged(true);
                var settings = SettingsManager.Default.GetOrCreate<PPCSettings>();
                settings.AutoConnectWiFiName = network.AutoConnect ? network.Name : null;
                settings.AutoConnectWiFiPassword = _cryptographer.Encrypt(auth.Password);
                settings.Save();
                _connectedNetwork = network;
            }

            return result;
        }

        /// <summary>
        /// Disconnects the specified network.
        /// </summary>
        /// <param name="network">The network.</param>
        /// <returns></returns>
        public void Disconnect(WiFiNetwork network)
        {
            Task.Factory.StartNew(() =>
            {
                var settings = SettingsManager.Default.GetOrCreate<PPCSettings>();
                settings.AutoConnectWiFiName = null;
                settings.AutoConnectWiFiPassword = null;
                settings.Save();
                network.AutoConnect = false;
                network.Disconnect().Wait();
                RefreshAvailableWiFiNetworks().Wait();
                OnConnectionStateChanged(false);
            });
        }

        /// <summary>
        /// Called when the connection state has been changed
        /// </summary>
        /// <param name="connected">if set to <c>true</c> [connected].</param>
        protected virtual void OnConnectionStateChanged(bool connected)
        {
            if (!connected)
            {
                _connectedNetwork = null;
            }
            IsConnected = connected;
            ConnectionStateChanged?.Invoke(this, new ConnectionStateEventArgs() { IsConnected = connected });
        }
    }
}