Esempio n. 1
0
        public void AddResourceType(string resourceTypeName, IDictionary <string, object> properties)
        {
            OCStackResult result = OCStack.OCBindResourceTypeToResource(_handle, resourceTypeName);

            OCStackException.ThrowIfError(result, "Failed to add resource type");
            _resourceProperties.Add(resourceTypeName, new IotivityValueDictionary(properties));
        }
Esempio n. 2
0
        public static void Initialize(ServiceMode mode)
        {
            var result = OCStack.OCInit(null, 0, (OCMode)mode);

            //var result = OCStack.OCInit1((OCMode)mode, OCTransportFlags.OC_DEFAULT_FLAGS, OCTransportFlags.OC_DEFAULT_FLAGS);
            if (result != OCStackResult.OC_STACK_OK)
            {
                throw new Exception(result.ToString());
            }
            ct  = new CancellationTokenSource();
            tcs = new TaskCompletionSource <object>();

#if NETFX_CORE
            Task.Run(async() =>
#else
            ThreadPool.QueueUserWorkItem(async(s) =>
#endif
            {
                while (!ct.IsCancellationRequested)
                {
                    var result2 = OCStack.OCProcess();
                    if (result2 != OCStackResult.OC_STACK_OK)
                    {
                        // tcs.SetException(new Exception("OCStackException on Process: " + result2.ToString()));
                        // break;
                    }
                    await Task.Delay(1);
                }
                tcs.SetResult(true);
                tcs = null;
                ct  = null;
            });
        }
Esempio n. 3
0
        private static void CreateResources()
        {
            //bswitch = new BinarySwitchDevice("/switch/1", false);
            //bswitch2 = new BinarySwitchDevice("/switch/2", true);
            // bswitch3 = new BinarySwitchDevice("/switch/3", true);
            // bswitch4 = new BinarySwitchDevice("/switch/4", true);
            // light = new LightDevice("/light/1", true, 50, 180, 100);
            // light2 = new LightDevice("/foo/1", false, 75);
            // light3 = new LightDevice("/lifx/2", true);
            IntPtr _handle;
            string resourceTypeName      = "oic.r.switch.binary";
            string resourceInterfaceName = "oic.if.baseline";

            OCStackResult result = OCStack.OCCreateResource(out _handle, resourceTypeName, resourceInterfaceName,
                                                            "/switch/1", null, IntPtr.Zero, OCResourceProperty.OC_DISCOVERABLE | OCResourceProperty.OC_OBSERVABLE);

            result = OCStack.OCCreateResource(out _handle, resourceTypeName + "2", resourceInterfaceName,
                                              "/switch/2", null, IntPtr.Zero, OCResourceProperty.OC_DISCOVERABLE | OCResourceProperty.OC_OBSERVABLE);

            result = OCStack.OCCreateResource(out _handle, resourceTypeName + "3", resourceInterfaceName,
                                              "/switch/3", null, IntPtr.Zero, OCResourceProperty.OC_DISCOVERABLE | OCResourceProperty.OC_OBSERVABLE);

            //result = OCStack.OCCreateResource(out _handle, resourceTypeName + "4", resourceInterfaceName,
            //    "/switch/4", null, IntPtr.Zero, OCResourceProperty.OC_DISCOVERABLE | OCResourceProperty.OC_OBSERVABLE);
        }
 public void Stop()
 {
     isRunning = false;
     if (handle != IntPtr.Zero)
     {
         var ret = OCStack.OCCancel(handle, OCQualityOfService.OC_LOW_QOS, null, 0);
         OCStackException.ThrowIfError(ret);
         handle = IntPtr.Zero;
     }
 }
Esempio n. 5
0
        private OCEntityHandlerResult OCEntityHandler(OCEntityHandlerFlag flag, OCEntityHandlerRequest entityHandlerRequest, IntPtr callbackParam)
        {
            OCEntityHandlerResult result         = OCEntityHandlerResult.OC_EH_OK;
            RepPayload            payload        = null;
            RepPayload            requestPayload = entityHandlerRequest.payload == IntPtr.Zero ? null : new RepPayload(entityHandlerRequest.payload);

            if (entityHandlerRequest != null && (flag.HasFlag(OCEntityHandlerFlag.OC_REQUEST_FLAG)))
            {
                switch (entityHandlerRequest.method)
                {
                case OCMethod.OC_REST_GET:
                {
                    var rpayload = payload = new RepPayload();
                    rpayload.SetUri(_uri);
                    foreach (var resource in _resourceProperties)
                    {
                        if (requestPayload != null && !requestPayload.Types.Contains(resource.Key))
                        {
                            continue;
                        }
                        var repayload = new RepPayload(resource.Value);
                        repayload.Types.Add(resource.Key);
                        rpayload.Next = repayload;
                        rpayload      = repayload;
                    }
                    payload = rpayload;
                }
                break;

                case OCMethod.OC_REST_POST:
                case OCMethod.OC_REST_PUT:
                {
                    var p = new RepPayload(entityHandlerRequest.payload);
                    result = OnPropertyUpdated(p);
                    PropertyUpdated?.Invoke(this, p);
                }
                break;

                default:
                    result = OCEntityHandlerResult.OC_EH_METHOD_NOT_ALLOWED;
                    break;
                }
                var response = new OCEntityHandlerResponse();
                response.requestHandle  = entityHandlerRequest.requestHandle;
                response.resourceHandle = entityHandlerRequest.resource;
                response.ehResult       = result;
                response.payload        = payload == null ? IntPtr.Zero : payload.AsOCRepPayload();
                response.numSendVendorSpecificHeaderOptions = 0;
                response.sendVendorSpecificHeaderOptions    = IntPtr.Zero;
                response.resourceUri          = string.Empty;
                response.persistentBufferFlag = 0;
                OCStack.OCDoResponse(response);
            }
            return(result);
        }
Esempio n. 6
0
        public static async Task Shutdown()
        {
            if (tcs == null)
            {
                return;
            }
            ct.Cancel();
            await tcs.Task;
            var result = OCStack.OCStop();

            OCStackException.ThrowIfError(result);
        }
Esempio n. 7
0
 public void Stop()
 {
     if (handle != IntPtr.Zero)
     {
         var ret = OCStack.OCCancel(handle, OCQualityOfService.OC_LOW_QOS, null, 0);
         if (ret != OCStackResult.OC_STACK_OK)
         {
             throw new Exception(ret.ToString());
         }
         handle = IntPtr.Zero;
     }
 }
Esempio n. 8
0
        public DeviceResource(string uri, string resourceTypeName, IDictionary <string, object> properties, string resourceInterfaceName = IotivityDotNet.Interop.Defines.OC_RSRVD_INTERFACE_DEFAULT)
        {
            _resourceCallback = this.OCEntityHandler;
            OCStackResult result = OCStack.OCCreateResource(out _handle, resourceTypeName, resourceInterfaceName, uri, _resourceCallback, IntPtr.Zero, OCResourceProperty.OC_DISCOVERABLE | OCResourceProperty.OC_OBSERVABLE | OCResourceProperty.OC_SECURE);

            OCStackException.ThrowIfError(result, "Failed to create resource");
            _uri = uri;
            _resourceProperties = new Dictionary <string, IotivityValueDictionary>();
            if (properties != null)
            {
                _resourceProperties.Add(resourceTypeName, new IotivityValueDictionary(properties));
            }
        }
Esempio n. 9
0
        public void Start()
        {
            if (handle != IntPtr.Zero)
            {
                return;
            }

            var ret = OCStack.OCDoResource(out handle, OCMethod.OC_REST_DISCOVER, requestUri, null, IntPtr.Zero, OCConnectivityType.CT_DEFAULT, OCQualityOfService.OC_LOW_QOS, cbData, null, 0);

            if (ret != OCStackResult.OC_STACK_OK)
            {
                throw new Exception(ret.ToString());
            }
        }
Esempio n. 10
0
        //public static byte[] DeviceId
        //{
        //    get
        //    {
        //        OCUUIdentity identity = null;
        //        var result = OCStack.OCGetDeviceId(out identity);
        //        if (result != OCStackResult.OC_STACK_OK)
        //        {
        //            throw new Exception(result.ToString());
        //        }
        //        return identity.deviceId;
        //    }
        //    set
        //    {
        //        if (value == null || value.Length > 16)
        //        {
        //            throw new ArgumentException(nameof(value));
        //        }
        //        var result = OCStack.OCSetDeviceId(new OCUUIdentity() { deviceId = value });
        //        if (result != OCStackResult.OC_STACK_OK)
        //        {
        //            throw new Exception(result.ToString());
        //        }
        //    }
        //}

        /// <summary>
        /// This function sets device information.
        /// Upon call to OCInit, the default Device Type (i.e. "rt") has already been set to the default
        /// Device Type "oic.wk.d". You do not have to specify "oic.wk.d" in the OCDeviceInfo.types linked
        /// list. The default Device Type is mandatory and always specified by this Device as the first
        /// Device Type.
        /// </summary>
        public static void SetDeviceInfo(string deviceName, IEnumerable <string> types, string specVersion, IEnumerable <string> dataModelVersions)
        {
            IntPtr octypes             = OCStringLL.Create(types);
            IntPtr ocdataModelVersions = OCStringLL.Create(dataModelVersions);
            var    info = new OCDeviceInfo()
            {
                deviceName        = deviceName,
                types             = octypes,
                specVersion       = specVersion,
                dataModelVersions = ocdataModelVersions
            };
            var result = OCStack.OCSetDeviceInfo(info);

            OCStackException.ThrowIfError(result);
        }
Esempio n. 11
0
        public static async Task Shutdown()
        {
            if (tcs == null)
            {
                return;
            }
            ct.Cancel();
            await tcs.Task;
            var result = OCStack.OCStop();

                                        if (result != OCStackResult.OC_STACK_OK)
            {
                throw new Exception(result.ToString());
            }
        }
        public async void Start()
        {
            isRunning = true;
            if (handle != IntPtr.Zero)
            {
                return;
            }
            while (isRunning)
            {
                var ret = OCStack.OCDoResource(out handle, OCMethod.OC_REST_DISCOVER, requestUri, null, IntPtr.Zero, OCConnectivityType.CT_DEFAULT, OCQualityOfService.OC_LOW_QOS, cbData, null, 0);
                OCStackException.ThrowIfError(ret);
                await Task.Delay(5000);

                ret    = OCStack.OCCancel(handle, OCQualityOfService.OC_LOW_QOS, null, 0);
                handle = IntPtr.Zero;
            }
        }
Esempio n. 13
0
        private async Task <ClientResponse <Payload> > SendAsync(string resourceTypeName, Dictionary <string, object> data, OCMethod method)
        {
            var tcs          = new TaskCompletionSource <ClientResponse <Payload> >();
            var callbackData = new OCCallbackData();
            OCClientResponseHandler handler = (context, handle, clientResponse) =>
            {
                GCHandle.FromIntPtr(context).Free();
                if (clientResponse.result > OCStackResult.OC_STACK_RESOURCE_CHANGED)
                {
                    var err = OCStackException.CreateException(clientResponse.result, "Resource returned error");
                    tcs.SetException(err);
                }
                else
                {
                    tcs.SetResult(new ClientResponse <Payload>(clientResponse));
                }
                return(OCStackApplicationResult.OC_STACK_DELETE_TRANSACTION);
            };
            var gcHandle = GCHandle.Alloc(handler);

            callbackData.cb      = handler;
            callbackData.context = GCHandle.ToIntPtr(gcHandle);

            IntPtr payloadHandle = IntPtr.Zero;

            if (resourceTypeName != null)
            {
                RepPayload payload = new RepPayload(data);

                payload.SetUri(_resourceUri);
                payload.Types.Add(resourceTypeName);
                payloadHandle = payload.AsOCRepPayload();
            }

            var result = OCStack.OCDoRequest(out _handle, method, _resourceUri, _address.OCDevAddr, payloadHandle, OCConnectivityType.CT_DEFAULT, OCQualityOfService.OC_LOW_QOS, callbackData, null, 0);

            if (payloadHandle != IntPtr.Zero)
            {
                OCPayloadInterop.OCPayloadDestroy(payloadHandle);
            }
            OCStackException.ThrowIfError(result, "Failed to send to resource");
            var response = await tcs.Task.ConfigureAwait(false);

            return(response);
        }
Esempio n. 14
0
        public static void Initialize(ServiceMode mode, string dataPath = "", string securityDBDatFilename = null)
        {
            storageHandler = new StorageHandler(dataPath, securityDBDatFilename);
            storageHandle  = GCHandle.Alloc(storageHandler);
            var fileresult = OCStack.OCRegisterPersistentStorageHandler(storageHandler.Handle);

            OCStackException.ThrowIfError(fileresult, "Failed to create storage handler");

            //var result = OCStack.OCInit(null, 0, (OCMode)mode);
            var result = OCStack.OCInit2((OCMode)mode, OCTransportFlags.OC_DEFAULT_FLAGS, OCTransportFlags.OC_DEFAULT_FLAGS, OCTransportAdapter.OC_ADAPTER_IP);

            // result = OCStack.OCInit("0.0.0.0", 0, (OCMode)mode);
            OCStackException.ThrowIfError(result);
            globalHandler = OCDefaultDeviceEntityHandler;
            GC.KeepAlive(storageHandler);
            result = OCStack.OCSetDefaultDeviceEntityHandler(globalHandler, IntPtr.Zero);
            OCStackException.ThrowIfError(result, "Failed to send to resource");


            ct  = new CancellationTokenSource();
            tcs = new TaskCompletionSource <object>();

            Task.Run(async() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    var result2 = OCStack.OCProcess();
                    if (result2 != OCStackResult.OC_STACK_OK)
                    {
                        // tcs.SetException(new Exception("OCStackException on Process: " + result2.ToString()));
                        // break;
                    }
                    await Task.Delay(1);
                }
                tcs.SetResult(true);
                tcs = null;
                ct  = null;
            });
        }
Esempio n. 15
0
 public void Dispose()
 {
     OCStack.OCDeleteResource(_handle);
 }
Esempio n. 16
0
        protected void BindInterface(string resourceInterfaceName)
        {
            OCStackResult result = OCStack.OCBindResourceInterfaceToResource(_handle, resourceInterfaceName);

            OCStackException.ThrowIfError(result, "Failed to bind interface");
        }