/// <summary>
        /// Registers a resource in IoTCon server.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        /// <privilege>http://tizen.org/privilege/internet</privilege>
        /// <privlevel>public</privlevel>
        /// <param name="resource">The resource to register.</param>
        /// <feature>http://tizen.org/feature/iot.ocf</feature>
        /// <pre>
        /// Initialize() should be called to initialize.
        /// </pre>
        /// <seealso cref="Resource"/>
        /// <seealso cref="LiteResource"/>
        /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
        /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
        /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
        /// <example><code><![CDATA[
        /// ResourceTypes types = new ResourceTypes(new List<string>(){ "org.tizen.light" });
        /// Attributes attributes = new Attributes { { "state", "ON" }};
        /// Resource res = new LiteResource("/room/1", types, ResourcePolicy.Discoverable, attributes);
        /// try {
        ///     IoTConnectivityServerManager.RegisterResource(res);
        /// } catch(Exception ex) {
        ///     Console.Log("Exception caught : " + ex.Message);
        /// }
        /// ]]></code></example>
        public static void RegisterResource(Resource resource)
        {
            Log.Info(IoTConnectivityErrorFactory.LogTag, "...");

            IntPtr id = IntPtr.Zero;

            lock (s_RequestHandlerCallbackMap)
            {
                id = (IntPtr)s_requestId++;
            }

            s_RequestHandlerCallbackMap[id] = (IntPtr r_resource, IntPtr request, IntPtr userData) =>
            {
                int requestId = (int)userData;

                Log.Info(IoTConnectivityErrorFactory.LogTag, "Received s_RequestHandlerCallbackMap : " + requestId);

                if (request == IntPtr.Zero)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "request is IntPtr.Zero");
                    return;
                }
                resource.OnRequest(r_resource, request, userData);
            };

            IntPtr handle    = IntPtr.Zero;
            int    errorCode = Interop.IoTConnectivity.Server.Resource.Create(resource.UriPath, resource.Types._resourceTypeHandle, resource.Interfaces.ResourceInterfacesHandle, (int)resource.Policy, s_RequestHandlerCallbackMap[id], id, out handle);

            if (errorCode != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed create resource");
                lock (s_RequestHandlerCallbackMap)
                {
                    s_RequestHandlerCallbackMap.Remove(id);
                }
                throw IoTConnectivityErrorFactory.GetException(errorCode);
            }
            else
            {
                resource.ResourceHandle = handle;
            }
            _resources.Add(resource);
        }
Example #2
0
        /// <summary>
        /// Adds a new ID and a correspoding data into the options.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        /// <remarks>
        /// <para>ResourceOptions can have up to 2 options.</para>
        /// <para>key is always situated between 2048 and 3000.</para>
        /// <para>Length of option data is less than or equal to 15.</para>
        /// </remarks>
        /// <param name="key">The ID of the option to insert.</param>
        /// <param name="value">The string data to insert into the options.</param>
        /// <feature>http://tizen.org/feature/iot.ocf</feature>
        /// <seealso cref="Remove(ushort)"/>
        /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
        /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
        /// <example><code>
        /// ResourceOptions options = new ResourceOptions();
        /// options.Add(2050, "sample-data");
        /// </code></example>
        public void Add(ushort key, string value)
        {
            int ret = (int)IoTConnectivityError.InvalidParameter;

            if (IsValid(key, value))
            {
                ret = Interop.IoTConnectivity.Common.Options.Add(_resourceOptionsHandle, key, value);
                if (ret != (int)IoTConnectivityError.None)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add option");
                    throw IoTConnectivityErrorFactory.GetException(ret);
                }
                _options.Add(key, value);
            }
            else
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Invalid options");
                throw IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.InvalidParameter);
            }
        }
Example #3
0
        /// <summary>
        /// Deletes the resource asynchronously.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        /// <privilege>http://tizen.org/privilege/internet</privilege>
        /// <privlevel>public</privlevel>
        /// <returns>Remote response with result and representation.</returns>
        /// <feature>http://tizen.org/feature/iot.ocf</feature>
        public async Task <RemoteResponse> DeleteAsync()
        {
            TaskCompletionSource <RemoteResponse> tcsRemoteResponse = new TaskCompletionSource <RemoteResponse>();

            IntPtr id = IntPtr.Zero;

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

            _taskCompletionMap[id] = tcsRemoteResponse;

            int errCode = Interop.IoTConnectivity.Client.RemoteResource.Delete(_remoteResourceHandle, _deleteResultCallback, id);

            if (errCode != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to delete");
                tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException(errCode));
            }
            return(await tcsRemoteResponse.Task);
        }
Example #4
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 #5
0
        internal ResourceTypes(IntPtr typesHandleToClone)
        {
            int ret = Interop.IoTConnectivity.Common.ResourceTypes.Clone(typesHandleToClone, out _resourceTypeHandle);

            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create type");
                throw IoTConnectivityErrorFactory.GetException(ret);
            }

            Interop.IoTConnectivity.Common.ResourceTypes.ForeachCallback cb = (string type, IntPtr data) =>
            {
                _resourceTypes.Add(type);
                return(true);
            };

            ret = Interop.IoTConnectivity.Common.ResourceTypes.Foreach(typesHandleToClone, cb, IntPtr.Zero);
            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create type");
                throw IoTConnectivityErrorFactory.GetException(ret);
            }
        }
Example #6
0
        internal ResourceQuery(IntPtr resourceQueryHandleToClone)
        {
            int ret = Interop.IoTConnectivity.Common.Query.Create(out _resourceQueryHandle);

            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create query");
                throw IoTConnectivityErrorFactory.GetException(ret);
            }

            Interop.IoTConnectivity.Common.Query.QueryCallback forEachCallback = (string key, string value, IntPtr userData) =>
            {
                Add(key, value);
                return(true);
            };

            ret = Interop.IoTConnectivity.Common.Query.Foreach(resourceQueryHandleToClone, forEachCallback, IntPtr.Zero);
            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to iterate query");
                throw IoTConnectivityErrorFactory.GetException(ret);
            }
        }
Example #7
0
        // internal constructor
        internal ResourceOptions(IntPtr handleToClone)
        {
            int ret = Interop.IoTConnectivity.Common.Options.Create(out _resourceOptionsHandle);

            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create options");
                throw IoTConnectivityErrorFactory.GetException(ret);
            }

            Interop.IoTConnectivity.Common.Options.OptionsCallback forEachCallback = (ushort id, string value, IntPtr userData) =>
            {
                Add(id, value);
                return(true);
            };

            ret = Interop.IoTConnectivity.Common.Options.ForEach(handleToClone, forEachCallback, IntPtr.Zero);
            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to iterate options");
                throw IoTConnectivityErrorFactory.GetException(ret);
            }
        }
Example #8
0
        private static void NativeDeleteResultCallbackHandler(IntPtr resource, int err, int requestType, IntPtr responseHandle, IntPtr userData)
        {
            IntPtr responseCompletionId = userData;
            TaskCompletionSource <RemoteResponse> responseCompletionSource;

            Log.Info(IoTConnectivityErrorFactory.LogTag, "Result callback for : " + responseCompletionId);

            if (!_taskCompletionMap.TryRemove(responseCompletionId, out responseCompletionSource))
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove Key");
                return;
            }

            if (err == (int)(IoTConnectivityError.Iotivity))
            {
                RemoteResponse response = new RemoteResponse();
                response.Result         = ResponseCode.Forbidden;
                response.Representation = null;
                responseCompletionSource.TrySetResult(response);
            }
            else if (responseHandle != IntPtr.Zero)
            {
                try
                {
                    responseCompletionSource.TrySetResult(GetRemoteResponse(responseHandle));
                }
                catch (Exception exp)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get RemoteResponse: ", exp.Message);
                    responseCompletionSource.TrySetException(exp);
                }
            }
            else
            {
                responseCompletionSource.TrySetException(IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.System));
            }
        }
Example #9
0
        private static void NativePostResultCallbackHandler(IntPtr resource, int err, int requestType, IntPtr responseHandle, IntPtr userData)
        {
            IntPtr responseCompletionId = userData;
            TaskCompletionSource <RemoteResponse> responseCompletionSource = _taskCompletionMap[responseCompletionId];

            _taskCompletionMap.Remove(responseCompletionId);

            if (responseHandle != IntPtr.Zero)
            {
                try
                {
                    responseCompletionSource.TrySetResult(GetRemoteResponse(responseHandle));
                }
                catch (Exception exp)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get RemoteResponse: ", exp.Message);
                    responseCompletionSource.TrySetException(exp);
                }
            }
            else
            {
                responseCompletionSource.TrySetException(IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.System));
            }
        }
Example #10
0
        internal static object GetList(IntPtr listHandle)
        {
            IList list = null;
            int   type;
            int   ret = Interop.IoTConnectivity.Common.List.GetType(listHandle, out type);

            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get type");
                throw IoTConnectivityErrorFactory.GetException(ret);
            }
            switch ((Interop.IoTConnectivity.Common.DataType)type)
            {
            case Interop.IoTConnectivity.Common.DataType.Int:
            {
                list = new List <int>();
                Interop.IoTConnectivity.Common.List.IntCallback cb = (int pos, int value, IntPtr userData) =>
                {
                    list.Add(value);
                    return(true);
                };
                ret = Interop.IoTConnectivity.Common.List.ForeachInt(listHandle, cb, IntPtr.Zero);
                break;
            }

            case Interop.IoTConnectivity.Common.DataType.Bool:
            {
                list = new List <bool>();
                Interop.IoTConnectivity.Common.List.BoolCallback cb = (int pos, bool value, IntPtr userData) =>
                {
                    list.Add(value);
                    return(true);
                };
                ret = Interop.IoTConnectivity.Common.List.ForeachBool(listHandle, cb, IntPtr.Zero);
                break;
            }

            case Interop.IoTConnectivity.Common.DataType.Double:
            {
                list = new List <double>();
                Interop.IoTConnectivity.Common.List.DoubleCallback cb = (int pos, double value, IntPtr userData) =>
                {
                    list.Add(value);
                    return(true);
                };
                ret = Interop.IoTConnectivity.Common.List.ForeachDouble(listHandle, cb, IntPtr.Zero);
                break;
            }

            case Interop.IoTConnectivity.Common.DataType.String:
            {
                list = new List <string>();
                Interop.IoTConnectivity.Common.List.StrCallback cb = (int pos, string value, IntPtr userData) =>
                {
                    list.Add(value);
                    return(true);
                };
                ret = Interop.IoTConnectivity.Common.List.ForeachStr(listHandle, cb, IntPtr.Zero);
                break;
            }

            case Interop.IoTConnectivity.Common.DataType.Attributes:
            {
                list = new List <Attributes>();
                Interop.IoTConnectivity.Common.List.AttribsCallback cb = (int pos, IntPtr value, IntPtr userData) =>
                {
                    list.Add(new Attributes(value));
                    return(true);
                };
                ret = Interop.IoTConnectivity.Common.List.ForeachAttributes(listHandle, cb, IntPtr.Zero);
                break;
            }

            case Interop.IoTConnectivity.Common.DataType.ByteStr:
            {
                list = new List <byte[]>();
                Interop.IoTConnectivity.Common.List.ByteStrCallback cb = (int pos, byte[] value, int len, IntPtr userData) =>
                {
                    list.Add(value);
                    return(true);
                };
                ret = Interop.IoTConnectivity.Common.List.ForeachByteStr(listHandle, cb, IntPtr.Zero);
                break;
            }

            case Interop.IoTConnectivity.Common.DataType.List:
            {
                list = new List <List <object> >();
                Interop.IoTConnectivity.Common.List.ListCallback cb = (int pos, IntPtr value, IntPtr userData) =>
                {
                    object childList = GetList(value);
                    if (childList != null)
                    {
                        list.Add(childList);
                    }
                    return(true);
                };
                ret = Interop.IoTConnectivity.Common.List.ForeachList(listHandle, cb, IntPtr.Zero);
                break;
            }

            default:
                break;
            }
            if (ret != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
                throw IoTConnectivityErrorFactory.GetException(ret);
            }
            return(list);
        }
Example #11
0
        internal static IntPtr GetListHandle(object list)
        {
            IntPtr listHandle = IntPtr.Zero;
            int    ret;
            int    pos = 0;

            if (list is IEnumerable <IEnumerable> )
            {
                ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.List, out listHandle);
                pos = 0;
                foreach (IEnumerable val in (IEnumerable <IEnumerable>)list)
                {
                    IntPtr childList = GetListHandle(val);
                    ret = Interop.IoTConnectivity.Common.List.AddList(listHandle, childList, pos++);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add attributes");
                        Interop.IoTConnectivity.Common.List.Destroy(childList);
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                }
            }
            else if (list is IEnumerable <int> )
            {
                ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.Int, out listHandle);
                pos = 0;
                foreach (int val in (IEnumerable <int>)list)
                {
                    ret = Interop.IoTConnectivity.Common.List.AddInt(listHandle, val, pos++);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add attributes");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                }
            }
            else if (list is IEnumerable <string> )
            {
                ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.String, out listHandle);
                pos = 0;
                foreach (string val in (IEnumerable <string>)list)
                {
                    ret = Interop.IoTConnectivity.Common.List.AddStr(listHandle, val, pos++);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add str");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                }
            }
            else if (list is IEnumerable <double> )
            {
                ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.Double, out listHandle);
                pos = 0;
                foreach (double val in (IEnumerable <double>)list)
                {
                    ret = Interop.IoTConnectivity.Common.List.AddDouble(listHandle, val, pos++);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add double");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                }
            }
            else if (list is IEnumerable <bool> )
            {
                ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.Bool, out listHandle);
                pos = 0;
                foreach (bool val in (IEnumerable <bool>)list)
                {
                    ret = Interop.IoTConnectivity.Common.List.AddBool(listHandle, val, pos++);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add bool");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                }
            }
            else if (list is IEnumerable <Attributes> )
            {
                ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.Attributes, out listHandle);
                pos = 0;
                foreach (Attributes val in (IEnumerable <Attributes>)list)
                {
                    ret = Interop.IoTConnectivity.Common.List.AddAttributes(listHandle, val._resourceAttributesHandle, pos++);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add attributes");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                }
            }
            else if (list is IEnumerable <byte[]> )
            {
                ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.ByteStr, out listHandle);
                pos = 0;
                foreach (byte[] val in (IEnumerable <byte[]>)list)
                {
                    ret = Interop.IoTConnectivity.Common.List.AddByteStr(listHandle, val, val.Length, pos++);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add byte[]");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                }
            }
            else
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to GetListHandle");
                throw IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.InvalidParameter);
            }
            return(listHandle);
        }
Example #12
0
        private void SetAttributes(IntPtr attributesHandle)
        {
            Interop.IoTConnectivity.Common.Attributes.AttributesCallback cb = (IntPtr attributes, string key, IntPtr userData) =>
            {
                Interop.IoTConnectivity.Common.DataType dataType;
                int ret = Interop.IoTConnectivity.Common.Attributes.GetType(attributes, key, out dataType);
                if (ret != (int)IoTConnectivityError.None)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get type");
                    throw IoTConnectivityErrorFactory.GetException(ret);
                }

                switch ((Interop.IoTConnectivity.Common.DataType)dataType)
                {
                case Interop.IoTConnectivity.Common.DataType.Int:
                {
                    int value;
                    ret = Interop.IoTConnectivity.Common.Attributes.GetInt(attributes, key, out value);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                    _attributes.Add(key, value);
                    break;
                }

                case Interop.IoTConnectivity.Common.DataType.Bool:
                {
                    bool value;
                    ret = Interop.IoTConnectivity.Common.Attributes.GetBool(attributes, key, out value);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                    _attributes.Add(key, value);
                    break;
                }

                case Interop.IoTConnectivity.Common.DataType.Double:
                {
                    double value;
                    ret = Interop.IoTConnectivity.Common.Attributes.GetDouble(attributes, key, out value);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                    _attributes.Add(key, value);
                    break;
                }

                case Interop.IoTConnectivity.Common.DataType.String:
                {
                    IntPtr value;
                    string Str;
                    ret = Interop.IoTConnectivity.Common.Attributes.GetStr(attributes, key, out value);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                    Str = (value != IntPtr.Zero) ? Marshal.PtrToStringAnsi(value) : string.Empty;
                    _attributes.Add(key, Str);
                    break;
                }

                case Interop.IoTConnectivity.Common.DataType.ByteStr:
                {
                    IntPtr byteStrPtr;
                    int    byteStrSize;
                    ret = Interop.IoTConnectivity.Common.Attributes.GetByteStr(attributes, key, out byteStrPtr, out byteStrSize);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                    byte[] byteStr = new byte[byteStrSize];
                    Marshal.Copy(byteStrPtr, byteStr, 0, byteStrSize);
                    _attributes.Add(key, byteStr);
                    break;
                }

                case Interop.IoTConnectivity.Common.DataType.Null:
                {
                    _attributes.Add(key, null);
                    break;
                }

                case Interop.IoTConnectivity.Common.DataType.List:
                {
                    IntPtr listHandle;
                    ret = Interop.IoTConnectivity.Common.Attributes.GetList(attributes, key, out listHandle);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                    _attributes.Add(key, List.GetList(listHandle));
                    break;
                }

                case Interop.IoTConnectivity.Common.DataType.Attributes:
                {
                    IntPtr attribsHandle;
                    ret = Interop.IoTConnectivity.Common.Attributes.GetAttributes(attributes, key, out attribsHandle);
                    if (ret != (int)IoTConnectivityError.None)
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
                        throw IoTConnectivityErrorFactory.GetException(ret);
                    }
                    _attributes.Add(key, new Attributes(attribsHandle));
                    break;
                }

                default:
                    break;
                }

                return(true);
            };

            int res = Interop.IoTConnectivity.Common.Attributes.Foreach(attributesHandle, cb, IntPtr.Zero);

            if (res != (int)IoTConnectivityError.None)
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove attributes");
                throw IoTConnectivityErrorFactory.GetException(res);
            }
        }
Example #13
0
        /// <summary>
        /// Adds an attribute.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        /// <param name="key">The key representing the attribute.</param>
        /// <param name="value">The value representing the attribute.</param>
        /// <feature>http://tizen.org/feature/iot.ocf</feature>
        /// <example><code>
        /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes();
        /// attributes.Add("brightness", 50);
        /// </code></example>
        public void Add(string key, object value)
        {
            int ret = 0;

            if (value is int)
            {
                ret = Interop.IoTConnectivity.Common.Attributes.AddInt(_resourceAttributesHandle, key, (int)value);
                if (ret != (int)IoTConnectivityError.None)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add int");
                    throw IoTConnectivityErrorFactory.GetException(ret);
                }
            }
            else if (value is Attributes)
            {
                Attributes attribs = (Attributes)value;
                ret = Interop.IoTConnectivity.Common.Attributes.AddAttributes(_resourceAttributesHandle, key, attribs._resourceAttributesHandle);
                if (ret != (int)IoTConnectivityError.None)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add attributes");
                    throw IoTConnectivityErrorFactory.GetException(ret);
                }
            }
            else if (value is string)
            {
                ret = Interop.IoTConnectivity.Common.Attributes.AddStr(_resourceAttributesHandle, key, (string)value);
                if (ret != (int)IoTConnectivityError.None)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add string");
                    throw IoTConnectivityErrorFactory.GetException(ret);
                }
            }
            else if (value is double)
            {
                ret = Interop.IoTConnectivity.Common.Attributes.AddDouble(_resourceAttributesHandle, key, (double)value);
                if (ret != (int)IoTConnectivityError.None)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add double");
                    throw IoTConnectivityErrorFactory.GetException(ret);
                }
            }
            else if (value is bool)
            {
                ret = Interop.IoTConnectivity.Common.Attributes.AddBool(_resourceAttributesHandle, key, (bool)value);
                if (ret != (int)IoTConnectivityError.None)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add bool");
                    throw IoTConnectivityErrorFactory.GetException(ret);
                }
            }
            else if (value is byte[])
            {
                byte[] val = value as byte[];
                if (val == null)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get byte[] val");
                    throw new ArgumentException("Invalid Parameter");
                }
                ret = Interop.IoTConnectivity.Common.Attributes.AddByteStr(_resourceAttributesHandle, key, val, val.Length);
                if (ret != (int)IoTConnectivityError.None)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add bool");
                    throw IoTConnectivityErrorFactory.GetException(ret);
                }
            }
            else if (value is IEnumerable)
            {
                IntPtr listHandle = List.GetListHandle(value);
                ret = Interop.IoTConnectivity.Common.Attributes.AddList(_resourceAttributesHandle, key, listHandle);
                if (ret != (int)IoTConnectivityError.None)
                {
                    Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add list");
                    throw IoTConnectivityErrorFactory.GetException(ret);
                }
            }
            else
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Add");
                throw IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.InvalidParameter);
            }
            _attributes.Add(key, value);
        }
        /// <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);
        }
        /// <summary>
        /// Starts receiving presence events.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        /// <remarks>
        /// <para>Sends request to receive presence to an interested server's resource with resourceType.
        /// If succeeded, <see cref="PresenceReceived"/> event handler will be triggered when the server sends presence.
        /// A server sends presence events when adds / removes / alters a resource or start / stop presence.</para>
        /// <para><paramref name="hostAddress" /> could be <see cref="MulticastAddress"/> for IPv4 multicast.
        /// The length of <paramref name="resourceType" /> should be less than or equal to 61.
        /// The <paramref name="resourceType" /> must start with a lowercase alphabetic character, followed by a sequence
        /// of lowercase alphabetic, numeric, ".", or "-" characters, and contains no white space.</para>
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/internet</privilege>
        /// <privlevel>public</privlevel>
        /// <param name="hostAddress">The address or addressable name of the server.</param>
        /// <param name="resourceType">A resource type that a client is interested in.</param>
        /// <returns>PresenceId - 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 receive presence, <see cref="PresenceReceived"/> event handler will be invoked.<br/>
        /// You must destroy presence by calling StopReceivingPresence() if presence event is no longer needed.
        /// </post>
        /// <seealso cref="IoTConnectivityServerManager.StartSendingPresence(uint)"/>
        /// <seealso cref="IoTConnectivityServerManager.StopSendingPresence()"/>
        /// <seealso cref="StopReceivingPresence(int)"/>
        /// <seealso cref="PresenceReceived"/>
        /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
        /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</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<PresenceReceivedEventArgs> handler = (sender, e) => {
        ///     Console.Log("PresenceReceived, presence id :" + e.PresenceId);
        /// }
        /// EventHandler<FindingErrorOccurredEventArgs> errorHandler = (sender, e) => {
        ///     Console.Log("Found error :" + e.Error.Message);
        /// }
        /// IoTConnectivityClientManager.PresenceReceived += handler;
        /// IoTConnectivityClientManager.FindingErrorOccurred += errorHandler;
        /// // Do not forget to remove these event handlers when they are not required any more.
        /// int id = IoTConnectivityClientManager.StartReceivingPresence(IoTConnectivityClientManager.MulticastAddress, "oic.iot.door");
        /// ]]></code></example>
        public static int StartReceivingPresence(string hostAddress, string resourceType)
        {
            Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType connectivityType = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ip;

            if (resourceType != null && !ResourceTypes.IsValid(resourceType))
            {
                Log.Error(IoTConnectivityErrorFactory.LogTag, "Invalid type");
                throw new ArgumentException("Invalid type");
            }

            IntPtr id = IntPtr.Zero;

            lock (s_presenceCallbacksMap)
            {
                id = (IntPtr)s_presenceListenerId++;
            }
            s_presenceCallbacksMap[id] = (IntPtr presence, int result, IntPtr presenceResponseHandle, IntPtr userData) =>
            {
                int presenceId = (int)userData;
                if (result == (int)IoTConnectivityError.None)
                {
                    if (presenceResponseHandle != IntPtr.Zero)
                    {
                        PresenceReceivedEventArgs e = GetPresenceReceivedEventArgs(presenceId, presenceResponseHandle);
                        if (e == null)
                        {
                            Log.Error(IoTConnectivityErrorFactory.LogTag, "Can't get PresenceReceivedEventArgs");
                            return;
                        }
                        PresenceReceived?.Invoke(null, e);
                    }
                    else
                    {
                        Log.Error(IoTConnectivityErrorFactory.LogTag, "Handle is null");
                        return;
                    }
                }
                else
                {
                    FindingErrorOccurredEventArgs e = GetFindingErrorOccurredEventArgs(presenceId, result);
                    FindingErrorOccurred?.Invoke(null, e);
                }
            };

            IntPtr presenceHandle;
            int    errorCode = Interop.IoTConnectivity.Client.Presence.AddPresenceCb(hostAddress, (int)connectivityType, resourceType, s_presenceCallbacksMap[id], id, out presenceHandle);

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

            lock (s_presenceHandlesMap)
            {
                s_presenceHandlesMap[id] = presenceHandle;
            }
            return((int)id);
        }