From aa458ce7de057d45bcc82c58065805746d038569 Mon Sep 17 00:00:00 2001 From: Heejin Kim Date: Thu, 6 Apr 2017 22:16:40 -0700 Subject: [PATCH] Delete Iotivity apps --- apps/examples/Kconfig | 2 - apps/examples/iotivity/Kconfig | 117 -- apps/examples/iotivity/Kconfig_ENTRY | 3 - apps/examples/iotivity/Makefile | 299 ---- apps/examples/iotivity/ca_main.c | 1688 --------------------- apps/examples/iotivity/data/data.dat | 1 - apps/examples/iotivity/data/oic_svr_db_server.dat | Bin 997 -> 0 bytes apps/examples/iotivity/iotivity_cloud_main.c | 955 ------------ apps/examples/iotivity/iotivity_main.c | 1264 --------------- apps/examples/iotivity/iotivity_sec_main.c | 676 --------- apps/examples/iotivity/iotivityopts.h | 90 -- apps/examples/iotivity/mkfsdata.pl | 125 -- apps/examples/iotivity/ocsecurity.c | 254 ---- apps/examples/iotivity/ocserver.h | 133 -- apps/examples/iotivity/port_tinyara.c | 159 -- apps/examples/iotivity/uuid/uuid.h | 121 -- 16 files changed, 5887 deletions(-) delete mode 100644 apps/examples/iotivity/Kconfig delete mode 100644 apps/examples/iotivity/Kconfig_ENTRY delete mode 100644 apps/examples/iotivity/Makefile delete mode 100644 apps/examples/iotivity/ca_main.c delete mode 100644 apps/examples/iotivity/data/data.dat delete mode 100644 apps/examples/iotivity/data/oic_svr_db_server.dat delete mode 100644 apps/examples/iotivity/iotivity_cloud_main.c delete mode 100644 apps/examples/iotivity/iotivity_main.c delete mode 100644 apps/examples/iotivity/iotivity_sec_main.c delete mode 100644 apps/examples/iotivity/iotivityopts.h delete mode 100755 apps/examples/iotivity/mkfsdata.pl delete mode 100644 apps/examples/iotivity/ocsecurity.c delete mode 100644 apps/examples/iotivity/ocserver.h delete mode 100644 apps/examples/iotivity/port_tinyara.c delete mode 100644 apps/examples/iotivity/uuid/uuid.h diff --git a/apps/examples/Kconfig b/apps/examples/Kconfig index 546b63c..223647b 100644 --- a/apps/examples/Kconfig +++ b/apps/examples/Kconfig @@ -18,7 +18,6 @@ source "$APPSDIR/examples/fota_sample/Kconfig_ENTRY" source "$APPSDIR/examples/hello/Kconfig_ENTRY" source "$APPSDIR/examples/hello_tash/Kconfig_ENTRY" source "$APPSDIR/examples/helloxx/Kconfig_ENTRY" -source "$APPSDIR/examples/iotivity/Kconfig_ENTRY" source "$APPSDIR/examples/iperf/Kconfig_ENTRY" source "$APPSDIR/examples/kernel_sample/Kconfig_ENTRY" source "$APPSDIR/examples/mdns_test/Kconfig_ENTRY" @@ -54,7 +53,6 @@ source "$APPSDIR/examples/fota_sample/Kconfig" source "$APPSDIR/examples/hello/Kconfig" source "$APPSDIR/examples/hello_tash/Kconfig" source "$APPSDIR/examples/helloxx/Kconfig" -source "$APPSDIR/examples/iotivity/Kconfig" source "$APPSDIR/examples/iperf/Kconfig" source "$APPSDIR/examples/kernel_sample/Kconfig" source "$APPSDIR/examples/mdns_test/Kconfig" diff --git a/apps/examples/iotivity/Kconfig b/apps/examples/iotivity/Kconfig deleted file mode 100644 index f75ba9e..0000000 --- a/apps/examples/iotivity/Kconfig +++ /dev/null @@ -1,117 +0,0 @@ -# -# For a description of the syntax of this configuration file, -# see kconfig-language at https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt -# - -config EXAMPLES_IOTIVITY - bool "IOTIVITY demo" - default n - depends on ENABLE_IOTIVITY - ---help--- - Enable the IOTIVITY demo - -config EXAMPLES_IOTIVITY_CLOUD - bool "IOTIVITY cloud demo" - default n - depends on ENABLE_IOTIVITY_CLOUD - ---help--- - Enable the IOTIVITY cloud demo - -config EXAMPLE_IOTIVITY_SECURED - bool "IOTIVITY demo with security enabled" - default n - depends on ENABLE_IOTIVITY_SECURED - ---help--- - Enable the IOTIVITY demo with security - -if EXAMPLES_IOTIVTIY - -config EXAMPLES_IOTIVITY_PROGNAME - string "Program name" - default "iotivity" - depends on BUILD_KERNEL - ---help--- - This is the name of the program that will be use when the TASH ELF - program is installed. - -config USER_ENTRYPOINT - string - default "iotivity_main" if ENTRY_IOTIVITY - -endif - -if EXAMPLES_IOTIVTIY_CLOUD - -config EXAMPLES_IOTIVITY_PROGNAME - string "Program name" - default "iotivity_cloud" - depends on BUILD_KERNEL - ---help--- - This is the name of the program that will be use when the TASH ELF - program is installed. - -config USER_ENTRYPOINT - string - default "iotivity_cloud_main" if ENTRY_IOTIVITY_CLOUD - -endif - -if EXAMPLES_IOTIVTIY_SECURED - -config EXAMPLES_IOTIVITY_PROGNAME - string "Program name" - default "iotivity_sec" - depends on BUILD_KERNEL - ---help--- - This is the name of the program that will be use when the TASH ELF - program is installed. - -config USER_ENTRYPOINT - string - default "iotivity_sec_main" if ENTRY_IOTIVITY_SECURED - -endif - -config TB_LOG - bool "enable / disable iotivity stack logs" - default n - depends on ENABLE_IOTIVITY - ---help--- - select to enable all iotivity stack logs (DEBUG / INFO etc.) - -config TCP_ADAPTER - bool "enable / disable TCP_ADAPTER in iotivity stack" - default n - depends on ENABLE_IOTIVITY - ---help--- - select to enable TCP_ADAPTER in iotivity stack - -config WITH_TCP - bool "build iotivity stack with TCP enabled" - default n - depends on ENABLE_IOTIVITY - ---help--- - required to makeuse of TCP adapter (by libcoap module) - -config WITH_DTLS - bool "enable / disable iotivity secure data transmission" - default n - depends on ENABLE_IOTIVITY - ---help--- - select to enable DTLS security mechanism in Iotivity for data in transit - -config WITH_SHA256 - bool "enable / disable SHA256 encryption in iotivity" - default n - depends on ENABLE_IOTIVITY - ---help--- - select to enable SHA256 mode of security in IoTivity - -config WITH_X509 - bool "standard for a public key infrastructure (PKI) to manage digital certificates" - default n - depends on ENABLE_IOTIVITY - ---help--- - select to enable X509 standard for PKI in IoTivity - - diff --git a/apps/examples/iotivity/Kconfig_ENTRY b/apps/examples/iotivity/Kconfig_ENTRY deleted file mode 100644 index 825a63d..0000000 --- a/apps/examples/iotivity/Kconfig_ENTRY +++ /dev/null @@ -1,3 +0,0 @@ -config ENTRY_IOTIVITY - bool "IOTIVITY demo" - depends on EXAMPLES_IOTIVITY diff --git a/apps/examples/iotivity/Makefile b/apps/examples/iotivity/Makefile deleted file mode 100644 index 7704445..0000000 --- a/apps/examples/iotivity/Makefile +++ /dev/null @@ -1,299 +0,0 @@ -########################################################################### -# -# Copyright 2016 Samsung Electronics All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -########################################################################### -############################################################################ -# apps/examples/iotivity/Makefile -# -# Copyright (C) 2007-2012, 2014 Gregory Nutt. All rights reserved. -# Author: Gregory Nutt -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the -# distribution. -# 3. Neither the name NuttX nor the names of its contributors may be -# used to endorse or promote products derived from this software -# without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS -# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -############################################################################ - --include $(TOPDIR)/.config --include $(TOPDIR)/Make.defs -include $(APPDIR)/Make.defs - -# iotivity built-in application info - -APPNAME = iotivity -PRIORITY = SCHED_PRIORITY_DEFAULT -STACKSIZE = 16384 - - - -# TinyAra Iotivity - -ifeq ($(CONFIG_IOTIVITY_SCONS_BUILD),y) - IOTIVITY_RELEASE = 1.2-rel - IOTIVITY_BASE_DIR = $(APPDIR)/../external/iotivity/iotivity_$(IOTIVITY_RELEASE) -else - IOTIVITY_APP_DIR = $(APPDIR)/../external/iotivity/iotivity_1.1.0 - IOTIVITY_SECURITY_APP_DIR = $(IOTIVITY_APP_DIR)/resource/csdk/security/src - IOTIVITY_CONNECTIVITY_ADAPTER_UTIL_DIR = $(IOTIVITY_APP_DIR)/resource/csdk/connectivity/src/adapter_util -endif - -ASRCS = -ifeq ($(CONFIG_IOTIVITY_SCONS_BUILD),y) -CFLAGS += -I$(IOTIVITY_BASE_DIR)/resource/csdk/stack/include -CFLAGS += -I$(IOTIVITY_BASE_DIR)/resource/c_common -CFLAGS += -I$(IOTIVITY_BASE_DIR)/resource/csdk/logger/include -CFLAGS += -I$(IOTIVITY_BASE_DIR)/resource/csdk/security/include -else -CFLAGS += -I$(IOTIVITY_APP_DIR)/extlibs/tinycbor/tinycbor -CFLAGS += -I$(IOTIVITY_APP_DIR)/extlibs/tinycbor/tinycbor/src -CFLAGS += -I$(IOTIVITY_APP_DIR)/extlibs/tinydtls -CFLAGS += -I$(IOTIVITY_APP_DIR)/extlibs/tinydtls/aes -CFLAGS += -I$(IOTIVITY_APP_DIR)/extlibs/tinydtls/ecc -CFLAGS += -I$(IOTIVITY_APP_DIR)/extlibs/tinydtls/sha2 -CFLAGS += -I$(IOTIVITY_APP_DIR)/extlibs/cjson -CFLAGS += -I$(IOTIVITY_APP_DIR)/extlibs/timer -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/oc_logger/include -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/c_common -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/stack/include -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/connectivity/lib/libcoap-4.1.1 -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/c_common/ocrandom/include -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/c_common/oic_malloc/include -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/c_common/oic_string/include -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/c_common/oic_time/include -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/connectivity/api -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/connectivity/common/inc -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/connectivity/inc -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/connectivity/inc/pkix -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/logger/include -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/security/include -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/security/include/internal -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/stack/include/internal -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/stack/include/ -ifeq ($(CONFIG_ROUTING_EP),y) -CFLAGS += -I$(IOTIVITY_APP_DIR)/resource/csdk/routing/include/ -endif -ifeq ($(CONFIG_ENABLE_IOTIVITY_CLOUD),y) -CFLAGS += -I$(IOTIVITY_APP_DIR)/cloud/samples/client/ -endif -endif #CONFIG_IOTIVITY_SCONS_BUILD - -ifneq ($(CONFIG_IOTIVITY_SCONS_BUILD),y) - -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/extlibs/tinycbor/tinycbor/src/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/extlibs/cjson/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/extlibs/timer/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/c_common/ocrandom/src/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/c_common/oic_malloc/src/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/c_common/oic_string/src/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/c_common/oic_time/src/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/csdk/connectivity/common/src/*.c) - -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/csdk/connectivity/src/ip_adapter/*.c) -ifeq ($(CONFIG_TCP_ADAPTER),y) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/csdk/connectivity/src/tcp_adapter/*.c) -endif -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/csdk/connectivity/src/ip_adapter/linux/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/csdk/connectivity/src/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/csdk/logger/src/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/csdk/connectivity/lib/libcoap-4.1.1/*.c) -CSRCS += $(IOTIVITY_CONNECTIVITY_ADAPTER_UTIL_DIR)/caadapterutils.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/secureresourcemanager.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/resourcemanager.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/aclresource.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/amaclresource.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/amsmgr.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/pstatresource.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/doxmresource.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/credresource.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/svcresource.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/pconfresource.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/dpairingresource.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/verresource.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/policyengine.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/psinterface.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/srmresourcestrings.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/srmutility.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/iotvticalendar.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/iotivitybase64.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/directpairing.c - -#IOTIVITY CLOUD COMPILATION FILES - -ifeq ($(CONFIG_ENABLE_IOTIVITY_CLOUD),y) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/cloud/samples/client/*.c) -endif - -#IOTIVITY SECURITY COMPILATION FILES -#CONFIG_ENABLE_IOTIVITY_SECURED is aligned to SECURED flag in iotivity linux build -#CONFIG_WITH_X509 is aligned to DTLS_WITH_X509 flag in iotivity linux build - - -ifeq ($(CONFIG_ENABLE_IOTIVITY_SECURED),y) - -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/extlibs/tinydtls/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/extlibs/tinydtls/aes/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/extlibs/tinydtls/ecc/*.c) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/extlibs/tinydtls/sha2/*.c) -CSRCS += $(IOTIVITY_CONNECTIVITY_ADAPTER_UTIL_DIR)/caadapternetdtls.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/oxmpincommon.c -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/pbkdf2.c -ifeq ($(CONFIG_WITH_X509),y) -CSRCS += $(IOTIVITY_SECURITY_APP_DIR)/crlresource.c -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/csdk/connectivity/src/adapter_util/pkix/*.c) -endif -endif -endif #CONFIG_IOTIVITY_SCONS_BUILD - -ifneq ($(CONFIG_IOTIVITY_SCONS_BUILD),y) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/csdk/stack/src/*.c) -ifeq ($(CONFIG_ROUTING_EP),y) -CSRCS += $(wildcard $(IOTIVITY_APP_DIR)/resource/csdk/routing/src/*.c) -endif -endif #CONFIG_IOTIVITY_SCONS_BUILD - -# Port TinyAra -CSRCS += port_tinyara.c - -MAINSRC = iotivity_main.c - -ifeq ($(CONFIG_ENABLE_IOTIVITY_CLOUD),y) -MAINSRC += iotivity_cloud_main.c -endif - -ifeq ($(CONFIG_ENABLE_IOTIVITY_SECURED),y) -MAINSRC += iotivity_sec_main.c file_data.c -CFLAGS += -D__WITH_DTLS__ -endif - -CFLAGS += -DWITH_POSIX -DIP_ADAPTER -CFLAGS += -DWITH_BWT -ifeq ($(CONFIG_IOTIVITY_ROUTING),"EP") -CFLAGS += -DROUTING_EP -else -CFLAGS += -DROUTING_GW -endif -CFLAGS += -D__TINYARA__ -CFLAGS += -std=c99 -CFLAGS += -w - -AOBJS = $(ASRCS:.S=$(OBJEXT)) -COBJS = $(CSRCS:.c=$(OBJEXT)) -MAINOBJ = $(MAINSRC:.c=$(OBJEXT)) - -SRCS = $(ASRCS) $(CSRCS) $(MAINSRC) -OBJS = $(AOBJS) $(COBJS) - -ifneq ($(CONFIG_BUILD_KERNEL),y) - OBJS += $(MAINOBJ) -endif - -ifeq ($(CONFIG_WINDOWS_NATIVE),y) - BIN = ..\..\libapps$(LIBEXT) -else -ifeq ($(WINTOOL),y) - BIN = ..\\..\\libapps$(LIBEXT) -else - BIN = ../../libapps$(LIBEXT) -endif -endif - -ifeq ($(WINTOOL),y) - INSTALL_DIR = "${shell cygpath -w $(BIN_DIR)}" -else - INSTALL_DIR = $(BIN_DIR) -endif - -CONFIG_EXAMPLES_IOTIVITY_PROGNAME ?= iotivity$(EXEEXT) -PROGNAME = $(CONFIG_EXAMPLES_IOTIVITY_PROGNAME) - -ROOTDEPPATH = --dep-path . - -# Common build - -VPATH = - -all: .built -.PHONY: clean depend distclean - -$(AOBJS): %$(OBJEXT): %.S - $(call ASSEMBLE, $<, $@) - -$(COBJS) $(MAINOBJ): %$(OBJEXT): %.c - $(call COMPILE, $<, $@) - -.built: $(OBJS) - $(call ARCHIVE, $(BIN), $(OBJS)) - @touch .built - -file_data.c: data/* - $(Q) ./mkfsdata.pl - -ifeq ($(CONFIG_BUILD_KERNEL),y) -$(BIN_DIR)$(DELIM)$(PROGNAME): $(OBJS) $(MAINOBJ) - @echo "LD: $(PROGNAME)" - $(Q) $(LD) $(LDELFFLAGS) $(LDLIBPATH) -o $(INSTALL_DIR)$(DELIM)$(PROGNAME) $(ARCHCRT0OBJ) $(MAINOBJ) $(LDLIBS) - $(Q) $(NM) -u $(INSTALL_DIR)$(DELIM)$(PROGNAME) - -install: $(BIN_DIR)$(DELIM)$(PROGNAME) - -else -install: - -endif - -context: - -.depend: Makefile $(SRCS) - @$(MKDEP) $(ROOTDEPPATH) "$(CC)" -- $(CFLAGS) -- $(SRCS) >Make.dep - @touch $@ - -depend: .depend - -custom_clean: - $(foreach OBJFILE, $(OBJS), rm -f $(OBJFILE)) - -clean: custom_clean - $(call DELFILE, .built) - $(call CLEAN) - -distclean: clean - $(call DELFILE, Make.dep) - $(call DELFILE, .depend) - --include Make.dep diff --git a/apps/examples/iotivity/ca_main.c b/apps/examples/iotivity/ca_main.c deleted file mode 100644 index 7fe0003..0000000 --- a/apps/examples/iotivity/ca_main.c +++ /dev/null @@ -1,1688 +0,0 @@ -/**************************************************************************** - * - * Copyright 2016 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific - * language governing permissions and limitations under the License. - * - ****************************************************************************/ - -#include -#include -#include -#include -#include -#include - -#include "cacommon.h" -#include "cainterface.h" -#include "oic_string.h" - -#if 0 -#define MAX_BUF_LEN 1024 -#else -#define MAX_BUF_LEN 100 -#endif -#define MAX_OPT_LEN 16 - -#define PORT_LENGTH 5 - -#define SECURE_DEFAULT_PORT 5684 - -#define RESOURCE_URI_LENGTH 14 - -#define SYSTEM_INVOKE_ERROR 127 -#define SYSTEM_ERROR -1 - -#ifdef WITH_BWT -#define BLOCK_SIZE(arg) (1 << ((arg) + 4)) -#endif - -// Iotivity Device Identity. -const unsigned char IDENTITY[] = ("1111111111111111"); - -// PSK between this device and peer device. -const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA"); - -int g_received; -uint16_t g_local_secure_port = SECURE_DEFAULT_PORT; -CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP; -const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"}; - -typedef struct -{ - char ipAddress[CA_IPADDR_SIZE]; - uint16_t port; -} addressSet_t; - -char get_menu(); -void process(); -CAResult_t get_network_type(); -CAResult_t get_input_data(char *buf, int32_t length); - -bool select_payload_type(); -CAPayload_t get_binary_payload(size_t *payloadLength); -bool read_file(const char *name, CAPayload_t *bytes, size_t *length); -void create_file(CAPayload_t bytes, size_t length); - -void start_listening_server(); -void start_discovery_server(); -void send_request(); -void send_request_all(); -void send_notification(); -void select_network(); -void unselect_network(); -void handle_request_response(); -void get_network_info(); -void send_secure_request(); - -void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo); -void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo); -void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t *errorInfo); -void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info); -void get_resource_uri(char *URI, char *resourceURI, int length); -int get_secure_information(CAPayload_t payLoad); -bool get_address_set(const char *pAddress, addressSet_t *outAddress); -void parsing_coap_uri(const char *uri, addressSet_t *address, CATransportFlags_t *flags); -CAHeaderOption_t *get_option_data(CAInfo_t *requestData); - -static CAToken_t g_last_request_token = NULL; - -static const char COAP_PREFIX[] = "coap://"; -static const char COAPS_PREFIX[] = "coaps://"; -static const char COAP_TCP_PREFIX[] = "coap+tcp://"; - -static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1; -static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1; -static const uint16_t COAP_TCP_PREFIX_LEN = sizeof(COAP_TCP_PREFIX) - 1; - -static const char SECURE_INFO_DATA[] = - "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"]," - "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":" - "%d}}]}"; -static const char NORMAL_INFO_DATA[] = - "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"]," - "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}"; - -#ifdef __WITH_DTLS__ -#ifdef __WITH_X509__ -int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo) -{ - (void) credInfo; - return -1; -} -int *GetCRLResource() -{ - return (int *) NULL; -} -#endif //__WITH_X509__ - -// Internal API. Invoked by CA stack to retrieve credentials from this module -int32_t CAGetDtlsPskCredentials(CADtlsPskCredType_t type, - const unsigned char *desc, size_t desc_len, - unsigned char *result, size_t result_length) -{ - printf("CAGetDtlsPskCredentials IN\n"); - - int32_t ret = -1; - - if (NULL == result) - { - return ret; - } - - switch (type) - { - case CA_DTLS_PSK_HINT: - case CA_DTLS_PSK_IDENTITY: - - if (result_length < sizeof(IDENTITY)) - { - printf("ERROR : Wrong value for result for storing IDENTITY"); - return ret; - } - - memcpy(result, IDENTITY, sizeof(IDENTITY)); - ret = sizeof(IDENTITY); - break; - - case CA_DTLS_PSK_KEY: - - if ((desc_len == sizeof(IDENTITY)) && - memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0) - { - if (result_length < sizeof(RS_CLIENT_PSK)) - { - printf("ERROR : Wrong value for result for storing RS_CLIENT_PSK"); - return ret; - } - - memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK)); - ret = sizeof(RS_CLIENT_PSK); - } - break; - - default: - - printf("Wrong value passed for PSK_CRED_TYPE."); - ret = -1; - } - - printf("CAGetDtlsPskCredentials OUT\n"); - return ret; -} - -#endif //__WITH_DTLS__ -#ifdef CONFIG_BUILD_KERNEL -int main(int argc, FAR char *argv[]) -#else -int iotivity_main(int argc, char *argv[]) -#endif -{ - - /* - int ret = system("clear"); - // shell invoke error: 127, others: -1 - if (SYSTEM_INVOKE_ERROR == ret || SYSTEM_ERROR == ret) - { - printf("Terminal Clear Error: %d\n", ret); - return -1; - } - */ - printf("=============================================\n"); - printf("\t\tsample main\n"); - printf("=============================================\n"); - - CAResult_t res = CAInitialize(); - if (CA_STATUS_OK != res) - { - printf("CAInitialize fail\n"); - return -1; - } - - // Set the PSK Credentials callback handler. -#ifdef __WITH_DTLS__ - res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials); - if (CA_STATUS_OK != res) - { - printf("Register credential handler fail\n"); - return -1; - } -#endif - - // set handler. - CARegisterHandler(request_handler, response_handler, error_handler); - - process(); - - CADestroyToken(g_last_request_token); - - g_last_request_token = NULL; - - CATerminate(); - return 0; -} - -void process() -{ - while (1) - { - char menu = get_menu(); - - switch (menu) - { - case 'm': // menu - case 'M': - break; - - case 'q': // quit - case 'Q': - printf("quit..!!\n"); - return; - - case 's': // start server - case 'S': - start_listening_server(); - break; - - case 't': // send request - case 'T': - send_request_all(); - break; - - case 'c': // start client - case 'C': - start_discovery_server(); - break; - - case 'r': // send request - case 'R': - send_request(); - break; - - case 'b': // send notification - case 'B': - send_notification(); - break; - - case 'n': // select network - case 'N': - select_network(); - break; - - case 'x': // unselect network - case 'X': - unselect_network(); - break; - - case 'h': // handle request response - case 'H': - handle_request_response(); - break; - - case 'w': - case 'W': - g_received = 0; - start_discovery_server(); - send_secure_request(); - while (g_received == 0) - { - sleep(1); - handle_request_response(); - } - break; - - case 'z': - case 'Z': - start_listening_server(); - while (1) - { - sleep(1); - handle_request_response(); - } - break; - - case 'g': // get network information - case 'G': - get_network_info(); - break; - - default: - printf("not supported menu!!\n"); - break; - } - } -} - -void start_listening_server() -{ - printf("start listening server!!\n"); - - CAResult_t res = CAStartListeningServer(); - if (CA_STATUS_OK != res) - { - printf("start listening server fail, error code : %d\n", res); - } - else - { - printf("start listening server success\n"); - } -} - -void start_discovery_server() -{ - printf("start discovery client!!\n"); - - CAResult_t res = CAStartDiscoveryServer(); - if (CA_STATUS_OK != res) - { - printf("start discovery client fail, error code : %d\n", res); - } - else - { - printf("start discovery client success\n"); - } -} - -bool select_payload_type() -{ - char buf[MAX_BUF_LEN] = {0}; - printf("\n=============================================\n"); - printf("Normal Payload : 0\nBig Payload : 1\n"); - printf("select Payload type : "); - - CAResult_t res = get_input_data(buf, sizeof(buf)); - if (CA_STATUS_OK != res) - { - printf("Payload type selection error\n"); - printf("Default: Using normal Payload\n"); - return false; - } - - return (buf[0] == '1') ? true : false; -} - -CAPayload_t get_binary_payload(size_t *payloadLength) -{ - CAPayload_t binaryPayload = NULL; - bool result = read_file("sample_input.txt", &binaryPayload, payloadLength); - if (false == result) - { - return NULL; - } - - return binaryPayload; -} - -void send_request() -{ - printf("\ninside Send_request() \n"); - CAResult_t res = get_network_type(); - if (CA_STATUS_OK != res) - { - return; - } - - printf("\nDo you want to send secure request ?.... enter (0/1): "); - - char secureRequest[MAX_BUF_LEN] = {0}; - if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN)) - { - return; - } - - if (strcmp(secureRequest, "1") == 0) - { - printf("Enter the URI like below....\n"); - printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n"); - } - else if (strcmp(secureRequest, "0") == 0) - { - printf("Enter the URI like below....\n"); - printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n"); - printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n"); - printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n"); - } - else - { - printf("Input data is wrong value\n"); - return; - } - - char uri[MAX_BUF_LEN] = "coaps://192.168.11.101:1025/core.light"; - /*if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN)) - { - return; - }*/ - - // create remote endpoint - CAEndpoint_t *endpoint = NULL; - CATransportFlags_t flags; - - printf("URI : %s\n", uri); - addressSet_t address = {{}, 0}; - parsing_coap_uri(uri, &address, &flags); - - res = CACreateEndpoint(flags, g_selected_nw_type, - (const char *)address.ipAddress, address.port, &endpoint); - if (CA_STATUS_OK != res || !endpoint) - { - printf("Failed to create remote endpoint, error code : %d\n", res); - return; - } - - printf("\n=============================================\n"); - printf("0:CON, 1:NON\n"); - printf("select message type : "); - - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) - { - CADestroyEndpoint(endpoint); - return; - } - - CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0; - - // create token - CAToken_t token = NULL; - uint8_t tokenLength = CA_MAX_TOKEN_LEN; - - res = CAGenerateToken(&token, tokenLength); - if ((CA_STATUS_OK != res) || (!token)) - { - printf("Token generate error, error code : %d\n", res); - CADestroyEndpoint(endpoint); - return; - } - - printf("Generated token %s\n", token); - - // extract relative resourceuri from give uri - char resourceURI[RESOURCE_URI_LENGTH + 1] = {0}; - get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH); - printf("resourceURI : %s\n", resourceURI); - - // create request data - CAInfo_t requestData = { .type = msgType, - .messageId = 0, - .token = token, - .tokenLength = tokenLength, - .options = NULL, - .numOptions = 0, - .payload = NULL, - .payloadSize = 0, - .resourceUri = (CAURI_t)resourceURI - }; - - if (strcmp(secureRequest, "1") == 0) - { - size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI); - requestData.payload = (CAPayload_t) calloc(length, sizeof(char)); - if (NULL == requestData.payload) - { - printf("Memory allocation fail\n"); - CADestroyEndpoint(endpoint); - CADestroyToken(token); - return; - } - snprintf((char *) requestData.payload, length, SECURE_INFO_DATA, - (const char *) resourceURI, g_local_secure_port); - requestData.payloadSize = length; - } - else - { - bool useBigPayload = select_payload_type(); - if (useBigPayload) - { - size_t payloadLength = 0; - CAPayload_t binaryPayload = get_binary_payload(&payloadLength); - if (!binaryPayload) - { - free(binaryPayload); - CADestroyToken(token); - CADestroyEndpoint(endpoint); - return; - } - - requestData.payload = (CAPayload_t) malloc(payloadLength); - if (NULL == requestData.payload) - { - printf("Memory allocation failed!"); - free(binaryPayload); - CADestroyToken(token); - CADestroyEndpoint(endpoint); - return; - } - memcpy(requestData.payload, binaryPayload, payloadLength); - requestData.payloadSize = payloadLength; - - // memory free - free(binaryPayload); - } - else - { - size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI); - requestData.payload = (CAPayload_t) calloc(length, sizeof(char)); - if (NULL == requestData.payload) - { - printf("Memory allocation fail\n"); - CADestroyEndpoint(endpoint); - CADestroyToken(token); - return; - } - snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA, - (const char *) resourceURI); - requestData.payloadSize = length; - } - } - - //CAHeaderOption_t* headerOpt = get_option_data(&requestData); - - CARequestInfo_t requestInfo = { .method = CA_GET, - .info = requestData, - .isMulticast = false - }; - - // send request - res = CASendRequest(endpoint, &requestInfo); - if (CA_STATUS_OK != res) - { - printf("Could not send request : %d\n", res); - } - - /* if (headerOpt) - { - free(headerOpt); - }*/ - - //destroy token - CADestroyToken(token); - // destroy remote endpoint - CADestroyEndpoint(endpoint); - free(requestData.payload); - - printf("=============================================\n"); -} - -void send_secure_request() -{ - char uri[MAX_BUF_LEN]; - char ipv4addr[CA_IPADDR_SIZE]; - - printf("\n=============================================\n"); - printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n"); - - if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE)) - { - return; - } - snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", COAPS_PREFIX, ipv4addr); - - // create remote endpoint - CAEndpoint_t *endpoint = NULL; - CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint); - if (CA_STATUS_OK != res) - { - printf("Failed to create remote endpoint, error code: %d\n", res); - goto exit; - } - - // create token - CAToken_t token = NULL; - uint8_t tokenLength = CA_MAX_TOKEN_LEN; - - res = CAGenerateToken(&token, tokenLength); - if (CA_STATUS_OK != res) - { - printf("Token generate error, error code : %d\n", res); - goto exit; - } - - printf("Generated token %s\n", token); - - // create request data - CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM, - .messageId = 0, - .token = token, - .tokenLength = tokenLength, - .options = NULL, - .numOptions = 0, - .payload = NULL, - .payloadSize = 0, - .resourceUri = NULL - }; - - CARequestInfo_t requestInfo = { .method = CA_GET, - .info = requestData, - .isMulticast = false - }; - - // send request - CASendRequest(endpoint, &requestInfo); - -exit: - // cleanup - CADestroyToken(token); - CADestroyEndpoint(endpoint); - printf("=============================================\n"); -} - - -void send_request_all() -{ - CAResult_t res = get_network_type(); - if (CA_STATUS_OK != res) - { - return; - } - - printf("\n=============================================\n"); - printf("ex) /a/light\n"); - printf("resource uri : "); - - char resourceURI[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN)) - { - return; - } - - // create remote endpoint - CAEndpoint_t *group = NULL; - res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &group); - if (CA_STATUS_OK != res) - { - printf("Create remote endpoint error, error code: %d\n", res); - return; - } - - // create token - CAToken_t token = NULL; - uint8_t tokenLength = CA_MAX_TOKEN_LEN; - - res = CAGenerateToken(&token, tokenLength); - if ((CA_STATUS_OK != res) || (!token)) - { - printf("Token generate error!!\n"); - CADestroyEndpoint(group); - return; - } - - printf("generated token %s\n", token); - - // create request data - CAPayload_t payload = (CAPayload_t) "TempJsonPayload"; - size_t payloadSize = strlen((const char *) payload); - - CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM, - .messageId = 0, - .token = token, - .tokenLength = tokenLength, - .options = NULL, - .numOptions = 0, - .payload = payload, - .payloadSize = payloadSize, - .resourceUri = (CAURI_t) resourceURI - }; - - CARequestInfo_t requestInfo = { .method = CA_GET, - .info = requestData, - .isMulticast = true - }; - - CAHeaderOption_t *headerOpt = get_option_data(&requestData); - - // send request - res = CASendRequest(group, &requestInfo); - if (CA_STATUS_OK != res) - { - printf("Could not send request to all\n"); - CADestroyToken(token); - } - else - { - CADestroyToken(g_last_request_token); - g_last_request_token = token; - } - - if (headerOpt) - { - free(headerOpt); - } - - // destroy remote endpoint - CADestroyEndpoint(group); - - printf("=============================================\n"); -} - -void send_notification() -{ - CAResult_t res = get_network_type(); - if (CA_STATUS_OK != res) - { - return; - } - - printf("\n=============================================\n"); - printf("Enter the URI like below....\n"); - printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n"); - printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n"); - printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n"); - printf("uri : "); - - char uri[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN)) - { - return; - } - - printf("\n=============================================\n"); - printf("\tselect message type\n"); - printf("CON : 0\n"); - printf("NON : 1\n"); - printf("ACK : 2\n"); - printf("RESET : 3\n"); - printf("select : "); - - char messageTypeBuf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN)) - { - return; - } - - int messageType = messageTypeBuf[0] - '0'; - - CATransportFlags_t flags; - addressSet_t address = {{}, 0}; - parsing_coap_uri(uri, &address, &flags); - - // create remote endpoint - CAEndpoint_t *endpoint = NULL; - res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint); - if (CA_STATUS_OK != res) - { - printf("Create remote endpoint error, error code: %d\n", res); - return; - } - - // create token - CAToken_t token = NULL; - uint8_t tokenLength = CA_MAX_TOKEN_LEN; - - res = CAGenerateToken(&token, tokenLength); - if ((CA_STATUS_OK != res) || (!token)) - { - printf("Token generate error!!\n"); - CADestroyEndpoint(endpoint); - return; - } - - printf("Generated token %s\n", token); - - // create response data - CAPayload_t payload = (CAPayload_t) "TempNotificationData"; - size_t payloadSize = strlen((const char *) payload); - - CAInfo_t requestData = { .type = messageType, - .messageId = 0, - .token = token, - .tokenLength = tokenLength, - .options = NULL, - .numOptions = 0, - .payload = payload, - .payloadSize = payloadSize, - .resourceUri = (CAURI_t) uri - }; - - CARequestInfo_t requestInfo = { .method = CA_GET, - .info = requestData - }; - - // send request - res = CASendRequest(endpoint, &requestInfo); - if (CA_STATUS_OK != res) - { - printf("Send notification error, error code: %d\n", res); - } - else - { - printf("Send notification success\n"); - } - - // destroy token - CADestroyToken(token); - // destroy remote endpoint - CADestroyEndpoint(endpoint); - - printf("\n=============================================\n"); -} - -void select_network() -{ - printf("\n=============================================\n"); - printf("\tselect network\n"); - printf("IP : 0\n"); - printf("GATT : 1\n"); - printf("RFCOMM : 2\n"); - printf("TCP : 4\n"); - printf("select : "); - - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) - { - return; - } - - int number = buf[0] - '0'; - - if (number < 0 || number > 4) - { - printf("Invalid network type\n"); - return; - } - - CAResult_t res = CASelectNetwork(1 << number); - if (CA_STATUS_OK != res) - { - printf("Select network error\n"); - } - else - { - printf("Select network success\n"); - } - - printf("=============================================\n"); -} - -void unselect_network() -{ - printf("\n=============================================\n"); - printf("\tunselect enabled network\n"); - printf("IP : 0\n"); - printf("GATT : 1\n"); - printf("RFCOMM : 2\n"); - printf("TCP : 4\n"); - printf("select : "); - - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) - { - return; - } - - int number = buf[0] - '0'; - - if (number < 0 || number > 4) - { - printf("Invalid network type\n"); - return; - } - - CAResult_t res = CAUnSelectNetwork(1 << number); - if (CA_STATUS_OK != res) - { - printf("Unselect network error\n"); - } - else - { - printf("Unselect network success\n"); - } - - printf("=============================================\n"); -} - -char get_menu() -{ - printf("\n=============================================\n"); - printf("\t\tMenu\n"); - printf("\ts : start server\n"); - printf("\tc : start client\n"); - printf("\tr : send request\n"); - printf("\tt : send request to all\n"); - printf("\tb : send notification\n"); - printf("\tn : select network\n"); - printf("\tx : unselect network\n"); - printf("\tg : get network information\n"); - printf("\th : handle request response\n"); - printf("\tz : run static server\n"); - printf("\tw : send secure request\n"); - printf("\tq : quit\n"); - printf("=============================================\n"); - printf("select : "); - - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) - { - printf("Failed to get input data\n"); - } - - return buf[0]; -} - -void handle_request_response() -{ - printf("Handle_request_response\n"); - - CAResult_t res = CAHandleRequestResponse(); - if (CA_STATUS_OK != res) - { - printf("Handle request error, error code: %d\n", res); - } - else - { - printf("Handle request success\n"); - } -} - -void get_network_info() -{ - CAEndpoint_t *tempInfo = NULL; - uint32_t tempSize = 0; - - CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize); - if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize) - { - printf("Network not connected\n"); - free(tempInfo); - return; - } - - printf("################## Network Information #######################\n"); - printf("Network info total size is %d\n\n", tempSize); - - for (uint32_t index = 0; index < tempSize; index++) - { - printf("Type: %d\n", tempInfo[index].adapter); - printf("Address: %s\n", tempInfo[index].addr); - if (CA_ADAPTER_IP == tempInfo[index].adapter) - { - printf("Port: %d\n", tempInfo[index].port); - printf("Secured: %s flag : %x\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" : - "false", tempInfo[index].flags); - - if (tempInfo[index].flags & CA_SECURE) - { - g_local_secure_port = tempInfo[index].port; - printf("Secured: in global %d\n\n", g_local_secure_port); - } - } - } - - free(tempInfo); - printf("##############################################################"); -} - -void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo) -{ - if (NULL == object || NULL == requestInfo) - { - printf("Input parameter is NULL\n"); - return; - } - - if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token) - && (memcmp(g_last_request_token, requestInfo->info.token, - CA_MAX_TOKEN_LEN) == 0)) - { - printf("token is same. received request of it's own. skip.. \n"); - return; - } - - printf("##########received request from remote device #############\n"); - if (CA_ADAPTER_IP == object->adapter) - { - printf("Remote Address: %s Port: %d secured:%d\n", object->addr, - object->port, object->flags & CA_SECURE); - } - else - { - printf("Remote Address: %s \n", object->addr); - } - printf("Data: %s\n", requestInfo->info.payload); - printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]); - - if (requestInfo->info.options) - { - uint32_t len = requestInfo->info.numOptions; - uint32_t i; - for (i = 0; i < len; i++) - { - printf("Option %d\n", i + 1); - printf("ID : %d\n", requestInfo->info.options[i].optionID); - printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength, - requestInfo->info.options[i].optionData); - } - } - printf("############################################################\n"); - - //Check if this has secure communication information - if (requestInfo->info.payload && - (CA_ADAPTER_IP == object->adapter)) - { - int securePort = get_secure_information(requestInfo->info.payload); - if (0 < securePort) //Set the remote endpoint secure details and send response - { - printf("This is secure resource...\n"); - - CAEndpoint_t *endpoint = NULL; - if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr, - object->port, &endpoint)) - { - printf("Failed to create duplicate of remote endpoint!\n"); - return; - } - endpoint->flags = CA_SECURE; - object = endpoint; - } - } - -#ifdef WITH_BWT - // if received message is bulk data, create output file - if ((requestInfo->info.payload) && - (requestInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE))) - { - create_file(requestInfo->info.payload, requestInfo->info.payloadSize); - } -#endif - - printf("Send response with URI\n"); - send_response(object, &requestInfo->info); - - g_received = 1; -} - -void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo) -{ - printf("##########Received response from remote device #############\n"); - if (CA_ADAPTER_IP == object->adapter) - { - printf("Remote Address: %s Port: %d secured:%d\n", object->addr, - object->port, object->flags & CA_SECURE); - } - else - { - printf("Remote Address: %s \n", object->addr); - } - printf("response result : %d\n", responseInfo->result); - printf("Data: %s\n", responseInfo->info.payload); - printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]); - printf("Token: %s\n", responseInfo->info.token); - if (responseInfo->info.options) - { - uint32_t len = responseInfo->info.numOptions; - uint32_t i; - for (i = 0; i < len; i++) - { - printf("Option %d\n", i + 1); - printf("ID : %d\n", responseInfo->info.options[i].optionID); - printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength, - responseInfo->info.options[i].optionData); - } - } - printf("############################################################\n"); - g_received = 1; - - //Check if this has secure communication information - if (responseInfo->info.payload) - { - int securePort = get_secure_information(responseInfo->info.payload); - if (0 < securePort) //Set the remote endpoint secure details and send response - { - printf("This is secure resource...\n"); - } - } - -#ifdef WITH_BWT - // if received message is bulk data, create output file - if ((responseInfo->info.payload) && - (responseInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE))) - { - create_file(responseInfo->info.payload, responseInfo->info.payloadSize); - } -#endif -} - -void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t *errorInfo) -{ - (void)rep; - printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n"); - - if (errorInfo) - { - const CAInfo_t *info = &errorInfo->info; - printf("Error Handler, ErrorInfo :\n"); - printf("Error Handler result : %d\n", errorInfo->result); - printf("Error Handler token : %s\n", info->token); - printf("Error Handler messageId : %d\n", (uint16_t) info->messageId); - printf("Error Handler type : %d\n", info->type); - printf("Error Handler resourceUri : %s\n", info->resourceUri); - printf("Error Handler payload : %s\n", info->payload); - - if (CA_ADAPTER_NOT_ENABLED == errorInfo->result) - { - printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n"); - } - else if (CA_SEND_FAILED == errorInfo->result) - { - printf("CA_SEND_FAILED, unable to send the message, check parameters\n"); - } - else if (CA_MEMORY_ALLOC_FAILED == errorInfo->result) - { - printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n"); - } - else if (CA_SOCKET_OPERATION_FAILED == errorInfo->result) - { - printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n"); - } - else if (CA_STATUS_FAILED == errorInfo->result) - { - printf("CA_STATUS_FAILED, message could not be delivered, internal error\n"); - } - } - printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n"); - - return; -} - -void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info) -{ - printf("entering send_response\n"); - - printf("\n=============================================\n"); - printf("\tselect message type\n"); - printf("CON : 0\n"); - printf("NON : 1\n"); - printf("ACK : 2\n"); - printf("RESET : 3\n"); - printf("select : "); - - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) - { - return; - } - - int messageType = buf[0] - '0'; - if (0 > messageType || 3 < messageType) - { - printf("Invalid message type\n"); - return; - } - - int responseCode = 0 ; - char responseCodeBuf[MAX_BUF_LEN] = { 0 }; - if (CA_MSG_RESET != messageType) - { - printf("\n=============================================\n"); - printf("\tselect response code\n"); - printf("EMPTY : 0\n"); - printf("CREATED : 201\n"); - printf("DELETED : 202\n"); - printf("VALID : 203\n"); - printf("CHANGED : 204\n"); - printf("CONTENT : 205\n"); - printf("BAD_REQ : 400\n"); - printf("BAD_OPT : 402\n"); - printf("NOT_FOUND : 404\n"); - printf("INTERNAL_SERVER_ERROR : 500\n"); - printf("RETRANSMIT_TIMEOUT : 504\n"); - printf("select : "); - - if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN)) - { - return; - } - responseCode = atoi(responseCodeBuf); - } - - // create response data - uint16_t messageId = (info != NULL) ? info->messageId : 0; - CAURI_t resourceUri = (info != NULL) ? info->resourceUri : 0; - - CAInfo_t responseData = { .type = messageType, - .messageId = messageId, - .token = NULL, - .tokenLength = 0, - .options = NULL, - .numOptions = 0, - .payload = NULL, - .payloadSize = 0, - .resourceUri = resourceUri - }; - - if (CA_MSG_RESET != messageType) - { - responseData.token = (info != NULL) ? info->token : NULL; - responseData.tokenLength = (info != NULL) ? info->tokenLength : 0; - - if (endpoint->flags & CA_SECURE) - { - if (!responseData.resourceUri) - { - printf("resourceUri not available in SECURE\n"); - return; - } - printf("Sending response on secure communication\n"); - - uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri); - responseData.payload = (CAPayload_t) calloc(length, sizeof(char)); - if (NULL == responseData.payload) - { - printf("Memory allocation fail\n"); - return; - } - snprintf((char *) responseData.payload, length, SECURE_INFO_DATA, - (const char *) responseData.resourceUri, g_local_secure_port); - responseData.payloadSize = length; - } - else - { - printf("Sending response on non-secure communication\n"); - - bool useBigPayload = select_payload_type(); - if (useBigPayload) - { - size_t payloadLength = 0; - CAPayload_t binaryPayload = get_binary_payload(&payloadLength); - if (NULL == binaryPayload) - { - free(binaryPayload); - return; - } - - responseData.payload = (CAPayload_t) malloc(payloadLength); - if (NULL == responseData.payload) - { - printf("Memory allocation failed!"); - free(binaryPayload); - return; - } - memcpy(responseData.payload, binaryPayload, payloadLength); - responseData.payloadSize = payloadLength; - - // memory free - free(binaryPayload); - } - else - { - if (!responseData.resourceUri) - { - printf("resourceUri not available in NON-SECURE\n"); - return; - } - uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri); - responseData.payload = (CAPayload_t) calloc(length, sizeof(char)); - if (NULL == responseData.payload) - { - printf("Memory allocation fail\n"); - return; - } - snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, - (const char *) responseData.resourceUri); - responseData.payloadSize = length; - } - } - } - - CAResponseInfo_t responseInfo = { .result = responseCode, - .info = responseData - }; - - // send response (transportType from remoteEndpoint of request Info) - CAResult_t res = CASendResponse(endpoint, &responseInfo); - if (CA_STATUS_OK != res) - { - printf("Send response error\n"); - } - else - { - printf("Send response success\n"); - } - - if (responseData.payload) - { - free(responseData.payload); - } - - printf("=============================================\n"); -} - -int get_secure_information(CAPayload_t payLoad) -{ - printf("Entering get_secure_information\n"); - - if (!payLoad) - { - printf("Payload is NULL\n"); - return -1; - } - - char *subString = NULL; - if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1"))) - { - printf("This is not secure resource\n"); - return -1; - } - - if (NULL == (subString = strstr((const char *) payLoad, "\"port\":"))) - { - printf("This secure resource does not have port information\n"); - return -1; - } - - char *startPos = strstr(subString, ":"); - if (!startPos) - { - printf("Parsing failed !\n"); - return -1; - } - - char *endPos = strstr(startPos, "}"); - if (!endPos) - { - printf("Parsing failed !\n"); - return -1; - } - - char portStr[6] = {0}; - OICStrcpyPartial(portStr, sizeof(portStr), startPos + 1, (endPos - 1) - startPos); - printf("secured port is: %s\n", portStr); - return atoi(portStr); -} - -void get_resource_uri(char *URI, char *resourceURI, int length) -{ - char *startPos = URI; - char *temp = NULL; - if (NULL != (temp = strstr(URI, "://"))) - { - startPos = strchr(temp + 3, '/'); - if (!startPos) - { - printf("Resource URI is missing\n"); - return; - } - } - - char *endPos = strchr(startPos, '?'); - if (!endPos) - { - endPos = URI + strlen(URI); - } - endPos -= 1; - - if (endPos - startPos <= length) - { - OICStrcpyPartial(resourceURI, length, startPos + 1, endPos - startPos); - } - - printf("URI: %s, ResourceURI:%s\n", URI, resourceURI); -} - -CAResult_t get_network_type() -{ - printf("Inside get_network_type()"); - char buf[MAX_BUF_LEN] = { 0 }; - - printf("\n=============================================\n"); - printf("\tselect network type\n"); - printf("IP : 0\n"); - printf("GATT : 1\n"); - printf("RFCOMM : 2\n"); - printf("TCP : 4\n"); - printf("\n=============================================\n"); - - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) - { - printf("\nCA_NOT_SUPPORTED [%d]\n", (buf[0] - '0')); - return CA_NOT_SUPPORTED ; - } - - int number = buf[0] - '0'; - - number = (number < 0 || number > 4) ? 0 : 1 << number; - printf("\n Number given %d\n", number); - switch (number) - { - case CA_ADAPTER_IP: - case CA_ADAPTER_GATT_BTLE: - case CA_ADAPTER_RFCOMM_BTEDR: - case CA_ADAPTER_TCP: - g_selected_nw_type = number; - return CA_STATUS_OK; - default: - return CA_NOT_SUPPORTED; - } -} - -CAResult_t get_input_data(char *buf, int32_t length) -{ - if (!fgets(buf, length, stdin)) - { - printf("fgets error\n"); - return CA_STATUS_FAILED; - } - - char *p = NULL; - if ((p = strchr(buf, '\n')) != NULL) - { - *p = '\0'; - } - - return CA_STATUS_OK; -} - -CAHeaderOption_t *get_option_data(CAInfo_t *requestData) -{ - char optionNumBuf[MAX_BUF_LEN] = "0"; - char optionData[MAX_OPT_LEN] = { 0 } ; - - printf("Option Num : "); - /* if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN)) - { - return NULL; - }*/ - int optionNum = atoi(optionNumBuf); - - CAHeaderOption_t *headerOpt = NULL; - if (0 >= optionNum) - { - printf("there is no headerOption!\n"); - return NULL; - } - else if (optionNum > MAX_OPT_LEN) - { - printf("Too many header options!\n"); - return NULL; - } - else - { - headerOpt = (CAHeaderOption_t *)calloc(optionNum, sizeof(CAHeaderOption_t)); - if (NULL == headerOpt) - { - printf("Memory allocation failed!\n"); - return NULL; - } - - int i; - for (i = 0; i < optionNum; i++) - { - char getOptionID[MAX_BUF_LEN] = { 0 } ; - - printf("[%d] Option ID : ", i + 1); - if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN)) - { - free(headerOpt); - return NULL; - } - int optionID = atoi(getOptionID); - headerOpt[i].optionID = optionID; - - printf("[%d] Option Data : ", i + 1); - if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN)) - { - free(headerOpt); - return NULL; - } - - OICStrcpy(headerOpt[i].optionData, sizeof(headerOpt[i].optionData), optionData); - - headerOpt[i].optionLength = (uint16_t) strlen(optionData); - } - requestData->numOptions = optionNum; - requestData->options = headerOpt; - } - return headerOpt; -} - -void parsing_coap_uri(const char *uri, addressSet_t *address, CATransportFlags_t *flags) -{ - if (NULL == uri) - { - printf("parameter is null\n"); - return; - } - - // parse uri - // #1. check prefix - uint8_t startIndex = 0; - if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0) - { - printf("uri has '%s' prefix\n", COAPS_PREFIX); - startIndex = COAPS_PREFIX_LEN; - *flags = CA_SECURE; - } - else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0) - { - printf("uri has '%s' prefix\n", COAP_PREFIX); - startIndex = COAP_PREFIX_LEN; - *flags = CA_IPV4; - } - else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0) - { - printf("uri has '%s' prefix\n", COAP_TCP_PREFIX); - startIndex = COAP_TCP_PREFIX_LEN; - *flags = CA_IPV4; - } - - // #2. copy uri for parse - int32_t len = strlen(uri) - startIndex; - - if (len <= 0) - { - printf("uri length is 0!\n"); - return; - } - - char *cloneUri = (char *) calloc(len + 1, sizeof(char)); - if (NULL == cloneUri) - { - printf("Out of memory\n"); - return; - } - - memcpy(cloneUri, &uri[startIndex], sizeof(char) * len); - cloneUri[len] = '\0'; - - char *pAddress = cloneUri; - printf("pAddress : %s\n", pAddress); - - if (!get_address_set(pAddress, address)) - { - printf("address parse error\n"); - - free(cloneUri); - return; - } - free(cloneUri); - return; -} - -bool get_address_set(const char *pAddress, addressSet_t *outAddress) -{ - if (NULL == pAddress) - { - printf("parameter is null !\n"); - return false; - } - - size_t len = strlen(pAddress); - bool isIp = false; - size_t ipLen = 0; - - for (size_t i = 0; i < len; i++) - { - if (pAddress[i] == '.') - { - isIp = true; - } - - // found port number start index - if (isIp && pAddress[i] == ':') - { - ipLen = i; - break; - } - } - - if (isIp) - { - if (ipLen && ipLen < sizeof(outAddress->ipAddress)) - { - OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress), - pAddress, ipLen); - } - else if (!ipLen && len < sizeof(outAddress->ipAddress)) - { - OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress), - pAddress, len); - } - else - { - printf("IP Address too long: %zu\n", (ipLen == 0) ? len : ipLen); - return false; - } - - if (ipLen > 0) - { - outAddress->port = atoi(pAddress + ipLen + 1); - } - return true; - } - else - { - return false; - } -} - -void create_file(CAPayload_t bytes, size_t length) -{ - FILE *fp = fopen("sample_output.txt", "wb"); - if (fp) - { - fwrite(bytes, 1, length, fp); - fclose(fp); - } -} - -bool read_file(const char *name, CAPayload_t *bytes, size_t *length) -{ - if (NULL == name) - { - printf("parameter is null\n"); - return false; - } - - FILE *file = NULL; - CAPayload_t buffer = NULL; - unsigned long fileLen = 0; - - // Open file - file = fopen(name, "rb"); - if (!file) - { - fprintf(stderr, "Unable to open file, %s\n", name); - return false; - } - - // Get file length - fseek(file, 0, SEEK_END); - fileLen = ftell(file); - fseek(file, 0, SEEK_SET); - - // Allocate memory - buffer = calloc(1, sizeof(uint8_t) * fileLen + 1); - if (!buffer) - { - fprintf(stderr, "Memory error\n"); - fclose(file); - return false; - } - - // Read file contents into buffer - size_t ret = fread(buffer, fileLen, 1, file); - if (ret != 1) - { - printf("Failed to read data from file, %s\n", name); - fclose(file); - free(buffer); - return false; - } - - fclose(file); - - *bytes = buffer; - *length = fileLen; - - return true; -} diff --git a/apps/examples/iotivity/data/data.dat b/apps/examples/iotivity/data/data.dat deleted file mode 100644 index 89aa230..0000000 --- a/apps/examples/iotivity/data/data.dat +++ /dev/null @@ -1 +0,0 @@ -012345678910 \ No newline at end of file diff --git a/apps/examples/iotivity/data/oic_svr_db_server.dat b/apps/examples/iotivity/data/oic_svr_db_server.dat deleted file mode 100644 index 82b4e405784448301d84ff7e1297ab39ee68ff01..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 997 zcmbV~O-{ow5QR%saS~QYaVwg{;sjiw?1+CtCw1b;cG|LR;TkLu-EfMYhkaQW+bJa~ z>K|ETGVy%MdvCI&2^IJ4yG3d%X!FJr%Juwxq$`qfYN`rYat(@WSt)z+ykJAc(_vQv z?b^3QnOSC^(PV^N3+W783n>zUDlQ&sAoT!qkgB@nynZgtlxt|zTL+*Qn}2OoD^KS6;H3?1V^}!!vNzr4e(7&f-sDu0LM{; zqxd!s`@Q4(xc5AG{a~PFxgs=g6O*@y%sWKqos97@P=5Ls|0VHQ{LF22@VRtF&swP~ yT(qdB=7PIO*y?Pd!a8fD+1p%!t2?)!v$MUaDU#|Dfiy4%^MqJQzfSm9*XwWg&SrxE diff --git a/apps/examples/iotivity/iotivity_cloud_main.c b/apps/examples/iotivity/iotivity_cloud_main.c deleted file mode 100644 index 6f9594e..0000000 --- a/apps/examples/iotivity/iotivity_cloud_main.c +++ /dev/null @@ -1,955 +0,0 @@ -/**************************************************************************** - * - * Copyright 2016 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific - * language governing permissions and limitations under the License. - * - ****************************************************************************/ - -/// -/// This sample provides the way to create cloud sample -#include -#include -#include -#include -#include -#include -#include "ocstack.h" -#include "ocpayload.h" - -#include "cloud_connector.h" - -#define DEFAULT_CONTEXT_VALUE 0x99 -#define DEFAULT_PUBLISH_QUERY "/oic/rd?rt=oic.wk.rdpub" -#define DEFAULT_DISCOVER_QUERY "/oic/res?rt=core.light" - -#define nullptr NULL - -/* - *Global Variables - */ -#define SAMPLE_MAX_NUM_POST_INSTANCE 2 -typedef struct LIGHTRESOURCE -{ - OCResourceHandle handle; - bool state; - int power; -} LightResource; -static LightResource gLightInstance[SAMPLE_MAX_NUM_POST_INSTANCE]; - -#define SAMPLE_MAX_NUM_OBSERVATIONS 2 -static bool observeThreadStarted = false; -int gCloudLightUnderObservation = 0; -pthread_t threadId_observe; -typedef struct -{ - OCObservationId observationId; - bool valid; - OCResourceHandle resourceHandle; -} Observers; -Observers interestedObservers[SAMPLE_MAX_NUM_OBSERVATIONS]; - -const char *coap_tcp_header = "coap+tcp://"; -char *g_host = nullptr; -char *g_session = nullptr; -char *g_authProviderName = nullptr; -char *g_authProviderCode = nullptr; - -int gNumObserveNotifies = 0; -int g_runningMode = 0; - -#ifdef CONFIG_NET_LWIP -#define IOTIVITY_TEST_STACKSIZE 16384 -#define IOTIVITY_TEST_PRI 100 -#define IOTIVITY_TEST_SCHED_POLICIY SCHED_RR - -// String Utility Functions Declaration -void tinyara_free(char **str); -void tinyara_strcpy(char **dst, const char *src, int *size); -void tinyara_strcat(char **dst, const char *src, int *size); - -/* - *Utility Functions to strings manipulation - */ -void tinyara_free(char **str) -{ - if (nullptr == str || nullptr == *str) return; - free(*str); - *str = nullptr; -} - -void tinyara_strcpy(char **dst, const char *src, int *size) -{ - if (nullptr == dst) return; - if (nullptr == src) return; - tinyara_free(dst); - - int src_size = strlen(src); - int dst_size = src_size + 1; - *dst = malloc(dst_size); - strncpy(*dst, src, dst_size); - if (size) - { - *size = dst_size; - } -} - -void tinyara_strcat(char **dst, const char *src, int *size) -{ - if (nullptr == dst) return; - if (nullptr == src) return; - if (nullptr == *dst) - { - tinyara_strcpy(dst, src, size); - return; - } - - int src_size = strlen(src); - int dst_size = strlen(*dst) + src_size + 1; - *dst = realloc(*dst, dst_size); - strncat(*dst, src, dst_size); - if (size) - { - *size = dst_size; - } -} - -OCRepPayload *responsePayload(int64_t power, bool state) -{ - OCRepPayload *payload = OCRepPayloadCreate(); - if (!payload) - { - printf("Failed to allocate Payload\n"); - return nullptr; - } - - OCRepPayloadSetPropBool(payload, "state", state); - OCRepPayloadSetPropInt(payload, "power", power); - - return payload; -} - -OCRepPayload *cloudConstructResponse(OCEntityHandlerRequest *ehRequest) -{ - if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION) - { - printf("Incoming payload not a representation\n"); - return nullptr; - } - - LightResource *currLightResource = nullptr; - - if (ehRequest->resource == gLightInstance[0].handle) - { - currLightResource = &gLightInstance[0]; - } - else if (ehRequest->resource == gLightInstance[1].handle) - { - currLightResource = &gLightInstance[1]; - } - - if (OC_REST_PUT == ehRequest->method) - { - // Get pointer to query - int64_t pow; - OCRepPayload *input = (OCRepPayload *)(ehRequest->payload); - - if (OCRepPayloadGetPropInt(input, "power", &pow)) - { - currLightResource->power = pow; - } - - bool state; - if (OCRepPayloadGetPropBool(input, "state", &state)) - { - currLightResource->state = state; - } - } - - return responsePayload(currLightResource->power, currLightResource->state); -} - -OCEntityHandlerResult cloudProcessGetRequest(OCEntityHandlerRequest *ehRequest, - OCRepPayload **payload) -{ - OCRepPayload *getResp = cloudConstructResponse(ehRequest); - if (!getResp) - { - printf("constructResponse failed\n"); - return OC_EH_ERROR; - } - - *payload = getResp; - - return OC_EH_OK; -} - -OCEntityHandlerResult cloudProcessPutRequest(OCEntityHandlerRequest *ehRequest, - OCRepPayload **payload) -{ - OCEntityHandlerResult ehResult; - OCRepPayload *putResp = cloudConstructResponse(ehRequest); - - if (!putResp) - { - printf("Failed to construct Json response\n"); - return OC_EH_ERROR; - } - - *payload = putResp; - ehResult = OC_EH_OK; - - return ehResult; -} - -void *cloudChangeLightRepresentation(void *param) -{ - (void)param; - OCStackResult result = OC_STACK_ERROR; - - while (true) - { - sleep(3); - gLightInstance[0].power += 1; - gLightInstance[1].power += 3; - - if (gCloudLightUnderObservation) - { - printf(" =====> Notifying stack of new power level %d \n ", gLightInstance[0].power); - printf(" =====> Notifying stack of new power level %d \n ", gLightInstance[1].power); - // Notifying all observers - result = OCNotifyAllObservers(gLightInstance[0].handle, OC_NA_QOS); - result = OCNotifyAllObservers(gLightInstance[1].handle, OC_NA_QOS); - printf(" =====> Notifying result %d \n", (int)result); - } - } - return nullptr; -} - -void cloudProcessObserveRegister(OCEntityHandlerRequest *ehRequest) -{ - printf("Received observation registration request with observation Id %u \n", ehRequest->obsInfo.obsId); - - if (!observeThreadStarted) - { - pthread_create(&threadId_observe, nullptr, cloudChangeLightRepresentation, (void *)nullptr); - observeThreadStarted = 1; - } - for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) - { - if (interestedObservers[i].valid == false) - { - interestedObservers[i].observationId = ehRequest->obsInfo.obsId; - interestedObservers[i].valid = true; - gCloudLightUnderObservation = 1; - break; - } - } -} - -void cloudProcessObserveDeregister(OCEntityHandlerRequest *ehRequest) -{ - bool clientStillObserving = false; - printf("Received observation deregistration request for observation Id %u \n", ehRequest->obsInfo.obsId); - for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) - { - if (interestedObservers[i].observationId == ehRequest->obsInfo.obsId) - { - interestedObservers[i].valid = false; - } - if (interestedObservers[i].valid == true) - { - // Even if there is one single client observing we continue notifying entity handler - clientStillObserving = true; - } - } - if (clientStillObserving == false) - gCloudLightUnderObservation = 0; -} - -OCEntityHandlerResult cloudOCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest *entityHandlerRequest, void *callback) -{ - OCEntityHandlerResult ehResult = OC_EH_OK; - OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, {}, { 0 }, false }; - - // Validate pointer - if (!entityHandlerRequest) - { - printf("Invalid request pointer \n"); - return OC_EH_ERROR; - } - - // Initialize certain response fields - response.numSendVendorSpecificHeaderOptions = 0; - memset(response.sendVendorSpecificHeaderOptions, - 0, sizeof response.sendVendorSpecificHeaderOptions); - memset(response.resourceUri, 0, sizeof response.resourceUri); - OCRepPayload *payload = nullptr; - - if (flag & OC_REQUEST_FLAG) - { - printf("Flag includes OC_REQUEST_FLAG\n"); - - if (OC_REST_GET == entityHandlerRequest->method) - { - printf("Received OC_REST_GET from client\n"); - ehResult = cloudProcessGetRequest(entityHandlerRequest, &payload); - } - else if (OC_REST_PUT == entityHandlerRequest->method) - { - printf("Received OC_REST_PUT from client\n"); - ehResult = cloudProcessPutRequest(entityHandlerRequest, &payload); - } - else - { - printf("Received unsupported method %d from client \n", (int)entityHandlerRequest->method); - ehResult = OC_EH_ERROR; - } - // If the result isn't an error or forbidden, send response - if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN))) - { - // Format the response. Note this requires some info about the request - response.requestHandle = entityHandlerRequest->requestHandle; - response.resourceHandle = entityHandlerRequest->resource; - response.ehResult = ehResult; - response.payload = (OCPayload *)(payload); - response.persistentBufferFlag = 0; - - // Send the response - if (OCDoResponse(&response) != OC_STACK_OK) - { - printf("Error sending response\n"); - ehResult = OC_EH_ERROR; - } - } - } - - if (flag & OC_OBSERVE_FLAG) - { - printf("Flag includes OC_OBSERVE_FLAG\n"); - if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) - { - printf("Received OC_OBSERVE_REGISTER from client\n"); - cloudProcessObserveRegister(entityHandlerRequest); - } - else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) - { - printf("Received OC_OBSERVE_DEREGISTER from client\n"); - cloudProcessObserveDeregister(entityHandlerRequest); - } - } - - OCPayloadDestroy(response.payload); - return ehResult; -} - -int cloudcreateLightResource(char *uri, LightResource *lightResource) -{ - if (!uri) - { - printf("Resource URI cannot be nullptr\n"); - return -1; - } - - lightResource->state = false; - lightResource->power = 0; - OCStackResult res = OCCreateResource(&(lightResource->handle), - "core.light", - "oc.mi.def", - uri, - cloudOCEntityHandlerCb, - nullptr, - OC_DISCOVERABLE | OC_OBSERVABLE); - printf("Created Light resource with result: %d \n", (int)res); - - - return res; -} - -OCStackApplicationResult handlePublishCB(void *ctx, - OCDoHandle handle, - OCClientResponse *clientResponse) -{ - if (ctx != (void *)DEFAULT_CONTEXT_VALUE) - { - printf("Invalid Publish callback received\n"); - } - printf("Publish resource response received, code:%d \n", (int)clientResponse->result); - - return OC_STACK_KEEP_TRANSACTION; -} - -void PublishResources(char *host, char *additionalQuery) -{ - printf("Running as Server mode\n"); - - char *requestQuery = nullptr; int requestQuerySize; - tinyara_strcpy(&requestQuery, DEFAULT_PUBLISH_QUERY, &requestQuerySize); - tinyara_strcat(&requestQuery, additionalQuery, &requestQuerySize); - printf("Publishing resources...\n"); - printf("%s,%s", host, requestQuery); - - if (cloudcreateLightResource((char *)"/a/light/0", &gLightInstance[0]) != 0) - { - printf("Unable to create sample resource\n"); - } - - if (cloudcreateLightResource((char *)"/a/light/1", &gLightInstance[1]) != 0) - { - printf("Unable to create sample resource\n"); - } - - if (OCCloudPublish(host, requestQuery, &handlePublishCB, 2, - gLightInstance[0].handle, gLightInstance[1].handle) != OC_STACK_OK) - { - printf("Unable to publish resources to cloud\n"); - } - tinyara_free(&requestQuery); -} - -/* - *Client Sample - */ -void PrintRepresentation(OCRepPayloadValue *val) -{ - while (val) - { - printf("Key: %s Value:", val->name); - switch (val->type) - { - case OCREP_PROP_NULL: - printf("NULL\n"); - break; - - case OCREP_PROP_INT: - printf("%d\n", val->i); - break; - - case OCREP_PROP_DOUBLE: - printf("%f\n", val->d); - break; - - case OCREP_PROP_BOOL: - printf("%u\n", val->b); - break; - - case OCREP_PROP_STRING: - printf("%s\n", val->str); - break; - - case OCREP_PROP_BYTE_STRING: - printf("%s\n", "[ByteString]"); - break; - - case OCREP_PROP_OBJECT: - printf("%s\n", "[Object]"); - break; - - case OCREP_PROP_ARRAY: - printf("%s\n", "[Array]"); - break; - } - - val = val->next; - } -} - - -OCStackApplicationResult obsReqCB(void *ctx, OCDoHandle handle, - OCClientResponse *clientResponse) -{ - printf("Observe response received from %s \n", clientResponse->resourceUri); - - if (ctx != (void *)DEFAULT_CONTEXT_VALUE) - { - printf("Invalid Put callback received\n"); - } - - if (clientResponse) - { - if (clientResponse->payload == nullptr) - { - printf("No payload received\n"); - } - - OCRepPayloadValue *val = ((OCRepPayload *)clientResponse->payload)->values; - - PrintRepresentation(val); - - gNumObserveNotifies++; - if (gNumObserveNotifies > 5) //large number to test observing in DELETE case. - { - printf("Cancelling with OC_HIGH_QOS\n"); - if (OCCancel(handle, OC_HIGH_QOS, nullptr, 0) != OC_STACK_OK) - { - printf("Observe cancel error\n"); - } - } - if (clientResponse->sequenceNumber == OC_OBSERVE_REGISTER) - { - printf("This also serves as a registration confirmation\n"); - } - else if (clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER) - { - printf("This also serves as a deregistration confirmation\n"); - return OC_STACK_DELETE_TRANSACTION; - } - else if (clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION) - { - printf("This also tells you that registration/deregistration failed\n"); - return OC_STACK_DELETE_TRANSACTION; - } - } - else - { - printf("obsReqCB received Null clientResponse\n"); - } - - return OC_STACK_KEEP_TRANSACTION; -} - -void ObserveResource(char **uri, char *additionalQuery) -{ - OCCallbackData cbData; - cbData.cb = obsReqCB; - cbData.context = (void *)DEFAULT_CONTEXT_VALUE; - cbData.cd = nullptr; - - tinyara_strcat(uri, additionalQuery, nullptr); - printf("Request OBSERVE to resource %s\n", *uri); - - OCStackResult res = OCDoResource(nullptr, OC_REST_OBSERVE, *uri, nullptr, nullptr, - CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, nullptr, 0); - printf("Requesting OBSERVE res=%d\n", (int)res); -} - -OCStackApplicationResult putReqCB(void *ctx, OCDoHandle handle, - OCClientResponse *clientResponse) -{ - printf("Put response received from %s\n ", clientResponse->resourceUri); - - if (ctx != (void *)DEFAULT_CONTEXT_VALUE) - { - printf("Invalid Put callback received\n"); - } - - if (clientResponse->payload == nullptr) - { - printf("No payload received\n"); - } - - OCRepPayloadValue *val = ((OCRepPayload *)clientResponse->payload)->values; - - PrintRepresentation(val); - - char *requestUri = nullptr; int requestUriSize; - tinyara_strcpy(&requestUri, g_host, &requestUriSize); - tinyara_strcat(&requestUri, clientResponse->resourceUri, &requestUriSize); - - ObserveResource(&requestUri, ""); - - tinyara_free(&requestUri); - - return OC_STACK_KEEP_TRANSACTION; -} - -OCPayload *putRequestPayload() -{ - OCRepPayload *payload = OCRepPayloadCreate(); - - if (!payload) - { - printf("Failed to create put payload object\n"); - exit(1); - } - - OCRepPayloadSetPropInt(payload, "power", 15); - OCRepPayloadSetPropBool(payload, "state", true); - - return (OCPayload *)payload; -} - -void PutResource(char **uri, char *additionalQuery) -{ - OCCallbackData cbData; - cbData.cb = putReqCB; - cbData.context = (void *)DEFAULT_CONTEXT_VALUE; - cbData.cd = nullptr; - - tinyara_strcat(uri, additionalQuery, nullptr); - printf("Request PUT to resource%s\n", *uri); - - OCStackResult res = OCDoResource(nullptr, OC_REST_PUT, *uri, nullptr, putRequestPayload(), - CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, nullptr, 0); - - printf("Requesting PUT res=%d\n", res); -} - -OCStackApplicationResult handleGetCB(void *ctx, - OCDoHandle handle, - OCClientResponse *clientResponse) -{ - printf("Get response received from %s\n", clientResponse->resourceUri); - - if (ctx != (void *)DEFAULT_CONTEXT_VALUE) - { - printf("Invalid Get callback received\n"); - } - - if (clientResponse->payload == nullptr) - { - printf("No payload received\n"); - } - - if (clientResponse->payload != nullptr && - clientResponse->payload->type == PAYLOAD_TYPE_REPRESENTATION) - { - OCRepPayloadValue *val = ((OCRepPayload *)clientResponse->payload)->values; - - PrintRepresentation(val); - - char *requestUri = nullptr; int requestUriSize; - tinyara_strcpy(&requestUri, g_host, &requestUriSize); - tinyara_strcat(&requestUri, clientResponse->resourceUri, &requestUriSize); - - PutResource(&requestUri, ""); - - tinyara_free(&requestUri); - } - - return OC_STACK_KEEP_TRANSACTION; -} - -void GetResource(char **uri, char *additionalQuery) -{ - OCCallbackData cbData; - cbData.cb = handleGetCB; - cbData.context = (void *)DEFAULT_CONTEXT_VALUE; - cbData.cd = nullptr; - - tinyara_strcat(uri, additionalQuery, nullptr); - printf("Request GET to resource %s\n", *uri); - - OCStackResult res = OCDoResource(nullptr, OC_REST_GET, *uri, nullptr, nullptr, - CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, nullptr, 0); - - printf("Requesting GET res=%d\n", (int)res); -} - -// This is a function called back when a device is discovered -OCStackApplicationResult discoveryReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse) -{ - if (ctx == (void *)DEFAULT_CONTEXT_VALUE) - { - printf("Callback Context for DISCOVER query recvd successfully\n"); - } - - if (clientResponse) - { - printf("StackResult: %d\n", (int)clientResponse->result); - - OCDiscoveryPayload *payload = (OCDiscoveryPayload *)clientResponse->payload; - if (!payload) - { - printf("Empty payload\n"); - return OC_STACK_DELETE_TRANSACTION; - } - - OCResourcePayload *resource = (OCResourcePayload *)payload->resources; - if (!resource) - { - printf("No resources in payload\n"); - return OC_STACK_DELETE_TRANSACTION; - } - - while (resource) - { - printf("Found Resource %s\n", resource->uri); - char *requestUri = nullptr; int requestUriSize; - tinyara_strcpy(&requestUri, g_host, &requestUriSize); - tinyara_strcat(&requestUri, resource->uri, &requestUriSize); - - GetResource(&requestUri, ""); - - tinyara_free(&requestUri); - - resource = resource->next; - } - } - else - { - printf("discoveryReqCB received Null clientResponse\n"); - } - return OC_STACK_KEEP_TRANSACTION; -} - -void DiscoverResources(char *host, char *additionalQuery) -{ - printf("Running as Client mode\n"); - - char *requestQuery = nullptr; int requestQuerySize; - tinyara_strcpy(&requestQuery, host, requestQuerySize); - tinyara_strcat(&requestQuery, DEFAULT_DISCOVER_QUERY, requestQuerySize); - tinyara_strcat(&requestQuery, additionalQuery, requestQuerySize); - - printf("Finding resources...\n"); - printf("%s\n", requestQuery); - - OCCallbackData cbData; - - cbData.cb = discoveryReqCB; - cbData.context = (void *)DEFAULT_CONTEXT_VALUE; - cbData.cd = nullptr; - - if (OCDoResource(nullptr, OC_REST_DISCOVER, requestQuery, nullptr, 0, CT_ADAPTER_TCP, - OC_LOW_QOS, &cbData, nullptr, 0) != OC_STACK_OK) - { - printf("Unable to find resources from cloud\n"); - } - - tinyara_free(&requestQuery); -} - -/////////////////////////////////////////////Common sample - -OCStackApplicationResult handleLoginoutCB(void *ctx, - OCDoHandle handle, - OCClientResponse *clientResponse) -{ - if (ctx != (void *)DEFAULT_CONTEXT_VALUE) - { - printf("Invalid Login/out callback received\n"); - } - - printf("Login/out response received code: %\n", (int)clientResponse->result); - - if (clientResponse->payload != nullptr && - clientResponse->payload->type == PAYLOAD_TYPE_REPRESENTATION) - { - printf("PAYLOAD_TYPE_REPRESENTATION received\n"); - - OCRepPayloadValue *val = ((OCRepPayload *)clientResponse->payload)->values; - - while (val) - { - printf("Key: %s Value: %s\n", val->name , val->str); - val = val->next; - } - - if (g_runningMode == 1) - { - PublishResources(g_host, ""); - } - else if (g_runningMode == 2) - { - DiscoverResources(g_host, ""); - } - } - - return OC_STACK_KEEP_TRANSACTION; -} - -OCStackApplicationResult handleRegisterCB(void *ctx, - OCDoHandle handle, - OCClientResponse *clientResponse) -{ - if (ctx != (void *)DEFAULT_CONTEXT_VALUE) - { - printf("Invalid Register callback received\n"); - } - - printf("Register response received code: %d\n", (int)clientResponse->result); - - if (clientResponse->payload != nullptr && - clientResponse->payload->type == PAYLOAD_TYPE_REPRESENTATION) - { - - printf("PAYLOAD_TYPE_REPRESENTATION received\n"); - printf("You can login using received session variable after disconnected or reboot\n"); - - OCRepPayloadValue *val = ((OCRepPayload *)clientResponse->payload)->values; - - while (val) - { - printf("Key: %s Value: %s\n", val->name , val->str); - if (0 == strncmp(val->name, "session", 7)) - { - tinyara_strcpy(&g_session, val->str, nullptr); - printf("Registered Session = '%s'\n", g_session); - } - val = val->next; - } - } - - return OC_STACK_KEEP_TRANSACTION; -} - -void PrintUsage() -{ - printf("\n"); - printf("Usage : \n"); - printf("TASH>> cloud_device \n"); - printf(" : Cloud Address, \"172.16.10.60:5683\"\n"); - printf(" : String value\n"); - printf(" : String value\n"); - printf("example: TASH>> iotivity_cloud 172.16.10.60:5683 github e37776fae12f62f0cd06 \n"); - printf("\n"); - - printf("TASH>> cloud_device \n"); - printf(" : Cloud Address, \"172.16.10.60:5683\"\n"); - printf(" : Session String value\n"); - printf("example: TASH>> iotivity_cloud 172.16.10.60:5683 g8ENZUi9mqBkywLY \n"); - printf("\n"); -} - -#ifdef CONFIG_BUILD_KERNEL -int main(int argc, FAR char *argv[]) -#else -#ifndef CONFIG_NET_LWIP -int iotivity_cloud_main(int argc, char *argv[]) -#else -int iotivity_cloud_main_cb(int argc, char *argv[]) -#endif -#endif -{ - if (g_session == nullptr || g_host == nullptr) - { - printf("Incorrect Parameters!!!\n"); - return 1; - } - - printf("IoTivity Cloud Address = '%s'\n", g_host); - printf("IoTivityCloud Session Value = '%s'\n", g_session); - - if (OCInit(nullptr, 0, OC_CLIENT_SERVER) != OC_STACK_OK) - { - printf("OCStack init error\n"); - return 2; - } - - OCStackResult res; - - g_runningMode = 1; - - res = OC_STACK_ERROR; - - res = OCCloudLogin(g_host, g_session, handleLoginoutCB); - - printf("OCCloudLogin return %d\n", (int)res); - - while (true) - { - if (OCProcess() != OC_STACK_OK) - { - printf("OCProcess process error\n"); - } - - usleep(100000); - } - - if (OCStop() != OC_STACK_OK) - { - printf("OCStop process error\n"); - } - - tinyara_free(&g_host); - tinyara_free(&g_session); - return 0; -} - -int iotivity_cloud_main_get_session(int argc, char *argv[]) -{ - if (g_authProviderName == nullptr || g_authProviderCode == nullptr || g_host == nullptr) - { - printf("Incorrect Parameters!!!\n"); - return 1; - } - - printf("IoTivity Cloud Address = '%s'\n", g_host); - printf("OAuth Provider Name = '%s'\n", g_authProviderName); - printf("OAuth Provider Code = '%s'\n", g_authProviderCode); - - if (OCInit(nullptr, 0, OC_CLIENT) != OC_STACK_OK) - { - printf("OCStack init error\n"); - return 2; - } - - OCStackResult res; - - printf("Register account to cloud using %s %s\n", g_authProviderName, g_authProviderCode); - - res = OCCloudRegisterLogin(g_host, g_authProviderName, g_authProviderCode, handleRegisterCB); - - printf("OCCloudRegisterLogin return %d\n", (int)res); - - printf("Waiting response..\n"); - - while (true) - { - if (OCProcess() != OC_STACK_OK) - { - printf("OCProcess process error\n"); - } - usleep(100000); - if (g_session != nullptr) break; - } - - printf("IoTivityCloud Session Value = '%s'\n", g_session); - - if (OCStop() != OC_STACK_OK) - { - printf("OCStop process error\n"); - } - - tinyara_free(&g_authProviderName); - tinyara_free(&g_authProviderCode); - - task_create("iotivity-cloud-test", IOTIVITY_TEST_PRI, IOTIVITY_TEST_STACKSIZE, - iotivity_cloud_main_cb, (FAR char * const *)nullptr); - - return 0; -} - -int iotivity_cloud_main(int argc, char *argv[]) -{ - if (argc == 4) - { - tinyara_strcpy(&g_host, coap_tcp_header, nullptr); - tinyara_strcat(&g_host, argv[1], nullptr); - - tinyara_strcpy(&g_authProviderName, argv[2], nullptr); - tinyara_strcpy(&g_authProviderCode, argv[3], nullptr); - - task_create("iotivity-cloud-get-session", IOTIVITY_TEST_PRI, IOTIVITY_TEST_STACKSIZE, - iotivity_cloud_main_get_session, (FAR char * const *)nullptr); - return 0; - } - - if (argc == 3) - { - tinyara_strcpy(&g_host, coap_tcp_header, nullptr); - tinyara_strcat(&g_host, argv[1], nullptr); - - tinyara_strcpy(&g_session, argv[2], nullptr); - - task_create("iotivity-cloud-test", IOTIVITY_TEST_PRI, IOTIVITY_TEST_STACKSIZE, - iotivity_cloud_main_cb, (FAR char * const *)nullptr); - return 0; - } - - PrintUsage(); - return 0; -} -#endif - diff --git a/apps/examples/iotivity/iotivity_main.c b/apps/examples/iotivity/iotivity_main.c deleted file mode 100644 index c6930da..0000000 --- a/apps/examples/iotivity/iotivity_main.c +++ /dev/null @@ -1,1264 +0,0 @@ -/**************************************************************************** - * - * Copyright 2016 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific - * language governing permissions and limitations under the License. - * - ****************************************************************************/ -//****************************************************************** -// -// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -/** - * @testcase :iotivity_lwip_tc - * @brief :Discovery resources and devices using IoTivity - * @scenario : - * @apicovered : - * @precondition :At Linux PC, 1. Build an Iotivity client - * : $ ./occlient -t - * :At test board, 1. Make a binary with 'iotivity' example configuration and flash - * : 2. Run the TASH - * : 3. Connect to Wi-Fi and get an IP address using DHCP - * : TASH>> iotivity - * @postcondition : - */ - -#include -#include -#include -#include -#include -#include -#include -#include "ocstack.h" -#include "logger.h" -#include "ocpayload.h" -#include "ocserver.h" - -/* For WiFi -- */ -#include -#include -#include -#ifdef CONFIG_NET_LWIP -#include -#include -#include -#include -#else -#include -#endif - -/**************************************************************************** - * Definitions - ****************************************************************************/ - - -#define IFHWADDRLEN 6 - -#if defined(LWIP_HAVE_LOOPIF) && LWIP_HAVE_LOOPIF == 1 -#define NET_DEVNUM 1 -#else -#define NET_DEVNUM 0 -#endif - -#if defined(CONFIG_ENC28J60) || defined(CONFIG_WICED) -#define NET_DEVNAME "en" -#elif defined(CONFIG_ARCH_BOARD_SIDK_S5JT200) -#define NET_DEVNAME "wl" -#else -#error "undefined CONFIG_NET_, check your .config" -#endif - -#define nlldbg printf - -static void lowlevelif_bringup(void) -{ - char ifname[6]; - uint8_t iff; - int ret = 0; - snprintf(ifname, IFNAMSIZ, "%s%d", NET_DEVNAME, NET_DEVNUM); - /* Bring Up the desired network interface */ - nlldbg("LWIP Bringing up network interface (%s)\n", ifname); - ret = netlib_ifup(ifname); - if (ret < 0) - { - printf("LWIP network interface (%s) bring up failed\n", ifname); - } - ret = netlib_getifstatus(ifname, &iff); - if (ret != OK) - { - printf("ERROR: Get %s interface flags error : %d\n", ifname, ret); - } - if (iff & IFF_UP) - { - printf("LWIP network interface (%s) is UP now\n", ifname); - } - -} - -/* -- For WiFi */ - -//string length of "/a/light/" + std::numeric_limits::digits10 + '\0'" -// 9 + 9 + 1 = 19 -const int URI_MAXSIZE = 19; - -static int gObserveNotifyType = 3; - -int gQuitFlag = 0; -int gLightUnderObservation = 0; - -static LightResource Light; -// This variable determines instance number of the Light resource. -// Used by POST method to create a new instance of Light resource. -static int gCurrLightInstance = 0; - -static LightResource gLightInstance[SAMPLE_MAX_NUM_POST_INSTANCE]; - -Observers interestedObservers[SAMPLE_MAX_NUM_OBSERVATIONS]; - -pthread_t threadId_observe; -pthread_t threadId_presence; - -static bool observeThreadStarted = false; - -#ifdef WITH_PRESENCE -#define numPresenceResources (2) -#endif - -char *gResourceUri = (char *)"/a/light"; -const char *dateOfManufacture = "myDateOfManufacture"; -const char *deviceName = "myDeviceName"; -const char *deviceUUID = "myDeviceUUID"; -const char *firmwareVersion = "myFirmwareVersion"; -const char *manufacturerName = "myName"; -const char *operatingSystemVersion = "myOS"; -const char *hardwareVersion = "myHardwareVersion"; -const char *platformID = "myPlatformID"; -const char *manufacturerUrl = "myManufacturerUrl"; -const char *modelNumber = "myModelNumber"; -const char *platformVersion = "myPlatformVersion"; -const char *supportUrl = "mySupportUrl"; -const char *version = "myVersion"; -const char *systemTime = "2015-05-15T11.04"; - -// Entity handler should check for resourceTypeName and ResourceInterface in order to GET -// the existence of a known resource -const char *resourceTypeName = "core.light"; -const char *resourceInterface = OC_RSRVD_INTERFACE_DEFAULT; - -OCPlatformInfo platformInfo; -OCDeviceInfo deviceInfo; - -OCRepPayload *getPayload(const char *uri, int64_t power, bool state) -{ - OCRepPayload *payload = OCRepPayloadCreate(); - if (!payload) - { - printf("Failed to allocate Payload"); - return NULL; - } - - OCRepPayloadSetUri(payload, uri); - OCRepPayloadSetPropBool(payload, "state", state); - OCRepPayloadSetPropInt(payload, "power", power); - - return payload; -} - -//This function takes the request as an input and returns the response -OCRepPayload *constructResponse(OCEntityHandlerRequest *ehRequest) -{ - if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION) - { - printf("Incoming payload not a representation"); - return NULL; - } - - OCRepPayload *input = (OCRepPayload *)ehRequest->payload; - - LightResource *currLightResource = &Light; - - if (ehRequest->resource == gLightInstance[0].handle) - { - currLightResource = &gLightInstance[0]; - gResourceUri = (char *) "a/light/0"; - } - else if (ehRequest->resource == gLightInstance[1].handle) - { - currLightResource = &gLightInstance[1]; - gResourceUri = (char *) "a/light/1"; - } - - if (OC_REST_PUT == ehRequest->method) - { - // Get pointer to query - int64_t pow; - if (OCRepPayloadGetPropInt(input, "power", &pow)) - { - currLightResource->power = pow; - } - - bool state; - if (OCRepPayloadGetPropBool(input, "state", &state)) - { - currLightResource->state = state; - } - } - - return getPayload(gResourceUri, currLightResource->power, currLightResource->state); -} - -/* - * Very simple example of query parsing. - * The query may have multiple filters separated by ';'. - * It is upto the entity handler to parse the query for the individual filters, - * VALIDATE them and respond as it sees fit. - - * This function only returns false if the query is exactly "power powerRequested) - { - OCLogv(INFO, TAG, "Current power: %d. Requested: <%d", Light.power - , powerRequested); - return false; - } - } - } - return true; -} - -/* - * Application should validate and process these as desired. - */ -OCEntityHandlerResult ValidateQueryParams(OCEntityHandlerRequest *entityHandlerRequest) -{ - OCLogv(INFO, TAG, PCF("Received query %s"), entityHandlerRequest->query); - OCLog(INFO, TAG, PCF("Not processing query")); - return OC_EH_OK; -} - -OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest, - OCRepPayload **payload) -{ - OCEntityHandlerResult ehResult; - bool queryPassed = checkIfQueryForPowerPassed(ehRequest->query); - - // Empty payload if the query has no match. - if (queryPassed) - { - OCRepPayload *getResp = constructResponse(ehRequest); - if (!getResp) - { - OCLog(ERROR, TAG, "constructResponse failed"); - return OC_EH_ERROR; - } - - *payload = getResp; - ehResult = OC_EH_OK; - } - else - { - ehResult = OC_EH_OK; - } - - return ehResult; -} - -OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest *ehRequest, - OCRepPayload **payload) -{ - OCEntityHandlerResult ehResult; - OCRepPayload *putResp = constructResponse(ehRequest); - - if (!putResp) - { - OCLog(ERROR, TAG, "Failed to construct Json response"); - return OC_EH_ERROR; - } - - *payload = putResp; - ehResult = OC_EH_OK; - - return ehResult; -} - -OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest, - OCEntityHandlerResponse *response, OCRepPayload **payload) -{ - OCEntityHandlerResult ehResult = OC_EH_OK; - OCRepPayload *respPLPost_light = NULL; - - /* - * The entity handler determines how to process a POST request. - * Per the REST paradigm, POST can also be used to update representation of existing - * resource or create a new resource. - * In the sample below, if the POST is for /a/light then a new instance of the Light - * resource is created with default representation (if representation is included in - * POST payload it can be used as initial values) as long as the instance is - * lesser than max new instance count. Once max instance count is reached, POST on - * /a/light updated the representation of /a/light (just like PUT) - */ - - if (ehRequest->resource == Light.handle) - { - if (gCurrLightInstance < SAMPLE_MAX_NUM_POST_INSTANCE) - { - // Create new Light instance - char newLightUri[URI_MAXSIZE]; - snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance); - - respPLPost_light = OCRepPayloadCreate(); - OCRepPayloadSetUri(respPLPost_light, gResourceUri); - OCRepPayloadSetPropString(respPLPost_light, "createduri", newLightUri); - - if (0 == createLightResource(newLightUri, &gLightInstance[gCurrLightInstance])) - { - OCLog(INFO, TAG, "Created new Light instance\n"); - gLightInstance[gCurrLightInstance].state = 0; - gLightInstance[gCurrLightInstance].power = 0; - gCurrLightInstance++; - strncpy((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH); - ehResult = OC_EH_RESOURCE_CREATED; - } - } - else - { - // Update repesentation of /a/light - Light.state = true; - Light.power = 11; - respPLPost_light = constructResponse(ehRequest); - } - } - else - { - for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++) - { - if (ehRequest->resource == gLightInstance[i].handle) - { - gLightInstance[i].state = true; - gLightInstance[i].power = 22; - if (i == 0) - { - respPLPost_light = constructResponse(ehRequest); - break; - } - else if (i == 1) - { - respPLPost_light = constructResponse(ehRequest); - } - } - } - } - - if ((respPLPost_light != NULL)) - { - *payload = respPLPost_light; - } - else - { - OCLog(INFO, TAG, "Payload was NULL"); - ehResult = OC_EH_ERROR; - } - - return ehResult; -} - -OCEntityHandlerResult ProcessDeleteRequest(OCEntityHandlerRequest *ehRequest) -{ - if (ehRequest == NULL) - { - OCLog(INFO, TAG, "The ehRequest is NULL"); - return OC_EH_ERROR; - } - OCEntityHandlerResult ehResult = OC_EH_OK; - - OCLogv(INFO, TAG, "\n\nExecuting %s for resource %p ", __func__, ehRequest->resource); - - /* - * In the sample below, the application will: - * 1a. pass the delete request to the c stack - * 1b. internally, the c stack figures out what needs to be done and does it accordingly - * (e.g. send observers notification, remove observers...) - * 1c. the c stack returns with the result whether the request is fullfilled. - * 2. optionally, app removes observers out of its array 'interestedObservers' - */ - - if ((ehRequest != NULL) && (ehRequest->resource == Light.handle)) - { - //Step 1: Ask stack to do the work. - OCStackResult result = OCDeleteResource(ehRequest->resource); - - if (result == OC_STACK_OK) - { - OCLog(INFO, TAG, "\n\nDelete Resource operation succeeded."); - ehResult = OC_EH_OK; - - //Step 2: clear observers who wanted to observe this resource at the app level. - for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) - { - if (interestedObservers[i].resourceHandle == ehRequest->resource) - { - interestedObservers[i].valid = false; - interestedObservers[i].observationId = 0; - interestedObservers[i].resourceHandle = NULL; - } - } - } - else if (result == OC_STACK_NO_RESOURCE) - { - OCLog(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted."); - ehResult = OC_EH_RESOURCE_DELETED; - } - else - { - OCLog(INFO, TAG, "\n\nEncountered error from OCDeleteResource()."); - ehResult = OC_EH_ERROR; - } - } - else if (ehRequest->resource != Light.handle) - { - //Let's this app not supporting DELETE on some resources so - //consider the DELETE request is received for a non-support resource. - OCLogv(INFO, TAG, "\n\nThe request is received for a non-support resource."); - ehResult = OC_EH_FORBIDDEN; - } - - return ehResult; -} - -OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ptr) -{ - OCLogv(INFO, TAG, "\n\nExecuting %s ", __func__); - - return OC_EH_RESOURCE_NOT_FOUND; -} - -void ProcessObserveRegister(OCEntityHandlerRequest *ehRequest) -{ - OCLogv(INFO, TAG, "Received observation registration request with observation Id %d", - ehRequest->obsInfo.obsId); - - if (!observeThreadStarted) - { - pthread_create(&threadId_observe, NULL, ChangeLightRepresentation, (void *)NULL); - observeThreadStarted = 1; - } - for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) - { - if (interestedObservers[i].valid == false) - { - interestedObservers[i].observationId = ehRequest->obsInfo.obsId; - interestedObservers[i].valid = true; - gLightUnderObservation = 1; - break; - } - } -} - -void ProcessObserveDeregister(OCEntityHandlerRequest *ehRequest) -{ - bool clientStillObserving = false; - - OCLogv(INFO, TAG, "Received observation deregistration request for observation Id %d", - ehRequest->obsInfo.obsId); - for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) - { - if (interestedObservers[i].observationId == ehRequest->obsInfo.obsId) - { - interestedObservers[i].valid = false; - } - if (interestedObservers[i].valid == true) - { - // Even if there is one single client observing we continue notifying entity handler - clientStillObserving = true; - } - } - if (clientStillObserving == false) - gLightUnderObservation = 0; -} - -OCEntityHandlerResult -OCDeviceEntityHandlerCb(OCEntityHandlerFlag flag, - OCEntityHandlerRequest *entityHandlerRequest, - char *uri, - void *callbackParam) -{ - OCLogv(INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri); - - OCEntityHandlerResult ehResult = OC_EH_OK; - OCEntityHandlerResponse response; - - // Validate pointer - if (!entityHandlerRequest) - { - OCLog(ERROR, TAG, "Invalid request pointer"); - return OC_EH_ERROR; - } - // Initialize certain response fields - response.numSendVendorSpecificHeaderOptions = 0; - memset(response.sendVendorSpecificHeaderOptions, 0, - sizeof response.sendVendorSpecificHeaderOptions); - memset(response.resourceUri, 0, sizeof response.resourceUri); - OCRepPayload *payload = NULL; - - - if (flag & OC_REQUEST_FLAG) - { - OCLog(INFO, TAG, "Flag includes OC_REQUEST_FLAG"); - - if (entityHandlerRequest->resource == NULL) - { - OCLog(INFO, TAG, "Received request from client to a non-existing resource"); - ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest); - } - else if (OC_REST_GET == entityHandlerRequest->method) - { - OCLog(INFO, TAG, "Received OC_REST_GET from client"); - ehResult = ProcessGetRequest(entityHandlerRequest, &payload); - } - else if (OC_REST_PUT == entityHandlerRequest->method) - { - OCLog(INFO, TAG, "Received OC_REST_PUT from client"); - ehResult = ProcessPutRequest(entityHandlerRequest, &payload); - } - else if (OC_REST_DELETE == entityHandlerRequest->method) - { - OCLog(INFO, TAG, "Received OC_REST_DELETE from client"); - ehResult = ProcessDeleteRequest(entityHandlerRequest); - } - else - { - OCLogv(INFO, TAG, "Received unsupported method %d from client", - entityHandlerRequest->method); - ehResult = OC_EH_ERROR; - } - // If the result isn't an error or forbidden, send response - if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN))) - { - // Format the response. Note this requires some info about the request - response.requestHandle = entityHandlerRequest->requestHandle; - response.resourceHandle = entityHandlerRequest->resource; - response.ehResult = ehResult; - response.payload = (OCPayload *)payload; - // Indicate that response is NOT in a persistent buffer - response.persistentBufferFlag = 0; - - // Send the response - if (OCDoResponse(&response) != OC_STACK_OK) - { - OCLog(ERROR, TAG, "Error sending response"); - ehResult = OC_EH_ERROR; - } - } - } - if (flag & OC_OBSERVE_FLAG) - { - OCLog(INFO, TAG, "Flag includes OC_OBSERVE_FLAG"); - if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) - { - OCLog(INFO, TAG, "Received OC_OBSERVE_REGISTER from client"); - } - else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) - { - OCLog(INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client"); - } - } - - return ehResult; -} - -OCEntityHandlerResult -OCNOPEntityHandlerCb(OCEntityHandlerFlag flag, - OCEntityHandlerRequest *entityHandlerRequest, - void *callbackParam) -{ - // This is callback is associated with the 2 presence notification - // resources. They are non-operational. - return OC_EH_OK; -} - -OCEntityHandlerResult -OCEntityHandlerCb(OCEntityHandlerFlag flag, - OCEntityHandlerRequest *entityHandlerRequest, void *callback) -{ - OCLogv(INFO, TAG, "Inside entity handler - flags: 0x%x", flag); - - OCEntityHandlerResult ehResult = OC_EH_OK; - OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { }, { 0 }, false }; - - // Validate pointer - if (!entityHandlerRequest) - { - OCLog(ERROR, TAG, "Invalid request pointer"); - return OC_EH_ERROR; - } - - // Initialize certain response fields - response.numSendVendorSpecificHeaderOptions = 0; - memset(response.sendVendorSpecificHeaderOptions, - 0, sizeof response.sendVendorSpecificHeaderOptions); - memset(response.resourceUri, 0, sizeof response.resourceUri); - OCRepPayload *payload = NULL; - - if (flag & OC_REQUEST_FLAG) - { - OCLog(INFO, TAG, "Flag includes OC_REQUEST_FLAG"); - - if (OC_REST_GET == entityHandlerRequest->method) - { - OCLog(INFO, TAG, "Received OC_REST_GET from client"); - ehResult = ProcessGetRequest(entityHandlerRequest, &payload); - } - else if (OC_REST_PUT == entityHandlerRequest->method) - { - OCLog(INFO, TAG, "Received OC_REST_PUT from client"); - ehResult = ProcessPutRequest(entityHandlerRequest, &payload); - } - else if (OC_REST_POST == entityHandlerRequest->method) - { - OCLog(INFO, TAG, "Received OC_REST_POST from client"); - ehResult = ProcessPostRequest(entityHandlerRequest, &response, &payload); - } - else if (OC_REST_DELETE == entityHandlerRequest->method) - { - OCLog(INFO, TAG, "Received OC_REST_DELETE from client"); - ehResult = ProcessDeleteRequest(entityHandlerRequest); - } - else - { - OCLogv(INFO, TAG, "Received unsupported method %d from client", - entityHandlerRequest->method); - ehResult = OC_EH_ERROR; - } - // If the result isn't an error or forbidden, send response - if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN))) - { - // Format the response. Note this requires some info about the request - response.requestHandle = entityHandlerRequest->requestHandle; - response.resourceHandle = entityHandlerRequest->resource; - response.ehResult = ehResult; - response.payload = (OCPayload *)payload; - // Indicate that response is NOT in a persistent buffer - response.persistentBufferFlag = 0; - - // Handle vendor specific options - if (entityHandlerRequest->rcvdVendorSpecificHeaderOptions && - entityHandlerRequest->numRcvdVendorSpecificHeaderOptions) - { - OCLog(INFO, TAG, "Received vendor specific options"); - uint8_t i = 0; - OCHeaderOption *rcvdOptions = - entityHandlerRequest->rcvdVendorSpecificHeaderOptions; - for (i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++) - { - if (((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID) - { - OCLogv(INFO, TAG, "Received option with OC_COAP_ID and ID %u with", - ((OCHeaderOption)rcvdOptions[i]).optionID); - - OCLogBuffer(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData, - MAX_HEADER_OPTION_DATA_LENGTH); - } - } - OCHeaderOption *sendOptions = response.sendVendorSpecificHeaderOptions; - uint8_t option2[] = {21, 22, 23, 24, 25, 26, 27, 28, 29, 30}; - uint8_t option3[] = {31, 32, 33, 34, 35, 36, 37, 38, 39, 40}; - sendOptions[0].protocolID = OC_COAP_ID; - sendOptions[0].optionID = 2248; - memcpy(sendOptions[0].optionData, option2, sizeof(option2)); - sendOptions[0].optionLength = 10; - sendOptions[1].protocolID = OC_COAP_ID; - sendOptions[1].optionID = 2600; - memcpy(sendOptions[1].optionData, option3, sizeof(option3)); - sendOptions[1].optionLength = 10; - response.numSendVendorSpecificHeaderOptions = 2; - } - - // Send the response - if (OCDoResponse(&response) != OC_STACK_OK) - { - OCLog(ERROR, TAG, "Error sending response"); - ehResult = OC_EH_ERROR; - } - } - } - if (flag & OC_OBSERVE_FLAG) - { - OCLog(INFO, TAG, "Flag includes OC_OBSERVE_FLAG"); - - if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) - { - OCLog(INFO, TAG, "Received OC_OBSERVE_REGISTER from client"); - ProcessObserveRegister(entityHandlerRequest); - } - else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) - { - OCLog(INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client"); - ProcessObserveDeregister(entityHandlerRequest); - } - } - - OCPayloadDestroy(response.payload); - return ehResult; -} - -/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ -void handleSigInt(int signum) -{ - gQuitFlag = 1; -} - -void *ChangeLightRepresentation(void *param) -{ - (void)param; - OCStackResult result = OC_STACK_ERROR; - - uint8_t j = 0; - uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS) / 2; - OCObservationId obsNotify[numNotifies]; - - while (!gQuitFlag) - { - sleep(3); - Light.power += 5; - if (gLightUnderObservation) - { - OCLogv(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power); - if (gObserveNotifyType == 1) - { - // Notify list of observers. Alternate observers on the list will be notified. - j = 0; - for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i = i + 2)) - { - if (interestedObservers[i].valid == true) - { - obsNotify[j] = interestedObservers[i].observationId; - j++; - } - } - - OCRepPayload *payload = getPayload(gResourceUri, Light.power, Light.state); - result = OCNotifyListOfObservers(Light.handle, obsNotify, j, - payload, OC_NA_QOS); - OCRepPayloadDestroy(payload); - } - else if (gObserveNotifyType == 0) - { - // Notifying all observers - result = OCNotifyAllObservers(Light.handle, OC_NA_QOS); - if (OC_STACK_NO_OBSERVERS == result) - { - OCLog(INFO, TAG, - "=======> No more observers exist, stop sending observations"); - gLightUnderObservation = 0; - } - } - else - { - OCLog(ERROR, TAG, "Incorrect notification type selected"); - } - } - } - return NULL; -} - -#ifdef WITH_PRESENCE -void *presenceNotificationGenerator(void *param) -{ - uint8_t secondsBeforePresence = 10; - OCLogv(INFO, TAG, "Will send out presence in %u seconds", secondsBeforePresence); - sleep(secondsBeforePresence); - (void)param; - OCDoHandle presenceNotificationHandles[numPresenceResources]; - OCStackResult res = OC_STACK_OK; - -// std::array presenceNotificationResources { { -// std::string("core.fan"), -// std::string("core.led") } }; -// std::array presenceNotificationUris { { -// std::string("/a/fan"), -// std::string("/a/led") } }; - - char *presenceNotificationResources[numPresenceResources] = {"core.fan", "core.led"}; - char *presenceNotificationUris[numPresenceResources] = {"/a/fan", "/a/led"}; - - for (int i = 0; i < numPresenceResources; i++) - { - if (res == OC_STACK_OK) - { - sleep(1); - res = OCCreateResource(&presenceNotificationHandles[i], - presenceNotificationResources[i], - OC_RSRVD_INTERFACE_DEFAULT, - presenceNotificationUris[i], - OCNOPEntityHandlerCb, - NULL, - OC_DISCOVERABLE | OC_OBSERVABLE); - } - if (res != OC_STACK_OK) - { - OCLogv(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource " - "%s with result %s.", presenceNotificationResources[i], - getResult(res)); - break; - } - OCLogv(INFO, TAG, PCF("Created %s for presence notification"), - presenceNotificationUris[i]); - } - sleep(5); - for (int i = 0; i < numPresenceResources; i++) - { - if (res == OC_STACK_OK) - { - res = OCDeleteResource(presenceNotificationHandles[i]); - } - if (res != OC_STACK_OK) - { - OCLogv(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\ - "resource %s.", presenceNotificationResources[i]); - break; - } - OCLogv(INFO, TAG, PCF("Deleted %s for presence notification"), - presenceNotificationUris[i]); - } - - OCLog(INFO, TAG, "================ stopping presence"); - OCStopPresence(); - - return NULL; -} -#endif - - -int createLightResource(char *uri, LightResource *lightResource) -{ - if (!uri) - { - OCLog(ERROR, TAG, "Resource URI cannot be NULL"); - return -1; - } - - lightResource->state = false; - lightResource->power = 0; - OCStackResult res = OCCreateResource(&(lightResource->handle), - "core.light", - "oc.mi.def", - uri, - OCEntityHandlerCb, - NULL, - OC_DISCOVERABLE | OC_OBSERVABLE); - OCLogv(INFO, TAG, "Created Light resource with result: %s", getResult(res)); - - return 0; -} - -bool DuplicateString(char **targetString, const char *sourceString) -{ - if (!sourceString) - { - return false; - } - else - { - *targetString = (char *) malloc(strlen(sourceString) + 1); - - if (*targetString) - { - strncpy(*targetString, sourceString, (strlen(sourceString) + 1)); - return true; - } - } - return false; -} - -OCStackResult SetPlatformInfo(const char *platformID, const char *manufacturerName, - const char *manufacturerUrl, const char *modelNumber, const char *dateOfManufacture, - const char *platformVersion, const char *operatingSystemVersion, const char *hardwareVersion, - const char *firmwareVersion, const char *supportUrl, const char *systemTime) -{ - - bool success = true; - - if (manufacturerName != NULL && (strlen(manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH)) - { - return OC_STACK_INVALID_PARAM; - } - - if (manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)) - { - return OC_STACK_INVALID_PARAM; - } - - if (!DuplicateString(&platformInfo.platformID, platformID)) - { - success = false; - } - - if (!DuplicateString(&platformInfo.manufacturerName, manufacturerName)) - { - success = false; - } - - if (!DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl)) - { - success = false; - } - - if (!DuplicateString(&platformInfo.modelNumber, modelNumber)) - { - success = false; - } - - if (!DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture)) - { - success = false; - } - - if (!DuplicateString(&platformInfo.platformVersion, platformVersion)) - { - success = false; - } - - if (!DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion)) - { - success = false; - } - - if (!DuplicateString(&platformInfo.hardwareVersion, hardwareVersion)) - { - success = false; - } - - if (!DuplicateString(&platformInfo.firmwareVersion, firmwareVersion)) - { - success = false; - } - - if (!DuplicateString(&platformInfo.supportUrl, supportUrl)) - { - success = false; - } - - if (!DuplicateString(&platformInfo.systemTime, systemTime)) - { - success = false; - } - - if (success) - { - return OC_STACK_OK; - } - - DeletePlatformInfo(); - return OC_STACK_ERROR; -} - -OCStackResult SetDeviceInfoName(const char *deviceName) -{ - if (!DuplicateString(&deviceInfo.deviceName, deviceName)) - { - return OC_STACK_ERROR; - } - return OC_STACK_OK; -} - -static void PrintUsage() -{ - OCLog(INFO, TAG, "Usage : ocserver -o <0|1>"); - OCLog(INFO, TAG, "-o 0 : Notify all observers"); - OCLog(INFO, TAG, "-o 1 : Notify list of observers"); -} - -#ifdef RA_ADAPTER -static void jidbound(char *jid) -{ - OCLogv(INFO, TAG, "\n\n Bound JID: %s\n\n", jid); -} -#endif - -#ifdef CONFIG_BUILD_KERNEL -int main(int argc, FAR char *argv[]) -#else -#if defined(CONFIG_NET_LWIP) && defined(CONFIG_TASH) -int iotivity_main_cb(int argc, char *argv[]) -#else -int iotivity_main(int argc, char *argv[]) -#endif -#endif -{ - -#ifndef CONFIG_NET_LWIP_DHCPC - lowlevelif_bringup(); -#endif - -#ifdef RA_ADAPTER - char host[] = "localhost"; - char user[] = "test1"; - char pass[] = "intel123"; - char empstr[] = ""; - OCRAInfo_t rainfo = {}; - - rainfo.hostname = host; - rainfo.port = 5222; - rainfo.xmpp_domain = host; - rainfo.username = user; - rainfo.password = pass; - rainfo.resource = empstr; - rainfo.user_jid = empstr; - rainfo.jidbound = jidbound; -#endif - - /* For Test -- */ - gObserveNotifyType = 0; - /* -- For Test */ - - //printf("#################### STEP 1 ##########################"); - /* - int opt = 0; - while ((opt = getopt(3, args, "o:s:p:d:u:w:r:j:")) != -1) - { - switch(opt) - { - case 'o': - gObserveNotifyType = atoi(optarg); - break; - #ifdef RA_ADAPTER - case 's': - rainfo.hostname = optarg; - break; - case 'p': - rainfo.port = atoi(optarg); - break; - case 'd': - rainfo.xmpp_domain = optarg; - break; - case 'u': - rainfo.username = optarg; - break; - case 'w': - rainfo.password = optarg; - break; - case 'j': - rainfo.user_jid = optarg; - break; - case 'r': - rainfo.resource = optarg; - break; - #endif - default: - PrintUsage(); - return -1; - } - } - */ - - if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1)) - { - PrintUsage(); - return -1; - } - -#ifdef RA_ADAPTER - OCSetRAInfo(&rainfo); -#endif - printf("\n[Iotivity Demo - IOTIVITY version is %s] : OCServer is starting...\n", IOTIVITY_VERSION); - if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) - { - printf("OCStack init error\n"); - return 0; - } - - //printf("#################### STEP 2 ##########################\n"); - -#ifdef WITH_PRESENCE - if (OCStartPresence(0) != OC_STACK_OK) - { - OCLog(ERROR, TAG, "OCStack presence/discovery error"); - return 0; - } -#endif - - //printf("#################### STEP 3 ##########################\n"); - - OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb, NULL); - OCStackResult registrationResult = - SetPlatformInfo(platformID, manufacturerName, manufacturerUrl, modelNumber, - dateOfManufacture, platformVersion, operatingSystemVersion, hardwareVersion, - firmwareVersion, supportUrl, systemTime); - if (registrationResult != OC_STACK_OK) - { - printf("Platform info setting failed locally!\n"); - exit(EXIT_FAILURE); - } - - //printf("#################### STEP 4 ##########################\n"); - - registrationResult = OCSetPlatformInfo(platformInfo); - - if (registrationResult != OC_STACK_OK) - { - printf("Platform Registration failed!"); - exit(EXIT_FAILURE); - } - - //printf("#################### STEP 5 ##########################\n"); - - registrationResult = SetDeviceInfoName(deviceName); - - if (registrationResult != OC_STACK_OK) - { - printf("Device info setting failed locally!"); - exit(EXIT_FAILURE); - } - - //printf("#################### STEP 6 ##########################\n"); - - registrationResult = OCSetDeviceInfo(deviceInfo); - - if (registrationResult != OC_STACK_OK) - { - printf("Device Registration failed!"); - exit(EXIT_FAILURE); - } - - //printf("#################### STEP 7 ##########################\n"); - - /* - * Declare and create the example resource: Light - */ - createLightResource(gResourceUri, &Light); - - //printf("#################### STEP 8 ##########################\n"); - - // Initialize observations data structure for the resource - for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) - { - interestedObservers[i].valid = false; - } - - //printf("#################### STEP 9 ##########################\n"); - - - /* - * Create a thread for generating changes that cause presence notifications - * to be sent to clients - */ - -#ifdef WITH_PRESENCE - pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL); -#endif - - //printf("#################### STEP 10 #########################"); - - // Break from loop with Ctrl-C - OCLog(INFO, TAG, "Entering ocserver main loop..."); - OCLog(INFO, TAG, "Will send out presence in 10 seconds"); - - - DeletePlatformInfo(); - - //printf("#################### STEP 11 #########################"); - - DeleteDeviceInfo(); - - //printf("#################### STEP 12 #########################"); - - while (!gQuitFlag) - { - usleep(10000); - if (OCProcess() != OC_STACK_OK) - { - OCLog(ERROR, TAG, "OCStack process error"); - return 0; - } - } - - //printf("#################### STEP 13 #########################"); - - if (observeThreadStarted) - { - pthread_cancel(threadId_observe); - pthread_join(threadId_observe, NULL); - } - - //printf("#################### STEP 14 #########################"); - - pthread_cancel(threadId_presence); - pthread_join(threadId_presence, NULL); - - printf("Exiting ocserver main loop..."); - - if (OCStop() != OC_STACK_OK) - { - printf("OCStack process error"); - } - - return 0; -} - -#if defined(CONFIG_NET_LWIP) && defined(CONFIG_TASH) - -#define IOTIVITY_TEST_STACKSIZE 16384 -#define IOTIVITY_TEST_PRI 100 -#define IOTIVITY_TEST_SCHED_POLICIY SCHED_RR - - -int iotivity_main(int argc, char *argv[]) -{ -#if 0 - pthread_attr_t attr; - struct sched_param sparam; - pthread_t tid; - - pthread_attr_init(&attr); - sparam.sched_priority = IOTIVITY_TEST_PRI; - pthread_attr_setschedparam(&attr, &sparam); - pthread_attr_setschedpolicy(&attr, IOTIVITY_TEST_SCHED_POLICIY); - pthread_attr_setstacksize(&attr, IOTIVITY_TEST_STACKSIZE); - pthread_create(&tid, &attr, iotivity_main_cb, NULL); - pthread_setname_np(tid, "iotivity-test"); -#endif - - task_create("iotivity-test", IOTIVITY_TEST_PRI, IOTIVITY_TEST_STACKSIZE, iotivity_main_cb, - (FAR char * const *)NULL); - return 0; -} - -#endif diff --git a/apps/examples/iotivity/iotivity_sec_main.c b/apps/examples/iotivity/iotivity_sec_main.c deleted file mode 100644 index 8b99731..0000000 --- a/apps/examples/iotivity/iotivity_sec_main.c +++ /dev/null @@ -1,676 +0,0 @@ -/**************************************************************************** - * - * Copyright 2016 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific - * language governing permissions and limitations under the License. - * - ****************************************************************************/ -/////////////////////////////////////////////////////////////////////// -//NOTE : This sample server is generated based on ocserverbasicops.cpp -/////////////////////////////////////////////////////////////////////// - - - - -#include -#include -#include -#include -#include -#include - - - -/* For WiFi -- */ -#include -#include -#include -#ifdef CONFIG_NET_LWIP -#include -#include -#include -#include -#else -#include -#endif - - - - -#include "ocstack.h" -#include "logger.h" -#include "ocpayload.h" - - -#include "file_data.c" - -#define TAG "SAMPLE_JUSTWORKS" - -int sec_gQuitFlag = 0; - -/* Structure to represent a LED resource */ -typedef struct LEDRESOURCE -{ - OCResourceHandle handle; - bool state; - int power; -} LEDResource; - -static LEDResource LED; -// This variable determines instance number of the LED resource. -// Used by POST method to create a new instance of LED resource. -static int gCurrLedInstance = 0; -#define SAMPLE_MAX_NUM_POST_INSTANCE 2 -static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE]; - -char *sec_gResourceUri = (char *)"/a/led"; - -//Secure Virtual Resource database for Iotivity Server -//It contains Server's Identity and the PSK credentials -//of other devices which the server trusts - -static char CRED_FILE[] = "oic_svr_db_server.dat"; -#define MOUNTDIR "/mnt/" - -/* Function that creates a new LED resource by calling the - * OCCreateResource() method. - */ -int createLEDResource(char *uri, LEDResource *ledResource, bool resourceState, int resourcePower); - -/* This method converts the payload to JSON format */ -OCRepPayload *sec_constructResponse(OCEntityHandlerRequest *ehRequest); - -/* Following methods process the PUT, GET, POST - * requests - */ -OCEntityHandlerResult sec_ProcessGetRequest(OCEntityHandlerRequest *ehRequest, - OCRepPayload **payload); -OCEntityHandlerResult sec_ProcessPutRequest(OCEntityHandlerRequest *ehRequest, - OCRepPayload **payload); -OCEntityHandlerResult sec_ProcessPostRequest(OCEntityHandlerRequest *ehRequest, - OCEntityHandlerResponse *response, - OCRepPayload **payload); - -/* Entity Handler callback functions */ -OCEntityHandlerResult -sec_OCEntityHandlerCb(OCEntityHandlerFlag flag, - OCEntityHandlerRequest *entityHandlerRequest, - void *callbackParam); - - -#define IFHWADDRLEN 6 - -#if defined(LWIP_HAVE_LOOPIF) && LWIP_HAVE_LOOPIF == 1 -#define NET_DEVNUM 1 -#else -#define NET_DEVNUM 0 -#endif - -#if defined(CONFIG_ENC28J60) || defined(CONFIG_WICED) -#define NET_DEVNAME "en" -#elif defined(CONFIG_ARCH_BOARD_SIDK_S5JT200) -#define NET_DEVNAME "wl" -#else -#error "undefined CONFIG_NET_, check your .config" -#endif - - -#define nlldbg printf - -#define printf(...) - -static void lowlevelif_bringup(void) -{ - char ifname[6]; - uint8_t iff; - int ret = 0; - snprintf(ifname, IFNAMSIZ, "%s%d", NET_DEVNAME, NET_DEVNUM); - /* Bring Up the desired network interface */ - nlldbg("LWIP Bringing up network interface (%s)\n", ifname); - ret = netlib_ifup(ifname); - if (ret < 0) - { - printf("LWIP network interface (%s) bring up failed\n", ifname); - } - ret = netlib_getifstatus(ifname, &iff); - if (ret != OK) - { - printf("ERROR: Get %s interface flags error : %d\n", ifname, ret); - } - if (iff & IFF_UP) - { - printf("LWIP network interface (%s) is UP now\n", ifname); - } -} - - - - -const char *sec_getResult(OCStackResult result) -{ - switch (result) - { - case OC_STACK_OK: - return "OC_STACK_OK"; - case OC_STACK_RESOURCE_CREATED: - return "OC_STACK_RESOURCE_CREATED"; - case OC_STACK_RESOURCE_DELETED: - return "OC_STACK_RESOURCE_DELETED"; - case OC_STACK_INVALID_URI: - return "OC_STACK_INVALID_URI"; - case OC_STACK_INVALID_QUERY: - return "OC_STACK_INVALID_QUERY"; - case OC_STACK_INVALID_IP: - return "OC_STACK_INVALID_IP"; - case OC_STACK_INVALID_PORT: - return "OC_STACK_INVALID_PORT"; - case OC_STACK_INVALID_CALLBACK: - return "OC_STACK_INVALID_CALLBACK"; - case OC_STACK_INVALID_METHOD: - return "OC_STACK_INVALID_METHOD"; - case OC_STACK_NO_MEMORY: - return "OC_STACK_NO_MEMORY"; - case OC_STACK_COMM_ERROR: - return "OC_STACK_COMM_ERROR"; - case OC_STACK_INVALID_PARAM: - return "OC_STACK_INVALID_PARAM"; - case OC_STACK_NOTIMPL: - return "OC_STACK_NOTIMPL"; - case OC_STACK_NO_RESOURCE: - return "OC_STACK_NO_RESOURCE"; - case OC_STACK_RESOURCE_ERROR: - return "OC_STACK_RESOURCE_ERROR"; - case OC_STACK_SLOW_RESOURCE: - return "OC_STACK_SLOW_RESOURCE"; - case OC_STACK_NO_OBSERVERS: - return "OC_STACK_NO_OBSERVERS"; -#ifdef WITH_PRESENCE - case OC_STACK_PRESENCE_STOPPED: - return "OC_STACK_PRESENCE_STOPPED"; -#endif - case OC_STACK_ERROR: - return "OC_STACK_ERROR"; - default: - return "UNKNOWN"; - } -} - -OCRepPayload *sec_getPayload(const char *uri, int64_t power, bool state) -{ - OCRepPayload *payload = OCRepPayloadCreate(); - if (!payload) - { - OIC_LOG(ERROR, TAG, "Failed to allocate Payload"); - return NULL; - } - - OCRepPayloadSetUri(payload, uri); - OCRepPayloadSetPropBool(payload, "state", state); - OCRepPayloadSetPropInt(payload, "power", power); - - return payload; -} - -//This function takes the request as an input and returns the response -OCRepPayload *sec_constructResponse(OCEntityHandlerRequest *ehRequest) -{ - if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION) - { - OIC_LOG(ERROR, TAG, "Incoming payload not a representation"); - return NULL; - } - - OCRepPayload *input = (OCRepPayload *)(ehRequest->payload); - - LEDResource *currLEDResource = &LED; - - if (ehRequest->resource == gLedInstance[0].handle) - { - currLEDResource = &gLedInstance[0]; - sec_gResourceUri = (char *) "/a/led/0"; - } - else if (ehRequest->resource == gLedInstance[1].handle) - { - currLEDResource = &gLedInstance[1]; - sec_gResourceUri = (char *) "/a/led/1"; - } - - if (OC_REST_PUT == ehRequest->method) - { - // Get pointer to query - int64_t pow; - if (OCRepPayloadGetPropInt(input, "power", &pow)) - { - currLEDResource->power = pow; - } - - bool state; - if (OCRepPayloadGetPropBool(input, "state", &state)) - { - currLEDResource->state = state; - } - } - - return sec_getPayload(sec_gResourceUri, currLEDResource->power, currLEDResource->state); -} - -OCEntityHandlerResult sec_ProcessGetRequest(OCEntityHandlerRequest *ehRequest, - OCRepPayload **payload) -{ - OCEntityHandlerResult ehResult; - - OCRepPayload *getResp = sec_constructResponse(ehRequest); - - if (getResp) - { - *payload = getResp; - ehResult = OC_EH_OK; - } - else - { - ehResult = OC_EH_ERROR; - } - - return ehResult; -} - -OCEntityHandlerResult sec_ProcessPutRequest(OCEntityHandlerRequest *ehRequest, - OCRepPayload **payload) -{ - OCEntityHandlerResult ehResult; - - OCRepPayload *putResp = sec_constructResponse(ehRequest); - - if (putResp) - { - *payload = putResp; - ehResult = OC_EH_OK; - } - else - { - ehResult = OC_EH_ERROR; - } - - return ehResult; -} - -OCEntityHandlerResult sec_ProcessPostRequest(OCEntityHandlerRequest *ehRequest, - OCEntityHandlerResponse *response, OCRepPayload **payload) -{ - OCRepPayload *respPLPost_led = NULL; - OCEntityHandlerResult ehResult = OC_EH_OK; - - /* - * The entity handler determines how to process a POST request. - * Per the REST paradigm, POST can also be used to update representation of existing - * resource or create a new resource. - * In the sample below, if the POST is for /a/led then a new instance of the LED - * resource is created with default representation (if representation is included in - * POST payload it can be used as initial values) as long as the instance is - * lesser than max new instance count. Once max instance count is reached, POST on - * /a/led updated the representation of /a/led (just like PUT) - */ - - if (ehRequest->resource == LED.handle) - { - if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE) - { - // Create new LED instance - char newLedUri[15] = "/a/led/"; - int newLedUriLength = strlen(newLedUri); - snprintf(newLedUri + newLedUriLength, sizeof(newLedUri) - newLedUriLength, "%d", gCurrLedInstance); - - respPLPost_led = OCRepPayloadCreate(); - OCRepPayloadSetUri(respPLPost_led, sec_gResourceUri); - OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri); - - if (0 == createLEDResource(newLedUri, &gLedInstance[gCurrLedInstance], false, 0)) - { - OIC_LOG(INFO, TAG, "Created new LED instance"); - gLedInstance[gCurrLedInstance].state = 0; - gLedInstance[gCurrLedInstance].power = 0; - gCurrLedInstance++; - strncpy((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH); - ehResult = OC_EH_RESOURCE_CREATED; - } - } - else - { - respPLPost_led = sec_constructResponse(ehRequest); - } - } - else - { - for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++) - { - if (ehRequest->resource == gLedInstance[i].handle) - { - if (i == 0) - { - respPLPost_led = sec_constructResponse(ehRequest); - break; - } - else if (i == 1) - { - respPLPost_led = sec_constructResponse(ehRequest); - } - } - } - } - - if (respPLPost_led != NULL) - { - *payload = respPLPost_led; - ehResult = OC_EH_OK; - } - else - { - OIC_LOG_V(INFO, TAG, "Payload was NULL"); - ehResult = OC_EH_ERROR; - } - - return ehResult; -} - -OCEntityHandlerResult -sec_OCEntityHandlerCb(OCEntityHandlerFlag flag, - OCEntityHandlerRequest *entityHandlerRequest, - void *callbackParam) -{ - OIC_LOG_V(INFO, TAG, "Inside entity handler - flags: 0x%x", flag); - (void)callbackParam; - OCEntityHandlerResult ehResult = OC_EH_ERROR; - - OCEntityHandlerResponse response; - memset(&response, 0, sizeof(response)); - - // Validate pointer - if (!entityHandlerRequest) - { - OIC_LOG(ERROR, TAG, "Invalid request pointer"); - return OC_EH_ERROR; - } - - OCRepPayload *payload = NULL; - - if (flag & OC_REQUEST_FLAG) - { - OIC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG"); - if (entityHandlerRequest) - { - if (OC_REST_GET == entityHandlerRequest->method) - { - OIC_LOG(INFO, TAG, "Received OC_REST_GET from client"); - ehResult = sec_ProcessGetRequest(entityHandlerRequest, &payload); - } - else if (OC_REST_PUT == entityHandlerRequest->method) - { - OIC_LOG(INFO, TAG, "Received OC_REST_PUT from client"); - ehResult = sec_ProcessPutRequest(entityHandlerRequest, &payload); - } - else if (OC_REST_POST == entityHandlerRequest->method) - { - OIC_LOG(INFO, TAG, "Received OC_REST_POST from client"); - ehResult = sec_ProcessPostRequest(entityHandlerRequest, &response, &payload); - } - else - { - OIC_LOG_V(INFO, TAG, "Received unsupported method %d from client", - entityHandlerRequest->method); - ehResult = OC_EH_ERROR; - } - - if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN) - { - // Format the response. Note this requires some info about the request - response.requestHandle = entityHandlerRequest->requestHandle; - response.resourceHandle = entityHandlerRequest->resource; - response.ehResult = ehResult; - response.payload = (OCPayload *)(payload); - response.numSendVendorSpecificHeaderOptions = 0; - memset(response.sendVendorSpecificHeaderOptions, 0, - sizeof(response.sendVendorSpecificHeaderOptions)); - memset(response.resourceUri, 0, sizeof(response.resourceUri)); - // Indicate that response is NOT in a persistent buffer - response.persistentBufferFlag = 0; - - // Send the response - if (OCDoResponse(&response) != OC_STACK_OK) - { - OIC_LOG(ERROR, TAG, "Error sending response"); - ehResult = OC_EH_ERROR; - } - } - } - } - - OCPayloadDestroy(response.payload); - return ehResult; -} -#if 0 -/* SIGINT handler: set sec_gQuitFlag to 1 for graceful termination */ -void handleSigInt(int signum) -{ - if (signum == SIGINT) - { - sec_gQuitFlag = 1; - } -} -#endif - - -/*Called by server_fopen. Used to open the CRED_FILE -Current implementation: CRED_FILE data is loaded/hardcoded in byte_array(data_oic_svr_db_server_dat) -Open CRED_FILE always. -*/ -FILE *open_dat_file(const char *path, const char *mode) -{ - OIC_LOG(DEBUG, TAG, "\nOpen dat file called\n"); - int ret, i; - int opt; - char filename[50]; - FILE *mfile = NULL; - snprintf(filename, 50, "%s%s", MOUNTDIR, CRED_FILE); - char read_buffer[1000] = "\0"; - printf("\n [IOTIVITY SEC][SERVER FOPEN] filename=%s read_buffer=%s:\n\n", filename, read_buffer); - ret = -1; - mfile = fopen(filename, mode); - if (!mfile) - { - /* This will happen during first boot */ - mfile = fopen(filename, "wb"); - if (!mfile) - { - OIC_LOG(DEBUG, TAG, "ERROR creating a file\n"); - return mfile; - } - /* write to new file from byte array */ - /*data_oic_svr_db_server_justworks_dat*/ - /*data_data_dat*/ - printf("\nWriting: dat size =%d\n", sizeof(data_oic_svr_db_server_dat)); - ret = fwrite(data_oic_svr_db_server_dat, 1, sizeof(data_oic_svr_db_server_dat), mfile); - if (ret != sizeof(data_oic_svr_db_server_dat)) - { - printf("Write failed %d returning NULL\n", ret); - return NULL; - } - ret = fclose(mfile); - if (ret != 0) - { - printf("Close failed %d returning NULL\n", ret); - return NULL; - } - /* Now open the file for reading */ - mfile = fopen(filename, mode); - if (!mfile) - { - OIC_LOG(DEBUG, TAG, "ERROR creating a file returning NULL\n"); - return mfile; - } - } - return mfile; -} -FILE *server_fopen(const char *path, const char *mode) -{ - (void)path; - return open_dat_file(path, mode); -} -#ifdef CONFIG_FS_SMARTFS - -static int fs_sample_erase() -{ - int ret = -1; - printf("File system erasing started. Please wait...\n"); - usleep(1000); - - /* Erase entire flash */ - ret = fs_erase("/dev/smart1"); - if (ret != OK) - { - return ret; - } - printf("File system erase done\n"); - usleep(1000); - return 0; -} -static int fs_sample_initiate() -{ - int ret = -1; - - printf("File system initiation started. Please wait...\n"); - - /* Initiate file system */ - ret = fs_initiate("/dev/smart1", "smartfs"); - if (ret != OK) - { - return ret; - } - printf("File system initiation done\n"); - return 0; -} -#endif - - -#ifdef CONFIG_BUILD_KERNEL -int main(int argc, FAR char *argv[]) -#else -#ifndef CONFIG_NET_LWIP -int iotivity_sec_main(int argc, char *argv[]) -#else -int iotivity_sec_main_cb(int argc, char *argv[]) -#endif -#endif -{ - -#ifndef CONFIG_NET_LWIP_DHCPC - lowlevelif_bringup(); -#endif - -#ifdef CONFIG_FS_SMARTFS - fs_sample_erase(); /*Required while running iotivity_sec for first time.*/ - fs_sample_initiate(); -#endif - - struct timespec timeout; - - OIC_LOG(DEBUG, TAG, "OCServer is starting..."); - - // Initialize Persistent Storage for SVR database - OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink}; - - OCRegisterPersistentStorageHandler(&ps); - - OIC_LOG(DEBUG, TAG, "OCServer Calling .OCRegisterPersistentStorageHandler.."); - - if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) - { - OIC_LOG(ERROR, TAG, "OCStack init error"); - return 0; - } - OIC_LOG(DEBUG, TAG, "OCServer Calling .After OCINit.."); - - /* - * Declare and create the example resource: LED - */ - createLEDResource(sec_gResourceUri, &LED, false, 0); - - OIC_LOG(DEBUG, TAG, "OCServer Calling .After createLED.."); - - timeout.tv_sec = 0; - timeout.tv_nsec = 100000000L; - - // Break from loop with Ctrl-C - OIC_LOG(INFO, TAG, "Entering ocserver main loop..."); - // signal(SIGINT, handleSigInt); - while (!sec_gQuitFlag) - { - if (OCProcess() != OC_STACK_OK) - { - OIC_LOG(ERROR, TAG, "OCStack process error"); - return 0; - } - nanosleep(&timeout, NULL); - } - - OIC_LOG(INFO, TAG, "Exiting ocserver main loop..."); - - if (OCStop() != OC_STACK_OK) - { - OIC_LOG(ERROR, TAG, "OCStack process error"); - } - - return 0; -} - -int createLEDResource(char *uri, LEDResource *ledResource, bool resourceState, int resourcePower) -{ - if (!uri) - { - OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL"); - return -1; - } - - ledResource->state = resourceState; - ledResource->power = resourcePower; - OCStackResult res = OCCreateResource(&(ledResource->handle), - "core.led", - OC_RSRVD_INTERFACE_DEFAULT, - uri, - sec_OCEntityHandlerCb, - NULL, - OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE); - OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", sec_getResult(res)); - - return 0; -} - - - -#ifdef CONFIG_NET_LWIP - -#define IOTIVITY_TEST_STACKSIZE 16384 -#define IOTIVITY_TEST_PRI 100 -#define IOTIVITY_TEST_SCHED_POLICIY SCHED_RR - - -int iotivity_sec_main(int argc, char *argv[]) -{ - - task_create("iotivity-sec-test", IOTIVITY_TEST_PRI, IOTIVITY_TEST_STACKSIZE, - iotivity_sec_main_cb, (FAR char * const *)NULL); - return 0; -} - -#endif - - diff --git a/apps/examples/iotivity/iotivityopts.h b/apps/examples/iotivity/iotivityopts.h deleted file mode 100644 index 280d571..0000000 --- a/apps/examples/iotivity/iotivityopts.h +++ /dev/null @@ -1,90 +0,0 @@ -/**************************************************************************** - * - * Copyright 2016 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific - * language governing permissions and limitations under the License. - * - ****************************************************************************/ -#ifndef __IOTIVITY_IOTIVITYOPTS_H__ -#define __IOTIVITY_IOTIVITYOPTS_H__ - -/******************************************************************************************* - * Included Files - *******************************************************************************************/ -#include -#include - -#ifdef CONFIG_ENABLE_IOTIVITY - -#define __TINYARA__ 1 - -#ifdef CONFIG_TB_LOG -#define TB_LOG 1 -#endif -#ifdef CONFIG_TCP_ADAPTER -#define TCP_ADAPTER 1 -#endif -#ifdef CONFIG_WITH_TCP -#define WITH_TCP 1 -#endif -#ifdef CONFIG_WITH_DTLS -#define __WITH_DTLS__ 1 -#endif -#ifdef CONFIG_WITH_X509 -#define __WITH_X509__ 1 -#endif -#ifdef CONFIG_WITH_SHA256 -#define WITH_SHA256 1 -#endif -#ifdef CONFIG_ROUTING_EP -#define ROUTING_EP 1 -#endif - - -#define RTM_NEWLINK 16 -#define NETLINK_ROUTE 0 - -struct sockaddr_nl -{ - __kernel_sa_family_t nl_family; /* AF_NETLINK */ - unsigned short nl_pad; /* zero */ - __u32 nl_pid; /* port ID */ - __u32 nl_groups; /* multicast groups mask */ -}; - - -struct nlmsghdr -{ - __u32 nlmsg_len; /* Length of message including header */ - __u16 nlmsg_type; /* Message content */ - __u16 nlmsg_flags; /* Additional flags */ - __u32 nlmsg_seq; /* Sequence number */ - __u32 nlmsg_pid; /* Sending process port ID */ -}; - -#define NLMSG_ALIGNTO 4U -#define NLMSG_ALIGN(len) ( ((len)+NLMSG_ALIGNTO-1) & ~(NLMSG_ALIGNTO-1) ) -#define NLMSG_HDRLEN ((int) NLMSG_ALIGN(sizeof(struct nlmsghdr))) -#define NLMSG_LENGTH(len) ((len) + NLMSG_HDRLEN) -#define NLMSG_DATA(nlh) ((void*)(((char*)nlh) + NLMSG_LENGTH(0))) -#define NLMSG_NEXT(nlh,len) ((len) -= NLMSG_ALIGN((nlh)->nlmsg_len), \ - (struct nlmsghdr*)(((char*)(nlh)) + NLMSG_ALIGN((nlh)->nlmsg_len))) -#define NLMSG_OK(nlh,len) ((len) >= (int)sizeof(struct nlmsghdr) && \ - (nlh)->nlmsg_len >= sizeof(struct nlmsghdr) && \ - (nlh)->nlmsg_len <= (len)) - - -#endif - - -#endif /* __IOTIVITY_IOTIVITYOPTS_H__ */ diff --git a/apps/examples/iotivity/mkfsdata.pl b/apps/examples/iotivity/mkfsdata.pl deleted file mode 100755 index 78a2394..0000000 --- a/apps/examples/iotivity/mkfsdata.pl +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/perl -########################################################################### -# -# Copyright 2016 Samsung Electronics All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -########################################################################### -# tools/mkfsdata.pl -# -# Extracted from uIP which has a license that is compatible with NuttX. -# There is no authorship, copyright, or licensing information in the -# original file. Possibly written by Adam Dunkels. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the -# distribution. -# 3. Neither the name NuttX nor the names of its contributors may be -# used to endorse or promote products derived from this software -# without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS -# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# - -open(OUTPUT, "> file_data.c"); - -chdir("data"); - -opendir(DIR, "."); -@files = grep { !/^\./ && !/(CVS|~)/ } readdir(DIR); -closedir(DIR); - -print(OUTPUT "#ifndef NULL\n#define NULL 0\n#endif\n\n"); - -foreach $file (@files) { - - if(-d $file && $file !~ /^\./) { - print "Processing directory $file\n"; - opendir(DIR, $file); - @newfiles = grep { !/^\./ && !/(CVS|~)/ } readdir(DIR); - closedir(DIR); - printf "Adding files @newfiles\n"; - @files = (@files, map { $_ = "$file/$_" } @newfiles); - next; - } -} - -foreach $file (@files) { - if(-f $file) { - - print "Adding file $file\n"; - - open(FILE, $file) || die "Could not open file $file\n"; - - $file =~ s-^-/-; - $fvar = $file; - $fvar =~ s-/-_-g; - $fvar =~ s-\.-_-g; - # for AVR, add PROGMEM here - print(OUTPUT "static const unsigned char data".$fvar."[] =\n"); - print(OUTPUT "{\n /* $file */\n\n "); - # for($j = 0; $j < length($file); $j++) { - # printf(OUTPUT "%#02x, ", unpack("C", substr($file, $j, 1))); - # } - # printf(OUTPUT "0x00,\n "); - - $i = 0; - while(read(FILE, $data, 1)) { - printf(OUTPUT "%#02x, ", unpack("C", $data)); - $i++; - if($i == 10) { - print(OUTPUT "\n"); - $i = 0; - print(OUTPUT " "); - } - } -# print(OUTPUT "0x00\n};\n\n"); - print(OUTPUT "\n};\n\n"); - close(FILE); - push(@fvars, $fvar); - push(@pfiles, $file); - } -} - -for($i = 0; $i < @fvars; $i++) { - $file = $pfiles[$i]; - $fvar = $fvars[$i]; - - if($i == 0) { - $prevfile = "NULL"; - } else { - $prevfile = "file" . $fvars[$i - 1]; - } -} - -# print(OUTPUT "#define HTTPD_FS_ROOT file$fvars[$i - 1]\n\n"); -print(OUTPUT "const int g_data_numfiles = $i;\n"); diff --git a/apps/examples/iotivity/ocsecurity.c b/apps/examples/iotivity/ocsecurity.c deleted file mode 100644 index e34d61f..0000000 --- a/apps/examples/iotivity/ocsecurity.c +++ /dev/null @@ -1,254 +0,0 @@ -/**************************************************************************** - * - * Copyright 2016 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific - * language governing permissions and limitations under the License. - * - ****************************************************************************/ -//****************************************************************** -// -// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#include "ocstack.h" -#include "ocmalloc.h" -#include "ocsecurity.h" -#include "ocsecurityconfig.h" -#include "cainterface.h" -#include - -static OCSecConfigData *secConfigData; -static int secConfigDataLen; - - -/** - * This internal API removes/clears the global variable holding the security - * config data. This needs to be invoked when OIC stack is shutting down. - * - * @retval none - */ -void DeinitOCSecurityInfo() -{ - if (secConfigData) - { - // Initialize sensitive data to zeroes before freeing. - memset(secConfigData, 0, secConfigDataLen); - - OCFree(secConfigData); - secConfigData = NULL; - } -} - -/** - * This internal callback is used by lower stack (i.e. CA layer) to - * retrieve PSK credentials from RI security layer. - * - * Note: When finished, caller should initialize memory to zeroes and - * invoke OCFree to delete @p credInfo. - * - * @param credInfo - * binary blob containing PSK credentials - * - * @retval none - */ -#ifdef __WITH_DTLS__ -void GetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo) -{ - // CA layer interface publishes security data structures ONLY if - // stack is compiled in SECURED mode - CADtlsPskCredsBlob_t *caBlob = NULL; - if (secConfigData && credInfo) - { - unsigned int i = 0; - OCSecBlob *osb = (OCSecBlob *)secConfigData->blob; - for (; (i < secConfigData->numBlob) && osb; i++) - { - if (osb->type == OC_BLOB_TYPE_PSK) - { - caBlob = (CADtlsPskCredsBlob_t *)OCCalloc(sizeof(CADtlsPskCredsBlob_t), 1); - if (caBlob) - { - OCDtlsPskCredsBlob *ocBlob = (OCDtlsPskCredsBlob *)osb->val; - - memcpy(caBlob->identity, ocBlob->identity, sizeof(caBlob->identity)); - caBlob->num = ocBlob->num; - caBlob->creds = - (OCDtlsPskCreds *) OCMalloc(caBlob->num * sizeof(OCDtlsPskCreds)); - if (caBlob->creds) - { - memcpy(caBlob->creds, ocBlob->creds, - caBlob->num * sizeof(OCDtlsPskCreds)); - *credInfo = caBlob; - // We copied the credential blob in the CA data structure. - // Let's get out of here. - return; - } - } - break; - } - osb = config_data_next_blob(osb); - } - } - - // Clear memory if any memory allocation failed above - if (caBlob) - { - OCFree(caBlob->creds); - OCFree(caBlob); - } -} -#endif //__WITH_DTLS__ - - -/** - * This method validates the sanctity of OCDtlsPskCredsBlob. - * - * @param secBlob - * binary blob containing PSK credentials - * - * @retval OC_STACK_OK for Success, otherwise some error value - */ -static -OCStackResult ValidateBlobTypePSK(const OCSecBlob *secBlob) -{ - OCDtlsPskCredsBlob *pskCredsBlob; - uint16_t validLen; - - if (!secBlob || secBlob->len == 0) - { - return OC_STACK_INVALID_PARAM; - } - - pskCredsBlob = (OCDtlsPskCredsBlob *)secBlob->val; - - //calculate the expected length of PSKCredsBlob - if (pskCredsBlob->num >= 1) - { - validLen = sizeof(OCDtlsPskCredsBlob) + - (pskCredsBlob->num - 1) * sizeof(OCDtlsPskCredsBlob); - } - else - { - validLen = sizeof(OCDtlsPskCredsBlob); - } - - if (secBlob->len != validLen) - return OC_STACK_INVALID_PARAM; - - return OC_STACK_OK; -} - - -/** - * This method validates the sanctity of configuration data provided - * by application to OC stack. - * - * @param cfgdata - * binary blob containing credentials and other config data - * @param len - * length of binary blob - * - * @retval OC_STACK_OK for Success, otherwise some error value - */ -static -OCStackResult ValidateSecConfigData(const OCSecConfigData *cfgData, - size_t len) -{ - OCStackResult ret = OC_STACK_OK; - unsigned int i = 0; - OCSecBlob *osb = NULL; - - if (!cfgData || (len == 0)) - { - return OC_STACK_INVALID_PARAM; - } - - if (cfgData->version != OCSecConfigVer_CurrentVersion) - { - return OC_STACK_INVALID_PARAM; - } - - osb = (OCSecBlob *)cfgData->blob; - for (; (i < cfgData->numBlob) && osb; i++) - { - if (osb->type == OC_BLOB_TYPE_PSK) - { - ret = ValidateBlobTypePSK(osb); - } - else - { - return OC_STACK_INVALID_PARAM; - } - - if (ret != OC_STACK_OK) - { - return ret; - } - osb = config_data_next_blob(osb); - } - - return ret; -} - - - -/** - * Provides the Security configuration data to OC stack. - * - * @param cfgdata - * binary blob containing credentials and other config data - * @param len - * length of binary blob - * - * @retval OC_STACK_OK for Success, otherwise some error value - */ -OCStackResult OCSecSetConfigData(const OCSecConfigData *cfgData, - size_t len) -{ - // Validate the data inside blob before consuming - if (cfgData && ValidateSecConfigData(cfgData, len) == OC_STACK_OK) - { - // Remove existing blob - DeinitOCSecurityInfo(); - // Allocate storage for new blob - secConfigData = (OCSecConfigData *)OCMalloc(len); - if (secConfigData) - { - memcpy(secConfigData, cfgData, len); - secConfigDataLen = len; - return OC_STACK_OK; - } - - return OC_STACK_NO_MEMORY; - } - - return OC_STACK_INVALID_PARAM; -} - - - diff --git a/apps/examples/iotivity/ocserver.h b/apps/examples/iotivity/ocserver.h deleted file mode 100644 index 2400f47..0000000 --- a/apps/examples/iotivity/ocserver.h +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** - * - * Copyright 2016 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific - * language governing permissions and limitations under the License. - * - ****************************************************************************/ -//****************************************************************** -// -// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#ifndef OCSERVER_H_ -#define OCSERVER_H_ - -#include "ocstack.h" - -//----------------------------------------------------------------------------- -// Defines -//----------------------------------------------------------------------------- -#define TAG "ocserver" -#define SAMPLE_MAX_NUM_OBSERVATIONS 8 -#define SAMPLE_MAX_NUM_POST_INSTANCE 2 - -//----------------------------------------------------------------------------- -// Typedefs -//----------------------------------------------------------------------------- - -/* Structure to represent a Light resource */ -typedef struct LIGHTRESOURCE -{ - OCResourceHandle handle; - bool state; - int power; -} LightResource; - -/* Structure to represent the observers */ -typedef struct -{ - OCObservationId observationId; - bool valid; - OCResourceHandle resourceHandle; -} Observers; - -//----------------------------------------------------------------------------- -// Function prototype -//----------------------------------------------------------------------------- - -/* call getResult in common.cpp to get the result in string format. */ -const char *getResult(OCStackResult result); - -/* Function that creates a new Light resource by calling the - * OCCreateResource() method. - */ -int createLightResource(char *uri, LightResource *lightResource); - -/* This method constructs a response from the request */ -OCRepPayload *constructResponse(OCEntityHandlerRequest *ehRequest); - -/* This method changes the Light power using an independent thread - * and notifies the observers of new state of the resource. - */ -void *ChangeLightRepresentation(void *param); - -/* This method check the validity of resourceTypeName and resource interfaces - * Entity Handler has to parse the query string in order to process it - */ -OCEntityHandlerResult ValidateQueryParams(OCEntityHandlerRequest *entityHandlerRequest); - -/* Following methods process the PUT, GET, POST, Delete, - * & Observe requests */ -OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest, - OCRepPayload **payload); -OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest *ehRequest, - OCRepPayload **payload); -OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest, - OCEntityHandlerResponse *response, - OCRepPayload **payload); -OCEntityHandlerResult ProcessDeleteRequest(OCEntityHandlerRequest *ehRequest); - -OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest); - -void ProcessObserveRegister(OCEntityHandlerRequest *ehRequest); -void ProcessObserveDeregister(OCEntityHandlerRequest *ehRequest); - -void DeleteDeviceInfo(); - -OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufacture, - const char *deviceName, const char *deviceUUID, const char *firmwareVersion, - const char *hostName, const char *manufacturerName, const char *manufacturerUrl, - const char *modelNumber, const char *platformVersion, const char *supportUrl, - const char *version); - - -//----------------------------------------------------------------------------- -// Callback functions -//----------------------------------------------------------------------------- -// Entity Handler callback functions -OCEntityHandlerResult -OCDeviceEntityHandlerCb(OCEntityHandlerFlag flag, - OCEntityHandlerRequest *entityHandlerRequest, char *uri, void *callbackParam); - -OCEntityHandlerResult -OCEntityHandlerCb(OCEntityHandlerFlag flag, - OCEntityHandlerRequest *entityHandlerRequest, void *callbackParam); - -#endif - diff --git a/apps/examples/iotivity/port_tinyara.c b/apps/examples/iotivity/port_tinyara.c deleted file mode 100644 index 1f09051..0000000 --- a/apps/examples/iotivity/port_tinyara.c +++ /dev/null @@ -1,159 +0,0 @@ -/**************************************************************************** - * - * Copyright 2016 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific - * language governing permissions and limitations under the License. - * - ****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "uuid/uuid.h" - -#if CONFIG_NSOCKET_DESCRIPTORS > 0 -extern struct netif *g_netdevices; -#endif - -void uuid_generate_random(uuid_t out) -{ - int i = 0; - - srand(time(NULL)); /* TODO: Need to check time(NULL) */ - for (i = 0; i < sizeof(uuid_t); i++) { /* 16 means UUID size */ - out[i] = rand() % 0xff; - } - - out[6] = (out[6] & 0x0F) | 0x40; - out[8] = (out[8] & 0x3F) | 0x80; -} - -void uuid_generate(uuid_t out) -{ - uuid_generate_random(out); -} - -void uuid_unparse_lower(const uuid_t uu, char *out) -{ - snprintf(out, - 37 /* UUID_STRING_SIZE */, - "%02x%02x%02x%02x-" - "%02x%02x-" - "%02x%02x-" - "%02x%02x-" - "%02x%02x%02x%02x%02x%02x", - uu[0], uu[1], uu[2], uu[3], - uu[4], uu[5], - uu[6], uu[7], - uu[8], uu[9], - uu[10], uu[11], uu[12], uu[13], uu[14], uu[15]); -} - -int getifaddrs(struct ifaddrs **ifap) -{ - static struct ifaddrs ifa; - static struct sockaddr_in addr, netmask; - uint8_t flags; - - memset(&ifa, 0, sizeof(ifa)); - memset(&addr, 0, sizeof(addr)); - memset(&netmask, 0, sizeof(netmask)); - - struct netif *curr = g_netdevices; - - netlib_get_ipv4addr(curr->d_ifname, &addr.sin_addr); - netlib_get_dripv4addr(curr->d_ifname, &netmask.sin_addr); - netlib_getifstatus(curr->d_ifname, &flags); - - ifa.ifa_next = NULL; - ifa.ifa_name = curr->d_ifname; - ifa.ifa_flags = flags | IFF_RUNNING; - addr.sin_family = netmask.sin_family = AF_INET; - ifa.ifa_addr = (struct sockaddr *) &addr; - ifa.ifa_netmask = (struct sockaddr *) &netmask; - - *ifap = &ifa; - - return 0; -} - -unsigned int if_nametoindex(const char *ifname) -{ - return 0; // TODO: Now supports only 1 device -} - -const char *gai_strerror(int errcode) -{ - static const char *n_str = "null"; - return n_str; -} - -const char *getResult(OCStackResult result) -{ - switch (result) - { - case OC_STACK_OK: - return "OC_STACK_OK"; - case OC_STACK_RESOURCE_CREATED: - return "OC_STACK_RESOURCE_CREATED"; - case OC_STACK_RESOURCE_DELETED: - return "OC_STACK_RESOURCE_DELETED"; - case OC_STACK_RESOURCE_CHANGED: - return "OC_STACK_RESOURCE_CHANGED"; - case OC_STACK_INVALID_URI: - return "OC_STACK_INVALID_URI"; - case OC_STACK_INVALID_QUERY: - return "OC_STACK_INVALID_QUERY"; - case OC_STACK_INVALID_IP: - return "OC_STACK_INVALID_IP"; - case OC_STACK_INVALID_PORT: - return "OC_STACK_INVALID_PORT"; - case OC_STACK_INVALID_CALLBACK: - return "OC_STACK_INVALID_CALLBACK"; - case OC_STACK_INVALID_METHOD: - return "OC_STACK_INVALID_METHOD"; - case OC_STACK_NO_MEMORY: - return "OC_STACK_NO_MEMORY"; - case OC_STACK_COMM_ERROR: - return "OC_STACK_COMM_ERROR"; - case OC_STACK_INVALID_PARAM: - return "OC_STACK_INVALID_PARAM"; - case OC_STACK_NOTIMPL: - return "OC_STACK_NOTIMPL"; - case OC_STACK_NO_RESOURCE: - return "OC_STACK_NO_RESOURCE"; - case OC_STACK_RESOURCE_ERROR: - return "OC_STACK_RESOURCE_ERROR"; - case OC_STACK_SLOW_RESOURCE: - return "OC_STACK_SLOW_RESOURCE"; - case OC_STACK_NO_OBSERVERS: - return "OC_STACK_NO_OBSERVERS"; - case OC_STACK_UNAUTHORIZED_REQ: - return "OC_STACK_UNAUTHORIZED_REQ"; -#ifdef WITH_PRESENCE - case OC_STACK_PRESENCE_STOPPED: - return "OC_STACK_PRESENCE_STOPPED"; - case OC_STACK_PRESENCE_TIMEOUT: - return "OC_STACK_PRESENCE_TIMEOUT"; -#endif - case OC_STACK_ERROR: - return "OC_STACK_ERROR"; - default: - return "UNKNOWN"; - } -} diff --git a/apps/examples/iotivity/uuid/uuid.h b/apps/examples/iotivity/uuid/uuid.h deleted file mode 100644 index 57051a5..0000000 --- a/apps/examples/iotivity/uuid/uuid.h +++ /dev/null @@ -1,121 +0,0 @@ -/**************************************************************************** - * - * Copyright 2016 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific - * language governing permissions and limitations under the License. - * - ****************************************************************************/ -/* - * Public include file for the UUID library - * - * Copyright (C) 1996, 1997, 1998 Theodore Ts'o. - * - * %Begin-Header% - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, and the entire permission notice in its entirety, - * including the disclaimer of warranties. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote - * products derived from this software without specific prior - * written permission. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF - * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE - * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH - * DAMAGE. - * %End-Header% - */ - -#ifndef _UUID_UUID_H -#define _UUID_UUID_H - -#include -#ifndef _WIN32 -#include -#endif -#include - -typedef unsigned char uuid_t[16]; - -/* UUID Variant definitions */ -#define UUID_VARIANT_NCS 0 -#define UUID_VARIANT_DCE 1 -#define UUID_VARIANT_MICROSOFT 2 -#define UUID_VARIANT_OTHER 3 - -/* UUID Type definitions */ -#define UUID_TYPE_DCE_TIME 1 -#define UUID_TYPE_DCE_RANDOM 4 - -/* Allow UUID constants to be defined */ -#ifdef __GNUC__ -#define UUID_DEFINE(name,u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15) \ - static const uuid_t name __attribute__ ((unused)) = {u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15} -#else -#define UUID_DEFINE(name,u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15) \ - static const uuid_t name = {u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15} -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* clear.c */ -void uuid_clear(uuid_t uu); - -/* compare.c */ -int uuid_compare(const uuid_t uu1, const uuid_t uu2); - -/* copy.c */ -void uuid_copy(uuid_t dst, const uuid_t src); - -/* gen_uuid.c */ -void uuid_generate(uuid_t out); -void uuid_generate_random(uuid_t out); -void uuid_generate_time(uuid_t out); -int uuid_generate_time_safe(uuid_t out); - -/* isnull.c */ -int uuid_is_null(const uuid_t uu); - -/* parse.c */ -int uuid_parse(const char *in, uuid_t uu); - -/* unparse.c */ -void uuid_unparse(const uuid_t uu, char *out); -void uuid_unparse_lower(const uuid_t uu, char *out); -void uuid_unparse_upper(const uuid_t uu, char *out); - -/* uuid_time.c */ -time_t uuid_time(const uuid_t uu, struct timeval *ret_tv); -int uuid_type(const uuid_t uu); -int uuid_variant(const uuid_t uu); - -#ifdef __cplusplus -} -#endif - -#endif /* _UUID_UUID_H */ -- 2.7.4