Example #1
0
        /// <summary>
        /// Starts observing on the resource.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        /// <remarks>
        /// When server sends notification message, <see cref="ObserverNotified"/> will be called.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/internet</privilege>
        /// <privlevel>public</privlevel>
        /// <param name="policy">The type to specify how client wants to observe.</param>
        /// <param name="query">The query to send to server.</param>
        /// <feature>http://tizen.org/feature/iot.ocf</feature>
        /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
        /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
        public void StartObserving(ObservePolicy policy, ResourceQuery query = null)
        {
            _observeCallback = (IntPtr resource, int err, int sequenceNumber, IntPtr response, IntPtr userData) =>
            {
                int    result;
                IntPtr representationHandle;
                int    ret = Interop.IoTConnectivity.Server.Response.GetResult(response, out result);
                if (ret != (int)IoTConnectivityError.None)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get result");
                    return;
                }

                ret = Interop.IoTConnectivity.Server.Response.GetRepresentation(response, out representationHandle);
                if (ret != (int)IoTConnectivityError.None)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get representation");
                    return;
                }

                Representation repr = null;
                try
                {
                    repr = new Representation(representationHandle);
                }
                catch (Exception exp)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new representation: " + exp.Message);
                    return;
                }

                ObserverNotifiedEventArgs e = new ObserverNotifiedEventArgs()
                {
                    Representation = repr,
                    Result         = (ResponseCode)result
                };
                ObserverNotified?.Invoke(this, e);
            };

            IntPtr queryHandle = IntPtr.Zero;

            if (query != null)
            {
                queryHandle = query._resourceQueryHandle;
            }

            int errCode = Interop.IoTConnectivity.Client.RemoteResource.RegisterObserve(_remoteResourceHandle, (int)policy, queryHandle, _observeCallback, IntPtr.Zero);

            if (errCode != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to register observe callbacks");
                throw IoTConnectivityErrorFactory.GetException(errCode);
            }
        }
Example #2
0
        /// <summary>
        /// Puts the representation of a resource asynchronously.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        /// <privilege>http://tizen.org/privilege/internet</privilege>
        /// <privlevel>public</privlevel>
        /// <param name="representation">Resource representation to put.</param>
        /// <param name="query">The ResourceQuery to send to server.</param>
        /// <returns>Remote response with result and representation.</returns>
        /// <feature>http://tizen.org/feature/iot.ocf</feature>
        public async Task <RemoteResponse> PutAsync(Representation representation, ResourceQuery query = null)
        {
            TaskCompletionSource <RemoteResponse> tcsRemoteResponse = new TaskCompletionSource <RemoteResponse>();

            IntPtr id = IntPtr.Zero;

            lock (_responseCallbacksMap)
            {
                id = (IntPtr)_responseCallbackId++;
            }
            _responseCallbacksMap[id] = (IntPtr resource, int err, int requestType, IntPtr responseHandle, IntPtr userData) =>
            {
                IntPtr responseCallbackId = userData;
                lock (_responseCallbacksMap)
                {
                    _responseCallbacksMap.Remove(responseCallbackId);
                }
                if (err == (int)(IoTConnectivityError.Iotivity))
                {
                    RemoteResponse response = new RemoteResponse();
                    response.Result         = ResponseCode.Forbidden;
                    response.Representation = null;
                    tcsRemoteResponse.TrySetResult(response);
                }
                else if (responseHandle != IntPtr.Zero)
                {
                    try
                    {
                        tcsRemoteResponse.TrySetResult(GetRemoteResponse(responseHandle));
                    }
                    catch (Exception exp)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get RemoteResponse: ", exp.Message);
                        tcsRemoteResponse.TrySetException(exp);
                    }
                }
                else
                {
                    tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.System));
                }
            };
            IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
            int    errCode     = Interop.IoTConnectivity.Client.RemoteResource.Put(_remoteResourceHandle, representation._representationHandle, queryHandle, _responseCallbacksMap[id], id);

            if (errCode != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to put resource representation");
                tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException(errCode));
            }
            return(await tcsRemoteResponse.Task);
        }
Example #3
0
        /// <summary>
        /// Posts request on a resource asynchronously.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        /// <privilege>http://tizen.org/privilege/internet</privilege>
        /// <privlevel>public</privlevel>
        /// <param name="representation">Resource representation of request.</param>
        /// <param name="query">The ResourceQuery to send to server.</param>
        /// <returns>Remote response with result and representation.</returns>
        /// <feature>http://tizen.org/feature/iot.ocf</feature>
        public async Task <RemoteResponse> PostAsync(Representation representation, ResourceQuery query = null)
        {
            TaskCompletionSource <RemoteResponse> tcsRemoteResponse = new TaskCompletionSource <RemoteResponse>();

            IntPtr id = IntPtr.Zero;

            lock (_taskCompletionMap)
            {
                id = (IntPtr)_responseCompletionId++;
            }

            _taskCompletionMap[id] = tcsRemoteResponse;

            IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
            int    errCode     = Interop.IoTConnectivity.Client.RemoteResource.Post(_remoteResourceHandle, representation._representationHandle, queryHandle, _postResultCallback, id);

            if (errCode != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to post request");
                tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException(errCode));
            }
            return(await tcsRemoteResponse.Task);
        }
Example #4
0
        private Request GetRequest(IntPtr requestHandle)
        {
            IntPtr hostAddressPtr;
            int    ret = Interop.IoTConnectivity.Server.Request.GetHostAddress(requestHandle, out hostAddressPtr);

            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get host address");
                return(null);
            }

            IntPtr optionsHandle = IntPtr.Zero;

            ret = Interop.IoTConnectivity.Server.Request.GetOptions(requestHandle, out optionsHandle);
            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get options");
                return(null);
            }

            IntPtr queryHandle = IntPtr.Zero;

            ret = Interop.IoTConnectivity.Server.Request.GetQuery(requestHandle, out queryHandle);
            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get Query");
                return(null);
            }

            IntPtr representationHandle = IntPtr.Zero;

            ret = Interop.IoTConnectivity.Server.Request.GetRepresentation(requestHandle, out representationHandle);
            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get representation");
                return(null);
            }

            ResourceOptions opts           = null;
            ResourceQuery   query          = null;
            Representation  representation = null;

            try
            {
                opts = (optionsHandle == IntPtr.Zero) ? null : new ResourceOptions(optionsHandle);
            }
            catch (Exception exp)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new ResourceOptions: " + exp.Message);
                return(null);
            }

            try
            {
                query = (queryHandle == IntPtr.Zero) ? null : new ResourceQuery(queryHandle);
            }
            catch (Exception exp)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new ResourceQuery: " + exp.Message);
                opts?.Dispose();
                return(null);
            }

            try
            {
                representation = (representationHandle == IntPtr.Zero) ? null : new Representation(representationHandle);
            }
            catch (Exception exp)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new Representation: " + exp.Message);
                opts?.Dispose();
                query?.Dispose();
                return(null);
            }

            return(new Request()
            {
                HostAddress = (hostAddressPtr != IntPtr.Zero) ? Marshal.PtrToStringAnsi(hostAddressPtr) : string.Empty,
                Options = opts,
                Query = query,
                Representation = representation
            });
        }
        /// <summary>
        /// Starts finding the platform information of remote server.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        /// <remarks>
        /// <para>Requests server for platform information.
        /// If succeeded, <see cref="PlatformInformationFound" /> event handler will be triggered with information of the platform.</para>
        /// <para><paramref name="hostAddress" /> could be <see cref="MulticastAddress"/> for IPv4 multicast.</para>
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/internet</privilege>
        /// <privlevel>public</privlevel>
        /// <param name="hostAddress">The host address of remote server.</param>
        /// <param name="query">The query specified as a filter for founding resources.</param>
        /// <returns>RequestId - An identifier for this request.</returns>
        /// <feature>http://tizen.org/feature/iot.ocf</feature>
        /// <pre>Initialize() should be called to initialize.</pre>
        /// <post>
        /// <see cref="PlatformInformationFound" /> event handler will be invoked.
        /// </post>
        /// <seealso cref="PlatformInformationFound"/>
        /// <seealso cref="PlatformInformationFoundEventArgs"/>
        /// <seealso cref="TimeOut"/>
        /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
        /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
        /// <example><code><![CDATA[
        /// EventHandler<PlatformInformationFoundEventArgs> handler = (sender, e) => {
        ///     Console.Log("PlatformInformationFound :" + e.RequestId);
        /// }
        /// EventHandler<FindingErrorOccurredEventArgs> errorHandler = (sender, e) => {
        ///     Console.Log("Found error :" + e.Error.Message);
        /// }
        /// IoTConnectivityClientManager.PlatformInformationFound += handler;
        /// IoTConnectivityClientManager.FindingErrorOccurred += errorHandler;
        /// // Do not forget to remove these event handlers when they are not required any more.
        /// int id = IoTConnectivityClientManager.StartFindingPlatformInformation(IoTConnectivityClientManager.MulticastAddress);
        /// ]]></code></example>
        public static int StartFindingPlatformInformation(string hostAddress, ResourceQuery query = null)
        {
            Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType connectivityType = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ip;

            IntPtr id = IntPtr.Zero;

            lock (s_platformInformationCallbacksMap)
            {
                id = (IntPtr)s_requestId++;
            }
            s_platformInformationCallbacksMap[id] = (IntPtr platformInfoHandle, int result, IntPtr userData) =>
            {
                if (PlatformInformationFound == null)
                {
                    return(false);
                }

                int requestId = (int)userData;
                if (result == (int)IoTConnectivityError.None)
                {
                    if (platformInfoHandle != IntPtr.Zero)
                    {
                        PlatformInformationFoundEventArgs e = GetPlatformInformationFoundEventArgs(requestId, platformInfoHandle);
                        if (e == null)
                        {
                            Log.Error(IoTConnectivityErrorFactory.LogTag, "Can't get PlatformInformationFoundEventArgs");
                            return(true);
                        }
                        PlatformInformationFound?.Invoke(null, e);
                        Log.Info(IoTConnectivityErrorFactory.LogTag, "e.EventContinue : " + e.EventContinue);
                        return(e.EventContinue);
                    }
                    else
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Handle is null");
                    }
                }
                else
                {
                    FindingErrorOccurredEventArgs e = GetFindingErrorOccurredEventArgs(requestId, result);
                    FindingErrorOccurred?.Invoke(null, e);

                    lock (s_platformInformationCallbacksMap)
                    {
                        s_platformInformationCallbacksMap.Remove(id);
                    }
                }
                return(true);
            };

            IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
            int    errorCode   = Interop.IoTConnectivity.Client.PlatformInformation.Find(hostAddress, (int)connectivityType, queryHandle, s_platformInformationCallbacksMap[id], id);

            if (errorCode != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get platform information");
                lock (s_platformInformationCallbacksMap)
                {
                    s_platformInformationCallbacksMap.Remove(id);
                }
                throw IoTConnectivityErrorFactory.GetException(errorCode);
            }

            return((int)id);
        }
        /// <summary>
        /// Starts finding resources.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        /// <remarks>
        /// <para>Sends request to find a resource of <paramref name="hostAddress" /> server with <paramref name="query" />.
        /// If succeeded, <see cref="ResourceFound"/> event handler will be triggered with information of the resource.</para>
        /// <para><paramref name="hostAddress" /> could be <see cref="MulticastAddress"/> for the IPv4 multicast.</para>
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/internet</privilege>
        /// <privlevel>public</privlevel>
        /// <param name="hostAddress">The address or addressable name of the server. The address includes a protocol like coaps://.</param>
        /// <param name="query">The query specified as a filter for founding resources.</param>
        /// <returns>RequestId - An identifier for this request.</returns>
        /// <feature>http://tizen.org/feature/iot.ocf</feature>
        /// <pre>Initialize() should be called to initialize.</pre>
        /// <post>
        /// When the resource is found, <see cref="ResourceFound"/> event handler will be invoked.
        /// </post>
        /// <seealso cref="ResourceFound"/>
        /// <seealso cref="ResourceFoundEventArgs"/>
        /// <seealso cref="TimeOut"/>
        /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
        /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
        /// <example><code><![CDATA[
        /// EventHandler<ResourceFoundEventArgs> handler = (sender, e) => {
        ///     Console.Log("Found resource at host address :" + e.Resource.HostAddress + ", uri :" + e.Resource.UriPath);
        /// }
        /// EventHandler<FindingErrorOccurredEventArgs> errorHandler = (sender, e) => {
        ///     Console.Log("Found error :" + e.Error.Message);
        /// }
        /// IoTConnectivityClientManager.ResourceFound += handler;
        /// IoTConnectivityClientManager.FindingErrorOccurred += errorHandler;
        /// ResourceQuery query = new ResourceQuery();
        /// query.Type = "oic.iot.door";
        /// // Do not forget to remove these event handlers when they are not required any more.
        /// int id = IoTConnectivityClientManager.StartFindingResource(null, query);
        /// ]]></code></example>
        public static int StartFindingResource(string hostAddress, ResourceQuery query = null)
        {
            Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType connectivityType = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ip;

            IntPtr id = IntPtr.Zero;

            lock (s_resourceFoundCallbacksMap)
            {
                id = (IntPtr)s_requestId++;
            }
            s_resourceFoundCallbacksMap[id] = (IntPtr remoteResourceHandle, int result, IntPtr userData) =>
            {
                if (ResourceFound == null)
                {
                    return(false);
                }

                int requestId = (int)userData;
                if (result == (int)IoTConnectivityError.None)
                {
                    if (remoteResourceHandle != IntPtr.Zero)
                    {
                        RemoteResource resource = null;
                        try
                        {
                            resource = new RemoteResource(remoteResourceHandle);
                        }
                        catch (Exception exp)
                        {
                            Log.Error(IoTConnectivityErrorFactory.LogTag, "Can't clone RemoteResource's handle: " + exp.Message);
                            return(true);
                        }
                        ResourceFoundEventArgs e = new ResourceFoundEventArgs()
                        {
                            RequestId     = requestId,
                            EventContinue = true,
                            Resource      = resource
                        };
                        ResourceFound?.Invoke(null, e);
                        Log.Info(IoTConnectivityErrorFactory.LogTag, "e.EventContinue : " + e.EventContinue);
                        return(e.EventContinue);
                    }
                    else
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Handle is null");
                    }
                }
                else
                {
                    FindingErrorOccurredEventArgs e = GetFindingErrorOccurredEventArgs(requestId, result);
                    FindingErrorOccurred?.Invoke(null, e);

                    lock (s_resourceFoundCallbacksMap)
                    {
                        s_resourceFoundCallbacksMap.Remove(id);
                    }
                }
                return(true);
            };
            IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
            int    errorCode   = Interop.IoTConnectivity.Client.ResourceFinder.AddResourceFoundCb(hostAddress, (int)connectivityType, queryHandle, s_resourceFoundCallbacksMap[id], id);

            if (errorCode != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to register resource found event handler");
                lock (s_resourceFoundCallbacksMap)
                {
                    s_resourceFoundCallbacksMap.Remove(id);
                }
                throw IoTConnectivityErrorFactory.GetException(errorCode);
            }
            return((int)id);
        }