Release 4.0.0-preview1-00051
[platform/core/csapi/tizenfx.git] / src / Tizen.Convergence / Tizen.Convergence / InternalDeviceFinder.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 Tizen;
19 using System.Threading;
20 using System.Threading.Tasks;
21 using System.ComponentModel;
22
23 namespace Tizen.Convergence
24 {
25     /// <summary>
26     /// DeviceFinder provides API to find all nearby Tizen D2D convergence compliant devices
27     /// </summary>
28     [EditorBrowsable(EditorBrowsableState.Never)]
29     public class InternalDeviceFinder : IDisposable
30     {
31         internal Interop.Internal.ConvManagerHandle _convManagerHandle;
32
33         /// <summary>
34         /// The constructor
35         /// </summary>
36         /// <feature>http://tizen.org/feature/convergence.d2d</feature>
37         /// <exception cref="NotSupportedException">Thrown if the required feature is not supported.</exception>
38         public InternalDeviceFinder()
39         {
40             int ret = Interop.Internal.ConvManager.ConvCreate(out _convManagerHandle);
41             if (ret != (int)ConvErrorCode.None)
42             {
43                 Log.Error(ErrorFactory.LogTag, "Failed to create conv manager handle");
44                 throw ErrorFactory.GetException(ret);
45             }
46
47         }
48
49         /// <summary>
50         /// DeviceFound event is triggered when a device is found during discovery procedure
51         /// </summary>
52         public event EventHandler<InternalDeviceFoundEventArgs> DeviceFound;
53
54         /// <summary>
55         /// Starts the discovery of nearby devices
56         /// </summary>
57         /// <param name="timeOut">Seconds for discovery timeout. 0 will use default timeout value</param>
58         /// <param name="cancellationToken">Cancellation token required to cancel the current discovery</param>
59         /// <privilege>http://tizen.org/privilege/internet</privilege>
60         /// <privilege>http://tizen.org/privilege/bluetooth</privilege>
61         /// <feature>http://tizen.org/feature/convergence.d2d</feature>
62         /// <exception cref="NotSupportedException">Thrown if the required feature is not supported.</exception>
63         /// <exception cref="InvalidOperationException">Thrown when the request is not supported as per Tizen D2D convergence specification </exception>
64         /// <seealso cref="DeviceFound"> Devices found are delivered through this event</seealso>
65         /// <returns>Task with discovery result</returns>
66         public async Task StartFindingAsync(int timeOut, CancellationToken cancellationToken = default(CancellationToken))
67         {
68             var task = new TaskCompletionSource<bool>();
69             Interop.Internal.ConvManager.ConvDiscoveryCallback discoveredCb = (IntPtr deviceHandle, Interop.Internal.ConvDiscoveryResult result, IntPtr userData) =>
70             {
71                 Log.Debug(ErrorFactory.LogTag, "discovery callback called with result:[" + result + "]");
72                 switch (result)
73                 {
74                     case Interop.Internal.ConvDiscoveryResult.Success:
75                         {
76                             InternalDevice device = new InternalDevice(deviceHandle);
77                             InternalDeviceFoundEventArgs deviceFoundEventArgs = new InternalDeviceFoundEventArgs()
78                             {
79                                 Device = device
80                             };
81                             DeviceFound?.Invoke(this, deviceFoundEventArgs);
82                             break;
83                         }
84                     case Interop.Internal.ConvDiscoveryResult.Error:
85                         {
86                             task.TrySetException(new InvalidOperationException("Discovery error occured"));
87                             break;
88                         }
89                     case Interop.Internal.ConvDiscoveryResult.Lost:
90                         {
91                             task.TrySetException(new InvalidOperationException("Discovery Lost"));
92                             break;
93                         }
94                     case Interop.Internal.ConvDiscoveryResult.Finished:
95                         {
96                             Log.Debug(ErrorFactory.LogTag, "discovery process finished");
97                             task.TrySetResult(true);
98                             break;
99                         }
100                 }
101             };
102             int ret = Interop.Internal.ConvManager.ConvDiscoveryStart(_convManagerHandle, timeOut, discoveredCb, IntPtr.Zero);
103             if (ret != (int)ConvErrorCode.None)
104             {
105                 Log.Error(ErrorFactory.LogTag, "Failed to start finding devices");
106                 throw ErrorFactory.GetException(ret);
107             }
108
109             if (cancellationToken != CancellationToken.None)
110             {
111                 cancellationToken.Register(() =>
112                 {
113                     int error = Interop.Internal.ConvManager.ConvDiscoveryStop(_convManagerHandle);
114                     if (error != (int)ConvErrorCode.None)
115                     {
116                         Log.Error(ErrorFactory.LogTag, "Failed to stop finding devices" + Internals.Errors.ErrorFacts.GetErrorMessage(error));
117                         throw ErrorFactory.GetException(error);
118                     }
119                     task.TrySetCanceled();
120                 });
121             }
122             await task.Task;
123         }
124
125         /// <summary>
126         /// The dispose method
127         /// </summary>
128         public void Dispose()
129         {
130             _convManagerHandle.Dispose();
131         }
132     }
133 }