Fixed issues while testing TCT
[platform/core/csapi/tizenfx.git] / src / Tizen.Network.IoTConnectivity / Tizen.Network.IoTConnectivity / RemoteResource.cs
1 /// Copyright 2016 by Samsung Electronics, Inc.,
2 ///
3 /// This software is the confidential and proprietary information
4 /// of Samsung Electronics, Inc. ("Confidential Information"). You
5 /// shall not disclose such Confidential Information and shall use
6 /// it only in accordance with the terms of the license agreement
7 /// you entered into with Samsung.
8
9 using System;
10 using System.Collections.Generic;
11 using System.Net;
12 using System.Runtime.InteropServices;
13 using System.Threading.Tasks;
14
15 namespace Tizen.Network.IoTConnectivity
16 {
17     /// <summary>
18     /// RemoteResource class
19     /// </summary>
20     public class RemoteResource : IDisposable
21     {
22         internal const int TimeOutMax = 3600;
23         internal IntPtr _remoteResourceHandle = IntPtr.Zero;
24
25         private bool _disposed = false;
26         private bool _cacheEnabled = false;
27         private ResourceOptions _options;
28
29         private int _responseCallbackId = 1;
30         private static Dictionary<IntPtr, Interop.IoTConnectivity.Client.RemoteResource.ResponseCallback> _responseCallbacksMap = new Dictionary<IntPtr, Interop.IoTConnectivity.Client.RemoteResource.ResponseCallback>();
31
32         private Interop.IoTConnectivity.Client.RemoteResource.CachedRepresentationChangedCallback _cacheUpdatedCallback;
33         private Interop.IoTConnectivity.Client.RemoteResource.StateChangedCallback _stateChangedCallback;
34         private Interop.IoTConnectivity.Client.RemoteResource.ObserveCallback _observeCallback;
35
36         private EventHandler<StateChangedEventArgs> _stateChangedEventHandler;
37
38         /// <summary>
39         /// Constructor
40         /// </summary>
41         public RemoteResource(string hostAddress, string uriPath, ResourcePolicy policy, ResourceTypes resourceTypes, ResourceInterfaces resourceInterfaces)
42         {
43             if (hostAddress == null || uriPath == null || resourceTypes == null || resourceInterfaces == null)
44             {
45                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Invalid parameters");
46                 throw new ArgumentException("Invalid parameter");
47             }
48
49             HostAddress = hostAddress;
50             UriPath = uriPath;
51             Policy = policy;
52             Types = new List<string>(resourceTypes);
53             Interfaces = new List<string>(resourceInterfaces);
54             DeviceId = null;
55
56             CreateRemoteResource(resourceTypes._resourceTypeHandle, resourceInterfaces.ResourceInterfacesHandle);
57         }
58
59         internal RemoteResource(IntPtr handleToClone)
60         {
61             int ret = Interop.IoTConnectivity.Client.RemoteResource.Clone(handleToClone, out _remoteResourceHandle);
62             if (ret != (int)IoTConnectivityError.None)
63             {
64                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Faled to clone");
65                 throw IoTConnectivityErrorFactory.GetException(ret);
66             }
67             SetRemoteResource();
68         }
69
70         ~RemoteResource()
71         {
72             Dispose(false);
73         }
74
75         /// <summary>
76         /// Event that is called to cache resource attribute's
77         /// </summary>
78         public event EventHandler<CacheUpdatedEventArgs> CacheUpdated;
79
80         /// <summary>
81         /// Observe event on the resource
82         /// </summary>
83         public event EventHandler<ObserverNotifiedEventArgs> ObserverNotified;
84
85         /// <summary>
86         /// Event that is called when remote resource's state are changed
87         /// </summary>
88         public event EventHandler<StateChangedEventArgs> StateChanged
89         {
90             add
91             {
92                 if (_stateChangedEventHandler == null)
93                 {
94                     RegisterStateChangedEvent();
95                 }
96                 _stateChangedEventHandler += value;
97             }
98             remove
99             {
100                 _stateChangedEventHandler -= value;
101                 if (_stateChangedEventHandler == null)
102                 {
103                     UnregisterStateChangedEvent();
104                 }
105             }
106         }
107
108         /// <summary>
109         /// The host address of the resource
110         /// </summary>
111         public string HostAddress { get; private set; }
112
113         /// <summary>
114         /// The URI path of the resource
115         /// </summary>
116         public string UriPath { get; private set; }
117
118         /// <summary>
119         /// The resource types of the remote resource
120         /// </summary>
121         public IEnumerable<string> Types { get; private set; }
122
123         /// <summary>
124         /// The interfaces of the resource
125         /// </summary>
126         public IEnumerable<string> Interfaces { get; private set; }
127
128         /// <summary>
129         /// The policy of the resource
130         /// </summary>
131         public ResourcePolicy Policy { get; private set; }
132
133         /// <summary>
134         /// The device name of the remote resource
135         /// </summary>
136         public string DeviceName { get; private set; }
137
138         /// <summary>
139         /// The header options of the resource
140         /// </summary>
141         public ResourceOptions Options
142         {
143             get
144             {
145                 return _options;
146             }
147             set
148             {
149                 _options = value;
150                 if (value != null)
151                 {
152                     int ret = Interop.IoTConnectivity.Client.RemoteResource.SetOptions(_remoteResourceHandle, value._resourceOptionsHandle);
153                     if (ret != (int)IoTConnectivityError.None)
154                     {
155                         Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set options");
156                         throw IoTConnectivityErrorFactory.GetException(ret);
157                     }
158                 }
159             }
160         }
161
162         /// <summary>
163         /// Cache enabled property
164         /// </summary>
165         public bool CacheEnabled
166         {
167             get
168             {
169                 return _cacheEnabled;
170             }
171             set
172             {
173                 if (_cacheEnabled != value)
174                 {
175                     _cacheEnabled = value;
176                     HandleCachePolicyChanged();
177                 }
178             }
179         }
180
181         /// <summary>
182         /// Time interval of monitoring and caching API
183         /// </summary>
184         public int TimeInterval
185         {
186             get
187             {
188                 int interval;
189                 int ret = Interop.IoTConnectivity.Client.RemoteResource.GetTimeInterval(out interval);
190                 if (ret != (int)IoTConnectivityError.None)
191                 {
192                     Log.Warn(IoTConnectivityErrorFactory.LogTag, "Failed to get time interval");
193                     return 0;
194                 }
195                 return interval;
196             }
197             set
198             {
199                 int ret = (int)IoTConnectivityError.InvalidParameter;
200                 if (value < TimeOutMax && value > 0)
201                 {
202                     ret = Interop.IoTConnectivity.Client.RemoteResource.SetTimeInterval(value);
203                 }
204                 if (ret != (int)IoTConnectivityError.None)
205                 {
206                     Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set time interval");
207                     throw IoTConnectivityErrorFactory.GetException(ret);
208                 }
209             }
210         }
211
212         /// <summary>
213         /// The device id of the resource
214         /// </summary>
215         public string DeviceId { get; private set; }
216
217         /// <summary>
218         /// Gets cached representation of the remote resource
219         /// </summary>
220         public Representation CachedRepresentation()
221         {
222             IntPtr handle;
223             int ret = Interop.IoTConnectivity.Client.RemoteResource.GetCachedRepresentation(_remoteResourceHandle, out handle);
224             if (ret != (int)IoTConnectivityError.None)
225             {
226                 Log.Warn(IoTConnectivityErrorFactory.LogTag, "Failed to get CachedRepresentation");
227                 return null;
228             }
229
230             Representation representation = new Representation(handle);
231             return representation;
232         }
233
234         /// <summary>
235         /// Registers the observe callback on the resource
236         /// </summary>
237         /// <param name="policy">The type to specify how client wants to observe</param>
238         /// <param name="query">The ResourceQuery to send to server</param>
239         public void StartObserving(ObservePolicy policy, ResourceQuery query = null)
240         {
241             _observeCallback = (IntPtr resource, int err, int sequenceNumber, IntPtr response, IntPtr userData) =>
242             {
243                 int result;
244                 IntPtr representationHandle;
245                 int ret = Interop.IoTConnectivity.Server.Response.GetResult(response, out result);
246                 if (ret != (int)IoTConnectivityError.None)
247                 {
248                     Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get result");
249                     return;
250                 }
251
252                 ret = Interop.IoTConnectivity.Server.Response.GetRepresentation(response, out representationHandle);
253                 if (ret != (int)IoTConnectivityError.None)
254                 {
255                     Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get representation");
256                     return;
257                 }
258
259                 Representation repr = null;
260                 try
261                 {
262                     repr = new Representation(representationHandle);
263                 }
264                 catch (Exception exp)
265                 {
266                     Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new representation: " + exp.Message);
267                     return;
268                 }
269
270                 ObserverNotifiedEventArgs e = new ObserverNotifiedEventArgs()
271                 {
272                     Representation = repr,
273                     Result = (ResponseCode)result
274                 };
275                 ObserverNotified?.Invoke(null, e);
276             };
277
278             IntPtr queryHandle = IntPtr.Zero;
279             if (query != null)
280             {
281                 queryHandle = query._resourceQueryHandle;
282             }
283
284             int errCode = Interop.IoTConnectivity.Client.RemoteResource.RegisterObserve(_remoteResourceHandle, (int)policy, queryHandle, _observeCallback, IntPtr.Zero);
285             if (errCode != (int)IoTConnectivityError.None)
286             {
287                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to register observe callbacks");
288                 throw IoTConnectivityErrorFactory.GetException(errCode);
289             }
290         }
291
292         /// <summary>
293         /// Deregisters the observe callback on the resource
294         /// </summary>
295         public void StopObserving()
296         {
297             int ret = Interop.IoTConnectivity.Client.RemoteResource.DeregisterObserve(_remoteResourceHandle);
298             if (ret != (int)IoTConnectivityError.None)
299             {
300                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to deregister observe callbacks");
301                 throw IoTConnectivityErrorFactory.GetException(ret);
302             }
303         }
304
305         /// <summary>
306         /// Gets the attributes of a resource
307         /// </summary>
308         /// <param name="query">The ResourceQuery to send to server</param>
309         /// <returns></returns>
310         public async Task<RemoteResponse> GetAsync(ResourceQuery query = null)
311         {
312             TaskCompletionSource<RemoteResponse> tcsRemoteResponse = new TaskCompletionSource<RemoteResponse>();
313
314             IntPtr id = IntPtr.Zero;
315             lock (_responseCallbacksMap)
316             {
317                 id = (IntPtr)_responseCallbackId++;
318             }
319             _responseCallbacksMap[id] = (IntPtr resource, int err, int requestType, IntPtr responseHandle, IntPtr userData) =>
320             {
321                 IntPtr responseCallbackId = userData;
322                 lock(_responseCallbacksMap)
323                 {
324                     _responseCallbacksMap.Remove(responseCallbackId);
325                 }
326
327                 if (responseHandle != IntPtr.Zero)
328                 {
329                     try
330                     {
331                         tcsRemoteResponse.TrySetResult(GetRemoteResponse(responseHandle));
332                     }
333                     catch(Exception exp)
334                     {
335                         Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get RemoteResponse: ", exp.Message);
336                         tcsRemoteResponse.TrySetException(exp);
337                     }
338                 }
339                 else
340                 {
341                     tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.System));
342                 }
343             };
344
345             IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
346             int errCode = Interop.IoTConnectivity.Client.RemoteResource.Get(_remoteResourceHandle, queryHandle, _responseCallbacksMap[id], id);
347             if (errCode != (int)IoTConnectivityError.None)
348             {
349                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get resource attributes");
350                 tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException(errCode));
351             }
352             return await tcsRemoteResponse.Task;
353         }
354
355         /// <summary>
356         /// Puts the representation of a resource, asynchronously.
357         /// </summary>
358         /// <param name="representation">Resource representation</param>
359         /// <param name="query">The ResourceQuery to send to server</param>
360         /// <returns></returns>
361         public async Task<RemoteResponse> PutAsync(Representation representation, ResourceQuery query = null)
362         {
363             TaskCompletionSource<RemoteResponse> tcsRemoteResponse = new TaskCompletionSource<RemoteResponse>();
364
365             IntPtr id = IntPtr.Zero;
366             lock (_responseCallbacksMap)
367             {
368                 id = (IntPtr)_responseCallbackId++;
369             }
370             _responseCallbacksMap[id] = (IntPtr resource, int err, int requestType, IntPtr responseHandle, IntPtr userData) =>
371             {
372                 IntPtr responseCallbackId = userData;
373                 lock (_responseCallbacksMap)
374                 {
375                     _responseCallbacksMap.Remove(responseCallbackId);
376                 }
377
378                 if (responseHandle != IntPtr.Zero)
379                 {
380                     try
381                     {
382                         tcsRemoteResponse.TrySetResult(GetRemoteResponse(responseHandle));
383                     }
384                     catch (Exception exp)
385                     {
386                         Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get RemoteResponse: ", exp.Message);
387                         tcsRemoteResponse.TrySetException(exp);
388                     }
389                 }
390                 else
391                 {
392                     tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.System));
393                 }
394             };
395
396             IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
397             int errCode = Interop.IoTConnectivity.Client.RemoteResource.Put(_remoteResourceHandle, representation._representationHandle, queryHandle, _responseCallbacksMap[id], id);
398             if (errCode != (int)IoTConnectivityError.None)
399             {
400                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to put resource representation");
401                 tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException(errCode));
402             }
403             return await tcsRemoteResponse.Task;
404         }
405
406         /// <summary>
407         /// Post request on a resource
408         /// </summary>
409         /// <param name="representation">Resource representation</param>
410         /// <param name="query">The ResourceQuery to send to server</param>
411         /// <returns></returns>
412         public async Task<RemoteResponse> PostAsync(Representation representation, ResourceQuery query = null)
413         {
414             TaskCompletionSource<RemoteResponse> tcsRemoteResponse = new TaskCompletionSource<RemoteResponse>();
415
416             IntPtr id = IntPtr.Zero;
417             lock (_responseCallbacksMap)
418             {
419                 id = (IntPtr)_responseCallbackId++;
420             }
421             _responseCallbacksMap[id] = (IntPtr resource, int err, int requestType, IntPtr responseHandle, IntPtr userData) =>
422             {
423                 IntPtr responseCallbackId = userData;
424                 lock (_responseCallbacksMap)
425                 {
426                     _responseCallbacksMap.Remove(responseCallbackId);
427                 }
428
429                 if (responseHandle != IntPtr.Zero)
430                 {
431                     try
432                     {
433                         tcsRemoteResponse.TrySetResult(GetRemoteResponse(responseHandle));
434                     }
435                     catch (Exception exp)
436                     {
437                         Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get RemoteResponse: ", exp.Message);
438                         tcsRemoteResponse.TrySetException(exp);
439                     }
440                 }
441                 else
442                 {
443                     tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.System));
444                 }
445             };
446
447             IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
448             int errCode = Interop.IoTConnectivity.Client.RemoteResource.Post(_remoteResourceHandle, representation._representationHandle, queryHandle, _responseCallbacksMap[id], id);
449             if (errCode != (int)IoTConnectivityError.None)
450             {
451                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to post request");
452                 tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException(errCode));
453             }
454             return await tcsRemoteResponse.Task;
455         }
456
457         /// <summary>
458         /// Delete the resource
459         /// </summary>
460         /// <returns></returns>
461         public async Task<RemoteResponse> DeleteAsync()
462         {
463             TaskCompletionSource<RemoteResponse> tcsRemoteResponse = new TaskCompletionSource<RemoteResponse>();
464
465             IntPtr id = IntPtr.Zero;
466             lock (_responseCallbacksMap)
467             {
468                 id = (IntPtr)_responseCallbackId++;
469             }
470             _responseCallbacksMap[id] = (IntPtr resource, int err, int requestType, IntPtr responseHandle, IntPtr userData) =>
471             {
472                 IntPtr responseCallbackId = userData;
473                 lock (_responseCallbacksMap)
474                 {
475                     _responseCallbacksMap.Remove(responseCallbackId);
476                 }
477
478                 if (responseHandle != IntPtr.Zero)
479                 {
480                     try
481                     {
482                         tcsRemoteResponse.TrySetResult(GetRemoteResponse(responseHandle));
483                     }
484                     catch (Exception exp)
485                     {
486                         Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get RemoteResponse: ", exp.Message);
487                         tcsRemoteResponse.TrySetException(exp);
488                     }
489                 }
490                 else
491                 {
492                     tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.System));
493                 }
494             };
495
496             int errCode = Interop.IoTConnectivity.Client.RemoteResource.Delete(_remoteResourceHandle, _responseCallbacksMap[id], id);
497             if (errCode != (int)IoTConnectivityError.None)
498             {
499                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to delete");
500                 tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException(errCode));
501             }
502             return await tcsRemoteResponse.Task;
503         }
504
505         public void Dispose()
506         {
507             Dispose(true);
508             GC.SuppressFinalize(this);
509         }
510
511         internal static Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType GetConnectivityType(string hostAddress)
512         {
513             Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType type = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.None;
514
515             if (hostAddress == IoTConnectivityClientManager.MulticastAddress)
516             {
517                 type = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ipv4;
518             }
519             else
520             {
521                 IPAddress address;
522                 string hostName = hostAddress;
523                 if (hostAddress.Contains(":"))
524                 {
525                     string[] hostParts = hostAddress.Split(':');
526                     if (hostParts.Length == 2)
527                     {
528                         hostName = hostParts[0];
529                     }
530                 }
531                 if (IPAddress.TryParse(hostName, out address))
532                 {
533                     switch (address.AddressFamily)
534                     {
535                         case System.Net.Sockets.AddressFamily.InterNetwork:
536                             type = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ipv4;
537                             break;
538                         case System.Net.Sockets.AddressFamily.InterNetworkV6:
539                             type = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ipv6;
540                             break;
541                         default:
542                             Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to parse for Ipv4 or Ipv6");
543                             break;
544                     }
545                 }
546             }
547             return type;
548         }
549
550         protected virtual void Dispose(bool disposing)
551         {
552             if (_disposed)
553                 return;
554
555             if (disposing)
556             {
557                 // Free managed objects
558             }
559
560             Interop.IoTConnectivity.Client.RemoteResource.Destroy(_remoteResourceHandle);
561             _disposed = true;
562         }
563
564         private void HandleCachePolicyChanged()
565         {
566             if (_cacheEnabled)
567             {
568                 _cacheUpdatedCallback = (IntPtr resource, IntPtr representation, IntPtr userData) =>
569                 {
570                     if (CacheEnabled)
571                     {
572                         Representation repr = null;
573                         try
574                         {
575                             repr = new Representation(representation);
576                         }
577                         catch (Exception exp)
578                         {
579                             Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new Representation: " + exp.Message);
580                             return;
581                         }
582
583                         CacheUpdatedEventArgs e = new CacheUpdatedEventArgs()
584                         {
585                             Representation = repr
586                         };
587                         CacheUpdated?.Invoke(null, e);
588                     }
589                 };
590
591                 int ret = Interop.IoTConnectivity.Client.RemoteResource.StartCaching(_remoteResourceHandle, _cacheUpdatedCallback, IntPtr.Zero);
592                 if (ret != (int)IoTConnectivityError.None)
593                 {
594                     Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add cache updated event handler");
595                     throw IoTConnectivityErrorFactory.GetException(ret);
596                 }
597             }
598             else
599             {
600                 int ret = Interop.IoTConnectivity.Client.RemoteResource.StopCaching(_remoteResourceHandle);
601                 if (ret != (int)IoTConnectivityError.None)
602                 {
603                     Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove cache updated event handler");
604                     throw IoTConnectivityErrorFactory.GetException(ret);
605                 }
606             }
607         }
608
609         private void RegisterStateChangedEvent()
610         {
611             _stateChangedCallback = (IntPtr resource, int state, IntPtr userData) =>
612             {
613                 StateChangedEventArgs e = new StateChangedEventArgs()
614                 {
615                     State = (ResourceState)state
616                 };
617                 _stateChangedEventHandler?.Invoke(null, e);
618             };
619
620             int ret = Interop.IoTConnectivity.Client.RemoteResource.StartMonitoring(_remoteResourceHandle, _stateChangedCallback, IntPtr.Zero);
621             if (ret != (int)IoTConnectivityError.None)
622             {
623                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add state changed event handler");
624                 throw IoTConnectivityErrorFactory.GetException(ret);
625             }
626         }
627
628         private void UnregisterStateChangedEvent()
629         {
630             int ret = Interop.IoTConnectivity.Client.RemoteResource.StopMonitoring(_remoteResourceHandle);
631             if (ret != (int)IoTConnectivityError.None)
632             {
633                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove state changed event handler");
634                 throw IoTConnectivityErrorFactory.GetException(ret);
635             }
636         }
637
638         private void CreateRemoteResource(IntPtr resourceTypeHandle, IntPtr resourceInterfaceHandle)
639         {
640             Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType connectivityType = GetConnectivityType(HostAddress);
641             if (connectivityType == Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.None)
642             {
643                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Unable to parse host address");
644                 throw new ArgumentException("Unable to parse host address");
645             }
646             int ret = Interop.IoTConnectivity.Client.RemoteResource.Create(HostAddress, (int)connectivityType, UriPath, (int)Policy, resourceTypeHandle, resourceInterfaceHandle, out _remoteResourceHandle);
647             if (ret != (int)IoTConnectivityError.None)
648             {
649                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get remote resource");
650                 throw IoTConnectivityErrorFactory.GetException(ret);
651             }
652
653             /*IntPtr deviceName;
654             ret = Interop.IoTConnectivity.Client.RemoteResource.GetDeviceName(_remoteResourceHandle, out deviceName);
655             if (ret != (int)IoTConnectivityError.None)
656             {
657                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get device name of remote resource");
658                 throw IoTConnectivityErrorFactory.GetException(ret);
659             }
660             DeviceName = Marshal.PtrToStringAuto(deviceName);*/
661         }
662
663         private void SetRemoteResource()
664         {
665             IntPtr hostAddressPtr, uriPathPtr;
666             int ret = Interop.IoTConnectivity.Client.RemoteResource.GetHostAddress(_remoteResourceHandle, out hostAddressPtr);
667             if (ret != (int)IoTConnectivityError.None)
668             {
669                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Faled to get host address");
670                 throw IoTConnectivityErrorFactory.GetException(ret);
671             }
672
673             ret = Interop.IoTConnectivity.Client.RemoteResource.GetUriPath(_remoteResourceHandle, out uriPathPtr);
674             if (ret != (int)IoTConnectivityError.None)
675             {
676                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Faled to get uri path");
677                 throw IoTConnectivityErrorFactory.GetException(ret);
678             }
679
680             int policy = (int)ResourcePolicy.NoProperty;
681             ret = Interop.IoTConnectivity.Client.RemoteResource.GetPolicies(_remoteResourceHandle, out policy);
682             if (ret != (int)IoTConnectivityError.None)
683             {
684                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Faled to get uri path");
685                 throw IoTConnectivityErrorFactory.GetException(ret);
686             }
687
688             IntPtr typesHandle, interfacesHandle;
689             ret = Interop.IoTConnectivity.Client.RemoteResource.GetTypes(_remoteResourceHandle, out typesHandle);
690             if (ret != (int)IoTConnectivityError.None)
691             {
692                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get resource types");
693                 throw IoTConnectivityErrorFactory.GetException(ret);
694             }
695
696             ret = Interop.IoTConnectivity.Client.RemoteResource.GetInterfaces(_remoteResourceHandle, out interfacesHandle);
697             if (ret != (int)IoTConnectivityError.None)
698             {
699                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get resource interfaces");
700                 throw IoTConnectivityErrorFactory.GetException(ret);
701             }
702
703             IntPtr deviceIdPtr;
704             ret = Interop.IoTConnectivity.Client.RemoteResource.GetDeviceId(_remoteResourceHandle, out deviceIdPtr);
705             if (ret != (int)IoTConnectivityError.None)
706             {
707                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get device id");
708                 throw IoTConnectivityErrorFactory.GetException(ret);
709             }
710                         IntPtr deviceName;
711             ret = Interop.IoTConnectivity.Client.RemoteResource.GetDeviceName(_remoteResourceHandle, out deviceName);
712             if (ret != (int)IoTConnectivityError.None)
713             {
714                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get device name of remote resource");
715                 throw IoTConnectivityErrorFactory.GetException(ret);
716             }
717             DeviceName = Marshal.PtrToStringAuto(deviceName);
718             DeviceId = Marshal.PtrToStringAuto(deviceIdPtr);
719             HostAddress = Marshal.PtrToStringAuto(hostAddressPtr);
720             UriPath = Marshal.PtrToStringAuto(uriPathPtr);
721             Types = new ResourceTypes(typesHandle);
722             Interfaces = new ResourceInterfaces(interfacesHandle);
723             Policy = (ResourcePolicy)policy;
724         }
725
726         private RemoteResponse GetRemoteResponse(IntPtr response)
727         {
728             int result;
729             IntPtr representationHandle, optionsHandle;
730             int ret = Interop.IoTConnectivity.Server.Response.GetResult(response, out result);
731             if (ret != (int)IoTConnectivityError.None)
732             {
733                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get result");
734                 throw IoTConnectivityErrorFactory.GetException(ret);
735             }
736
737             ret = Interop.IoTConnectivity.Server.Response.GetRepresentation(response, out representationHandle);
738             if (ret != (int)IoTConnectivityError.None)
739             {
740                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get representation");
741                 throw IoTConnectivityErrorFactory.GetException(ret);
742             }
743
744             ret = Interop.IoTConnectivity.Server.Response.GetOptions(response, out optionsHandle);
745             if (ret != (int)IoTConnectivityError.None)
746             {
747                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get options");
748                 throw IoTConnectivityErrorFactory.GetException(ret);
749             }
750             return new RemoteResponse()
751             {
752                 Result = (ResponseCode)result,
753                 Representation = new Representation(representationHandle),
754                 Options = (optionsHandle == IntPtr.Zero)? null : new ResourceOptions(optionsHandle)
755             };
756         }
757     }
758 }