Release 4.0.0-preview1-00051
[platform/core/csapi/tizenfx.git] / src / Tizen.Network.WiFi / Tizen.Network.WiFi / WiFiAP.cs
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 using System;
18 using System.Threading.Tasks;
19 using System.Collections.Generic;
20
21 namespace Tizen.Network.WiFi
22 {
23     /// <summary>
24     /// A class for managing the network information of the access point(AP).
25     /// </summary>
26     /// <since_tizen> 3 </since_tizen>
27     public class WiFiAP : IDisposable
28     {
29         private IntPtr _apHandle = IntPtr.Zero;
30         private Dictionary<IntPtr, Interop.WiFi.VoidCallback> _callback_map = new Dictionary<IntPtr, Interop.WiFi.VoidCallback>();
31         private static Dictionary<IntPtr, Interop.WiFi.VoidCallback> s_callbackMap = new Dictionary<IntPtr, Interop.WiFi.VoidCallback>();
32         private int _requestId = 0;
33         private static int s_requestId = 0;
34         private WiFiNetwork _network;
35         private WiFiSecurity _security;
36         private bool _disposed = false;
37
38         /// <summary>
39         /// The network information of the access point(AP).
40         /// </summary>
41         /// <since_tizen> 3 </since_tizen>
42         /// <value>WiFiNetwork instance containing network information of AP.</value>
43         public WiFiNetwork NetworkInformation
44         {
45             get
46             {
47                 return _network;
48             }
49         }
50
51         /// <summary>
52         /// The security information of the access point(AP).
53         /// </summary>
54         /// <since_tizen> 3 </since_tizen>
55         /// <value>WiFiSecurity instance containing security information of AP.</value>
56         public WiFiSecurity SecurityInformation
57         {
58             get
59             {
60                 return _security;
61             }
62         }
63
64         internal WiFiAP(IntPtr handle)
65         {
66             Log.Debug(Globals.LogTag, "New WiFiAP. Handle: " + handle);
67             _apHandle = handle;
68             Initialize();
69         }
70
71         /// <summary>
72         /// Creates an object for the access point.
73         /// </summary>
74         /// <since_tizen> 3 </since_tizen>
75         /// <param name="essid">The Extended Service Set Identifier of the access point.</param>
76         /// <feature>http://tizen.org/feature/network.wifi</feature>
77         /// <privilege>http://tizen.org/privilege/network.get</privilege>
78         /// <exception cref="NotSupportedException">Thrown when WiFi is not supported.</exception>
79         /// <exception cref="UnauthorizedAccessException">Thrown when permission is denied.</exception>
80         /// <exception cref="ArgumentNullException">Thrown when Essid is passed as null.</exception>
81         /// <exception cref="ArgumentException">Thrown when it is failed due to an invalid parameter.</exception>
82         /// <exception cref="OutOfMemoryException">Thrown when the system is out of memory.</exception>
83         /// <exception cref="InvalidOperationException">Thrown when it is failed due to invalid operation.</exception>
84         public WiFiAP(string essid)
85         {
86             Log.Debug(Globals.LogTag, "New WiFiAP. Essid: " + essid);
87             createHandle(essid, true);
88             Initialize();
89         }
90
91         /// <summary>
92         /// Creates an object for the hidden access point.
93         /// </summary>
94         /// <since_tizen> 3 </since_tizen>
95         /// <param name="essid">The Extended Service Set Identifier of the access point.</param>
96         /// <param name="hidden">The value to set hidden AP</param>
97         /// <feature>http://tizen.org/feature/network.wifi</feature>
98         /// <privilege>http://tizen.org/privilege/network.get</privilege>
99         /// <exception cref="NotSupportedException">Thrown when WiFi is not supported.</exception>
100         /// <exception cref="UnauthorizedAccessException">Thrown when permission is denied.</exception>
101         /// <exception cref="ArgumentNullException">Thrown when Essid is passed as null.</exception>
102         /// <exception cref="ArgumentException">Thrown when it is failed due to an invalid parameter.</exception>
103         /// <exception cref="OutOfMemoryException">Thrown when the system is out of memory.</exception>
104         /// <exception cref="InvalidOperationException">Thrown when it is failed due to invalid operation.</exception>
105         public WiFiAP(string essid, bool hidden)
106         {
107             createHandle(essid, hidden);
108             Initialize();
109         }
110
111         ~WiFiAP()
112         {
113             Dispose(false);
114         }
115
116         /// <summary>
117         /// A method to destroy the managed WiFiAP objects.
118         /// </summary>
119         /// <since_tizen> 3 </since_tizen>
120         public void Dispose()
121         {
122             Dispose(true);
123             GC.SuppressFinalize(this);
124         }
125
126         private void Dispose(bool disposing)
127         {
128             if (_disposed)
129                 return;
130
131             if (disposing)
132             {
133                 Interop.WiFi.AP.Destroy(_apHandle);
134                 _apHandle = IntPtr.Zero;
135             }
136             _disposed = true;
137         }
138
139         private void createHandle(string id, bool hidden)
140         {
141             int ret = -1;
142             if (id == null)
143             {
144                 throw new ArgumentNullException("Essid is null");
145             }
146
147             if (hidden)
148             {
149                 ret = Interop.WiFi.AP.CreateHiddenAP(WiFiManagerImpl.Instance.GetSafeHandle(), id, out _apHandle);
150             }
151
152             else
153             {
154                 ret = Interop.WiFi.AP.Create(WiFiManagerImpl.Instance.GetSafeHandle(), id, out _apHandle);
155             }
156
157             if (ret != (int)WiFiError.None)
158             {
159                 Log.Error(Globals.LogTag, "Failed to create handle, Error - " + (WiFiError)ret);
160                 WiFiErrorFactory.ThrowWiFiException(ret, WiFiManagerImpl.Instance.GetSafeHandle().DangerousGetHandle());
161             }
162         }
163
164         private void Initialize()
165         {
166             Interop.WiFi.SafeWiFiAPHandle apHandle = new Interop.WiFi.SafeWiFiAPHandle(_apHandle);
167             _network = new WiFiNetwork(apHandle);
168             _security = new WiFiSecurity(apHandle);
169         }
170
171         /// <summary>
172         /// Refreshes the access point information.
173         /// </summary>
174         /// <since_tizen> 3 </since_tizen>
175         /// <feature>http://tizen.org/feature/network.wifi</feature>
176         /// <privilege>http://tizen.org/privilege/network.get</privilege>
177         /// <exception cref="NotSupportedException">Thrown when WiFi is not supported.</exception>
178         /// <exception cref="UnauthorizedAccessException">Thrown when permission is denied.</exception>
179         /// <exception cref="ObjectDisposedException">Thrown when object instance is disposed or released.</exception>
180         /// <exception cref="ArgumentException">Thrown when method is failed due to an invalid parameter.</exception>
181         /// <exception cref="InvalidOperationException">Thrown when the method failed due to invalid operation.</exception>
182         public void Refresh()
183         {
184             Log.Debug(Globals.LogTag, "Refresh");
185             if (_disposed)
186             {
187                 throw new ObjectDisposedException("Invalid AP instance (Object may have been disposed or released)");
188             }
189             int ret = Interop.WiFi.AP.Refresh(_apHandle);
190             if (ret != (int)WiFiError.None)
191             {
192                 Log.Error(Globals.LogTag, "Failed to refresh ap handle, Error - " + (WiFiError)ret);
193                 WiFiErrorFactory.ThrowWiFiException(ret, _apHandle, "http://tizen.org/privilege/network.get");
194             }
195         }
196
197         /// <summary>
198         /// Connects the access point asynchronously.
199         /// </summary>
200         /// <since_tizen> 3 </since_tizen>
201         /// <returns> A task indicating whether the Connect method is done or not.</returns>
202         /// <feature>http://tizen.org/feature/network.wifi</feature>
203         /// <privilege>http://tizen.org/privilege/network.set</privilege>
204         /// <privilege>http://tizen.org/privilege/network.get</privilege>
205         /// <exception cref="NotSupportedException">Thrown when WiFi is not supported.</exception>
206         /// <exception cref="UnauthorizedAccessException">Thrown when permission is denied.</exception>
207         /// <exception cref="ObjectDisposedException">Thrown when object instance is disposed or released.</exception>
208         /// <exception cref="OutOfMemoryException">Thrown when the system is out of memory.</exception>
209         /// <exception cref="ArgumentException">Thrown when method is failed due to an invalid parameter.</exception>
210         /// <exception cref="InvalidOperationException">Thrown when the method failed due to invalid operation.</exception>
211         public Task ConnectAsync()
212         {
213             Log.Debug(Globals.LogTag, "ConnectAsync");
214             if (_disposed)
215             {
216                 throw new ObjectDisposedException("Invalid AP instance (Object may have been disposed or released)");
217             }
218             TaskCompletionSource<bool> task = new TaskCompletionSource<bool>();
219             IntPtr id;
220             lock (_callback_map)
221             {
222                 id = (IntPtr)_requestId++;
223                 _callback_map[id] = (error, key) =>
224                 {
225                     Log.Debug(Globals.LogTag, "Connecting finished : " + (WiFiError)error);
226                     if (error != (int)WiFiError.None)
227                     {
228                         Log.Error(Globals.LogTag, "Error occurs during WiFi connecting, " + (WiFiError)error);
229                         task.SetException(new InvalidOperationException("Error occurs during WiFi connecting, " + (WiFiError)error));
230                     }
231                     task.SetResult(true);
232                     lock (_callback_map)
233                     {
234                         _callback_map.Remove(key);
235                     }
236                 };
237             }
238
239             int ret = Interop.WiFi.Connect(WiFiManagerImpl.Instance.GetSafeHandle(), _apHandle, _callback_map[id], id);
240             if (ret != (int)WiFiError.None)
241             {
242                 Log.Error(Globals.LogTag, "Failed to connect wifi, Error - " + (WiFiError)ret);
243                 WiFiErrorFactory.ThrowWiFiException(ret, WiFiManagerImpl.Instance.GetSafeHandle().DangerousGetHandle(), _apHandle);
244             }
245
246             return task.Task;
247         }
248
249         /// <summary>
250         /// Connects the access point with WPS asynchronously.
251         /// </summary>
252         /// <since_tizen> 3 </since_tizen>
253         /// <param name="info">A WpsInfo instance which is of type WpsPbcInfo or WpsPinInfo.</param>
254         /// <returns>A task indicating whether the ConnectWps method is done or not.</returns>
255         /// <feature>http://tizen.org/feature/network.wifi</feature>
256         /// <privilege>http://tizen.org/privilege/network.profile</privilege>
257         /// <privilege>http://tizen.org/privilege/network.get</privilege>
258         /// <exception cref="NotSupportedException">Thrown when WiFi is not supported.</exception>
259         /// <exception cref="UnauthorizedAccessException">Thrown when permission is denied.</exception>
260         /// <exception cref="ObjectDisposedException">Thrown when object instance is disposed or released.</exception>
261         /// <exception cref="ArgumentNullException">Thrown when WpsPinInfo object is constructed with null pin.</exception>
262         /// <exception cref="ArgumentOutOfRangeException">Thrown when WpsPinInfo object is constructed with pin which is an empty string or more than 7 characters.</exception>
263         /// <exception cref="OutOfMemoryException">Thrown when the system is out of memory.</exception>
264         /// <exception cref="ArgumentException">Thrown when method is failed due to an invalid parameter.</exception>
265         /// <exception cref="InvalidOperationException">Thrown when the method failed due to invalid operation.</exception>
266         public Task ConnectWpsAsync(WpsInfo info)
267         {
268             Log.Debug(Globals.LogTag, "ConnectWpsAsync");
269             if (_disposed)
270             {
271                 throw new ObjectDisposedException("Invalid AP instance (Object may have been disposed or released)");
272             }
273             TaskCompletionSource<bool> task = new TaskCompletionSource<bool>();
274             IntPtr id;
275             lock (_callback_map)
276             {
277                 id = (IntPtr)_requestId++;
278                 _callback_map[id] = (error, key) =>
279                 {
280                     Log.Debug(Globals.LogTag, "Connecting by WPS finished");
281                     if (error != (int)WiFiError.None)
282                     {
283                         Log.Error(Globals.LogTag, "Error occurs during WiFi connecting, " + (WiFiError)error);
284                         task.SetException(new InvalidOperationException("Error occurs during WiFi connecting, " + (WiFiError)error));
285                     }
286                     task.SetResult(true);
287                     lock (_callback_map)
288                     {
289                         _callback_map.Remove(key);
290                     }
291                 };
292             }
293
294             int ret = -1;
295             if (info.GetType() == typeof(WpsPbcInfo))
296             {
297                 ret = Interop.WiFi.ConnectByWpsPbc(WiFiManagerImpl.Instance.GetSafeHandle(), _apHandle, _callback_map[id], id);
298             }
299
300             else if (info.GetType() == typeof(WpsPinInfo))
301             {
302                 WpsPinInfo pinInfo = (WpsPinInfo)info;
303                 if (pinInfo.GetWpsPin() == null)
304                 {
305                     throw new ArgumentNullException("Wps pin should not be null");
306                 }
307
308                 if (pinInfo.GetWpsPin().Length == 0 || pinInfo.GetWpsPin().Length > 8)
309                 {
310                     throw new ArgumentOutOfRangeException("Wps pin should not be empty or more than 7 characters");
311                 }
312
313                 ret = Interop.WiFi.ConnectByWpsPin(WiFiManagerImpl.Instance.GetSafeHandle(), _apHandle, pinInfo.GetWpsPin(), _callback_map[id], id);
314             }
315
316             if (ret != (int)WiFiError.None)
317             {
318                 Log.Error(Globals.LogTag, "Failed to connect wifi, Error - " + (WiFiError)ret);
319                 WiFiErrorFactory.ThrowWiFiException(ret, WiFiManagerImpl.Instance.GetSafeHandle().DangerousGetHandle(), _apHandle);
320             }
321
322             return task.Task;
323         }
324
325         /// <summary>
326         /// Connects the access point with WPS without ssid asynchronously.
327         /// </summary>
328         /// <since_tizen> 3 </since_tizen>
329         /// <param name="info">A WpsInfo instance which is of type WpsPbcInfo or WpsPinInfo.</param>
330         /// <returns>A task which contains Connected access point information.</returns>
331         /// <remarks>
332         /// If WpsPinInfo is used, its object has to be constructed with a pin which must be 4 or 8 characters long.
333         /// </remarks>
334         /// <feature>http://tizen.org/feature/network.wifi</feature>
335         /// <privilege>http://tizen.org/privilege/network.set</privilege>
336         /// <privilege>http://tizen.org/privilege/network.get</privilege>
337         /// <privilege>http://tizen.org/privilege/network.profile</privilege>
338         /// <exception cref="NotSupportedException">Thrown when WiFi is not supported.</exception>
339         /// <exception cref="UnauthorizedAccessException">Thrown when permission is denied.</exception>
340         /// <exception cref="ArgumentNullException">Thrown when WpsPinInfo object is constructed with null pin.</exception>
341         /// <exception cref="ArgumentOutOfRangeException">Thrown when WpsPinInfo object is constructed with pin which is not of 4 or 8 characters long.</exception>
342         /// <exception cref="OutOfMemoryException">Thrown when the system is out of memory.</exception>
343         /// <exception cref="ArgumentException">Thrown when method is failed due to an invalid parameter.</exception>
344         /// <exception cref="InvalidOperationException">Thrown when the method failed due to invalid operation.</exception>
345         public static Task<WiFiAP> ConnectWpsWithoutSsidAsync(WpsInfo info)
346         {
347             TaskCompletionSource<WiFiAP> task = new TaskCompletionSource<WiFiAP>();
348             IntPtr id;
349             lock (s_callbackMap)
350             {
351                 id = (IntPtr)s_requestId++;
352                 s_callbackMap[id] = (error, key) =>
353                 {
354                     Log.Debug(Globals.LogTag, "Connecting by WPS finished");
355                     if (error != (int)WiFiError.None)
356                     {
357                         Log.Error(Globals.LogTag, "Error occurs during WiFi connecting, " + (WiFiError)error);
358                         task.SetException(new InvalidOperationException("Error occurs during WiFi connecting, " + (WiFiError)error));
359                     }
360                     WiFiAP ap = WiFiManagerImpl.Instance.GetConnectedAP();
361                     task.SetResult(ap);
362                     lock (s_callbackMap)
363                     {
364                         s_callbackMap.Remove(key);
365                     }
366                 };
367             }
368
369             int ret = -1;
370             if (info.GetType() == typeof(WpsPbcInfo))
371             {
372                 ret = Interop.WiFi.ConnectByWpsPbcWithoutSsid(WiFiManagerImpl.Instance.GetSafeHandle(), s_callbackMap[id], id);   
373             }
374
375             else if (info.GetType() == typeof(WpsPinInfo))
376             {
377                 WpsPinInfo pinInfo = (WpsPinInfo)info;
378                 if (pinInfo.GetWpsPin() == null)
379                 {
380                     throw new ArgumentNullException("Wps pin should not be null");
381                 }
382
383                 if (pinInfo.GetWpsPin().Length != 4 && pinInfo.GetWpsPin().Length != 8)
384                 {
385                     throw new ArgumentOutOfRangeException("Wps pin should be of 4 or 8 characters long");
386                 }
387
388                 ret = Interop.WiFi.ConnectByWpsPinWithoutSsid(WiFiManagerImpl.Instance.GetSafeHandle(), pinInfo.GetWpsPin(), s_callbackMap[id], id);
389             }
390
391             if (ret != (int)WiFiError.None)
392             {
393                 Log.Error(Globals.LogTag, "Failed to connect wifi, Error - " + (WiFiError)ret);
394                 WiFiErrorFactory.ThrowWiFiException(ret, WiFiManagerImpl.Instance.GetSafeHandle().DangerousGetHandle());
395             }
396
397             return task.Task;
398         }
399
400         /// <summary>
401         /// Disconnects the access point asynchronously.
402         /// </summary>
403         /// <since_tizen> 3 </since_tizen>
404         /// <returns> A task indicating whether the Disconnect method is done or not.</returns>
405         /// <feature>http://tizen.org/feature/network.wifi</feature>
406         /// <privilege>http://tizen.org/privilege/network.set</privilege>
407         /// <privilege>http://tizen.org/privilege/network.get</privilege>
408         /// <exception cref="NotSupportedException">Thrown when WiFi is not supported.</exception>
409         /// <exception cref="UnauthorizedAccessException">Thrown when permission is denied.</exception>
410         /// <exception cref="ObjectDisposedException">Thrown when object instance is disposed or released.</exception>
411         /// <exception cref="OutOfMemoryException">Thrown when the system is out of memory.</exception>
412         /// <exception cref="ArgumentException">Thrown when method is failed due to an invalid parameter.</exception>
413         /// <exception cref="InvalidOperationException">Thrown when the method failed due to invalid operation.</exception>
414         public Task DisconnectAsync()
415         {
416             Log.Debug(Globals.LogTag, "DisconnectAsync");
417             if (_disposed)
418             {
419                 throw new ObjectDisposedException("Invalid AP instance (Object may have been disposed or released)");
420             }
421             TaskCompletionSource<bool> task = new TaskCompletionSource<bool>();
422             IntPtr id;
423             lock (_callback_map)
424             {
425                 id = (IntPtr)_requestId++;
426                 _callback_map[id] = (error, key) =>
427                 {
428                     Log.Debug(Globals.LogTag, "Disconnecting finished");
429                     if (error != (int)WiFiError.None)
430                     {
431                         Log.Error(Globals.LogTag, "Error occurs during WiFi disconnecting, " + (WiFiError)error);
432                         task.SetException(new InvalidOperationException("Error occurs during WiFi disconnecting, " + (WiFiError)error));
433                     }
434                     task.SetResult(true);
435                     lock (_callback_map)
436                     {
437                         _callback_map.Remove(key);
438                     }
439                 };
440             }
441             int ret = Interop.WiFi.Disconnect(WiFiManagerImpl.Instance.GetSafeHandle(), _apHandle, _callback_map[id], id);
442             if (ret != (int)WiFiError.None)
443             {
444                 Log.Error(Globals.LogTag, "Failed to disconnect wifi, Error - " + (WiFiError)ret);
445                 WiFiErrorFactory.ThrowWiFiException(ret, WiFiManagerImpl.Instance.GetSafeHandle().DangerousGetHandle(), _apHandle);
446             }
447             return task.Task;
448         }
449
450         /// <summary>
451         /// Deletes the information of stored access point and disconnects it when it is connected.<br>
452         /// If an AP is connected, then connection information will be stored. This information is used when a connection to that AP is established automatically.
453         /// </summary>
454         /// <since_tizen> 3 </since_tizen>
455         /// <feature>http://tizen.org/feature/network.wifi</feature>
456         /// <privilege>http://tizen.org/privilege/network.profile</privilege>
457         /// <privilege>http://tizen.org/privilege/network.get</privilege>
458         /// <exception cref="NotSupportedException">Thrown when WiFi is not supported.</exception>
459         /// <exception cref="UnauthorizedAccessException">Thrown when permission is denied.</exception>
460         /// <exception cref="ObjectDisposedException">Thrown when object instance is disposed or released.</exception>
461         /// <exception cref="OutOfMemoryException">Thrown when the system is out of memory.</exception>
462         /// <exception cref="ArgumentException">Thrown when method is failed due to an invalid parameter.</exception>
463         /// <exception cref="InvalidOperationException">Thrown when the method failed due to invalid operation.</exception>
464         public void ForgetAP()
465         {
466             Log.Debug(Globals.LogTag, "ForgetAP");
467             if (_disposed)
468             {
469                 throw new ObjectDisposedException("Invalid AP instance (Object may have been disposed or released)");
470             }
471             int ret = Interop.WiFi.RemoveAP(WiFiManagerImpl.Instance.GetSafeHandle(), _apHandle);
472             if (ret != (int)WiFiError.None)
473             {
474                 Log.Error(Globals.LogTag, "Failed to forget AP, Error - " + (WiFiError)ret);
475                 WiFiErrorFactory.ThrowWiFiException(ret, WiFiManagerImpl.Instance.GetSafeHandle().DangerousGetHandle(), _apHandle);
476             }
477         }
478     }
479
480     /// <summary>
481     /// An abstract class which is used to represent WPS information of access point.
482     /// </summary>
483     /// <since_tizen> 3 </since_tizen>
484     public abstract class WpsInfo
485     {
486     }
487
488     /// <summary>
489     /// A class which is used to represent WPS PBC information of access point.
490     /// </summary>
491     public class WpsPbcInfo : WpsInfo
492     {
493     }
494
495     /// <summary>
496     /// A class which is used to represent WPS PIN information of access point.
497     /// </summary>
498     public class WpsPinInfo : WpsInfo
499     {
500         private string _pin;
501
502         private WpsPinInfo()
503         {
504         }
505
506         /// <summary>
507         /// A public constructor which instantiates WpsPinInfo class with the given pin.
508         /// </summary>
509         /// <since_tizen> 3 </since_tizen>
510         /// <param name="pin">WPS Pin of the access point.</param>
511         /// <remarks>
512         /// Pin should not be null or empty. It should be of less than 8 characters.
513         /// </remarks>
514         public WpsPinInfo(string pin)
515         {
516             _pin = pin;
517         }
518
519         internal string GetWpsPin()
520         {
521             return _pin;
522         }
523     }
524 }