--Added a single line at the end for full RI code review.
--For specific RI integration changes refer
https://gerrit.iotivity.org/gerrit/#/c/394/
Change-Id: I54e3fcf2e0c10c382d4be59d2d380eb4db5f9791
Signed-Off-By: Sudarshan Prasad <sudarshan.prasad@intel.com>
Signed-off-by: Erich Keane <erich.keane@intel.com>
Signed-off-by: Shilpa Sodani <shilpa.a.sodani@intel.com>
Signed-off-by: Sakthivel Samidurai <sakthivel.samidurai@intel.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/401
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Sashi Penta <sashi.kumar.penta@intel.com>
Tested-by: Sashi Penta <sashi.kumar.penta@intel.com>
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# The main build script
#
# Print bin upload command line (arduino only)
if target_os == 'arduino':
env.UploadHelp()
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
##
# This script includes arduino specific config for oic-resource
##
build $1 $2 false
scons resource TEST=1
echo "===================== done ====================="
+
//******************************************************************
//
-// Copyright 2014 Intel Corporation.
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <map>
+#include <stdexcept>
#include "WrapResource.h"
#include "Client.h"
*/
string MiddleClient::formatResourceID(std::shared_ptr<OCResource> resource)
{
- string host = resource->host();
- if (host.compare(0, 7, "coap://") == 0)
- host = host.erase(0, 7);
- return host + resource->uri();
+ if(!resource)
+ {
+ throw invalid_argument("Invalid resource object in formatResourceID");
+ }
+
+ return resource->sid() + resource->uri();
}
void MiddleClient::addResource(WrapResource *wres)
{
+ if(!wres)
+ {
+ throw invalid_argument("Invalid WrapResource object in addResource");
+ }
+
string resourceID = wres->getResourceID();
try {
m_resourceMap[resourceID];
m_resourceMap[resourceID] = wres;
}
}
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# Examples build script
##
env.AppendTarget('examples')
+
#//******************************************************************
#//
-#// Copyright 2014 Intel Corporation.
+#// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
#//
#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#//
rm -rf debug
rm -rf release
+
-#This script builds edisonclient for Ubuntu and edisonserver for Yocto.
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#This script builds edisonclient for Ubuntu and edisonserver for Yocto.
#Client build for Ubuntu
#Set IOTIVITY_ROOT to the root of oic-resource on Ubuntu.
-IOTIVITY_ROOT = ''
-#Set IOTIVITY_LIBS_PATH to path on Ubuntu that contains liboc.so, liboctbstack.so, liboc_logger.so and libcoap.so.
+IOTIVITY_ROOT = ''
+#Set IOTIVITY_LIBS_PATH to path on Ubuntu that contains liboc.so, liboctbstack.so, liboc_logger.so and libcoap.so.
IOTIVITY_LIBS_PATH = ''
env = DefaultEnvironment()
envClient = env.Clone()
envClient.AppendUnique(CPPPATH = [
- IOTIVITY_ROOT + '/resource/include',
+ IOTIVITY_ROOT + '/resource/include',
IOTIVITY_ROOT + '/resource/csdk/stack/include',
IOTIVITY_ROOT + '/resource/oc_logger/include',
])
sdk_root + '/usr/include/iotivity/',
sdk_root + '/usr/include/iotivity/stack/',
sdk_root + '/usr/include/iotivity/oc_logger/',
- ])
+ ])
except:
print "ERROR configuring Yocto cross-toolchain environment. This is required for building the server"
+
checkBoost 19 arm-linux-androideabi 4.9
checkBoost 19 x86 4.9
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# 'hippomocks' script to check if Hippo Mocks Unit Test library is installed.
# If not, get it and install it
os.rename(hippomocks_dir_src, hippomocks_dir_dest)
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
######################################################################
# This script manages extra build options
#
*********************************************************************************
'''
Exit(1)
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# 'resource' sub-project main build script
#
elif target_os == 'arduino':
SConscript('csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript')
+
<oic-resource>/examples/ocicuc/client
<oic-resource>/examples/ocicuc/monoprocess
<oic-resource>/examples/ocicuc/server
-
+
===============================================================================
==== Arduino ATMega 2560 - Release & Debug - Ethernet Shield ====
+
arduino:
$(error "You must specify "arduinomega" or "arduinodue" when trying to\
build arduino targets.")
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# liboctbstack (share library) build script
##
OCTBSTACK_SRC + 'occlientcb.c',
OCTBSTACK_SRC + 'ocresource.c',
OCTBSTACK_SRC + 'ocobserve.c',
- OCTBSTACK_SRC + 'ocserverrequest.c',
+ OCTBSTACK_SRC + 'ocserverrequest.c',
OCTBSTACK_SRC + 'occollection.c',
OCTBSTACK_SRC + 'oicgroup.c',
'security/src/ocsecurity.c',
liboctbstack = liboctbstack_env.SharedLibrary('octbstack', liboctbstack_src)
liboctbstack_env.InstallTarget(liboctbstack, 'liboctbstack')
+
rm -rf $(OBJ_DIR)
rm -rf release
rm -rf debug
+
legacy_clean:
rm -f *.o $(PROGRAMS)
+
void DeinitOCSecurityInfo();
#endif //OC_SECURITY_INTERNAL_H
+
#endif // __cplusplus
#endif //OC_SECURITY_H
+
#endif //OC_SECURITY_CONFIG_H
+
OCDtlsPskCredsBlob *pskCredsBlob;
uint16_t validLen;
- if(secBlob->len == 0)
+ if(!secBlob || secBlob->len == 0)
{
return OC_STACK_INVALID_PARAM;
}
}
+
#include <ocresource.h>
#include "cacommon.h"
-typedef struct OCPresence {
+typedef struct OCPresence
+{
// This is the TTL associated with presence
uint32_t TTL;
uint32_t * timeOut;
uint32_t TTLlevel;
-}OCPresence;
+} OCPresence;
-typedef struct OCMulticastNode {
- unsigned char * uri;
+typedef struct OCMulticastNode
+{
+ char * uri;
uint32_t nonce;
struct OCMulticastNode * next;
} OCMulticastNode;
-extern OCMulticastNode * mcPresenceNodes;
-
typedef struct ClientCB {
// callback method defined in application address space
OCClientResponseHandler callBack;
// This is the sequence identifier the server applies to the invocation tied to 'handle'.
uint32_t sequenceNumber;
// This is the request uri associated with the call back
- unsigned char * requestUri;
+ char * requestUri;
// Struct to hold TTL info for presence
#ifdef WITH_PRESENCE
OCPresence * presence;
extern struct ClientCB *cbList;
-//-- AddClientCB -----------------------------------------------------------
/** @ingroup ocstack
*
* This method is used to add a client callback method in cbList.
*
* @param[out] clientCB
* The resulting node from making this call. Null if out of memory.
- * @param[in] cb
+ * @param[in] cbData
* address to client callback function.
* @param[in] token
* identifier for OTA CoAP comms.
* @param[in] handle
* Masked in the public API as an 'invocation handle' - Used for callback management.
+ * @param[in] method
+ * OCMethod via which this client callback is expected to operate
* @param[in] requestUri
* the resource uri of the request.
* @param[in] resourceType
*
* @brief If the handle you're looking for does not exist, the stack will reply with a RST message.
*
- * @retval OC_STACK_OK for Success, otherwise some error value
+ * @return OC_STACK_OK for Success, otherwise some error value
*/
-//------------------------------------------------------------------------
OCStackResult
AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
CAToken_t * token, OCDoHandle *handle, OCMethod method,
- unsigned char * requestUri, unsigned char * resourceTypeName);
+ char * requestUri, char * resourceTypeName);
-//-- DeleteClientCB -----------------------------------------------------------
/** @ingroup ocstack
*
* This method is used to remove a callback node from cbList.
* @param[in] cbNode
* address to client callback node.
*/
-//------------------------------------------------------------------------
void DeleteClientCB(ClientCB *cbNode);
-//-- GetClientCB ---------------------------------------------------------
/** @ingroup ocstack
*
- * This method is used to search a cb node in cbList.
+ * This method is used to search and retrieve a cb node in cbList.
*
* @param[in] token
* token to search for.
* @param[in] requestUri
* Uri to search for.
*
- * @brief You can search by token OR by handle. Not both.
+ * @brief You can search by token OR by handle, but not both.
*
- * @retval address of the node if found, otherwise NULL
+ * @return address of the node if found, otherwise NULL
*/
-//------------------------------------------------------------------------
-ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const unsigned char * requestUri);
+ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const char * requestUri);
/**
- * Inserts a new resource type filter into this clientCB node.
+ * Inserts a new resource type filter into this cb node.
*
- * @param cbNode - the node to add the new resourceType filter to
- * @param resourceTypeName - the value to create the new resourceType filter from
+ * @param[in] cbNode
+ * the node to add the new resourceType filter to
+ * @param[in] resourceTypeName
+ * the value to create the new resourceType filter from
*
* @return
* OC_STACK_OK on success
OCStackResult InsertResourceTypeFilter(ClientCB * cbNode, const char * resourceTypeName);
#endif // WITH_PRESENCE
-//-- DeleteClientCBList --------------------------------------------------
/** @ingroup ocstack
*
* This method is used to clear the cbList.
*
*/
-//------------------------------------------------------------------------
void DeleteClientCBList();
-//-- FindAndDeleteClientCB -----------------------------------------------
/** @ingroup ocstack
*
* This method is used to verify the presence of a cb node in cbList
* @param[in] cbNode
* address to client callback node.
*/
-//------------------------------------------------------------------------
void FindAndDeleteClientCB(ClientCB * cbNode);
/** @ingroup ocstack
* The resulting node from making this call. Null if doesn't exist.
*/
//------------------------------------------------------------------------
-OCMulticastNode* GetMCPresenceNode(const unsigned char * uri);
+OCMulticastNode* GetMCPresenceNode(const char * uri);
/** @ingroup ocstack
*
* @return OC_STACK_OK for Success, otherwise some error value
*/
//------------------------------------------------------------------------
-OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, unsigned char* uri, uint32_t nonce);
+OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, char* uri, uint32_t nonce);
#endif //OC_CLIENT_CB
+
#ifndef OC_OBSERVE_H
#define OC_OBSERVE_H
-/* In CoAP sequence number is a 24 bit field */
+/* Sequence number is a 24 bit field */
#define MAX_SEQUENCE_NUMBER (0xFFFFFF)
#define MAX_OBSERVER_FAILED_COMM (2)
#define MAX_OBSERVER_NON_COUNT (3)
/* This information is stored for each registerd observer */
-typedef struct ResourceObserver {
+typedef struct ResourceObserver
+{
// Observation Identifier for request
OCObservationId observeId;
// URI of observed resource
- unsigned char *resUri;
+ char *resUri;
// Query
- unsigned char *query;
+ char *query;
//token for the observe request
CAToken_t token;
// Resource handle
#endif
OCStackResult SendListObserverNotification (OCResource * resource,
OCObservationId *obsIdList, uint8_t numberOfIds,
- unsigned char *notificationJSONPayload, uint32_t maxAge,
+ const char *notificationJSONPayload, uint32_t maxAge,
OCQualityOfService qos);
void DeleteObserverList();
CAToken_t *token,
OCResource *resHandle,
OCQualityOfService qos,
- CAAddress_t *addressInfo,
+ const CAAddress_t *addressInfo,
CAConnectivityType_t connectivityType);
OCStackResult DeleteObserverUsingToken (CAToken_t * token);
+
ResourceObserver* GetObserverUsingToken (const CAToken_t * token);
ResourceObserver* GetObserverUsingId (const OCObservationId observeId);
uint8_t * numOptions);
#endif //OC_OBSERVE_H
+
#define OC_RSRVD_OC "oc"
#define OC_RSRVD_PAYLOAD "payload"
#define OC_RSRVD_HREF "href"
+#define OC_RSRVD_REPRESENTATION "rep"
+#define OC_RSRVD_CONTENT_TYPE "ct"
#define OC_RSRVD_RESOURCE_TYPE "rt"
#define OC_RSRVD_RESOURCE_TYPE_PRESENCE "core.presence"
#define OC_RSRVD_INTERFACE "if"
#define OC_RSRVD_INTERFACE_BATCH "oc.mi.b"
#define OC_RSRVD_INTERFACE_GROUP "oc.mi.grp"
+#define OC_RSRVD_MFG_DATE "mndt"
+#define OC_RSRVD_FW_VERSION "mnfv"
+#define OC_RSRVD_HOST_NAME "hn"
+#define OC_RSRVD_MFG_NAME "mnmn"
+#define OC_RSRVD_MFG_URL "mnml"
+#define OC_RSRVD_MODEL_NUM "mnmo"
+#define OC_RSRVD_PLATFORM_VERSION "mnpv"
+#define OC_RSRVD_SUPPORT_URL "mnsl"
+#define OC_RSRVD_VERSION "icv"
+
#define OC_RSRVD_OBSERVABLE "obs"
#define OC_RSRVD_SECURE "sec"
#define OC_RESOURCE_OBSERVABLE 1
#define OC_RESOURCE_SECURE 1
-typedef enum {
+typedef enum
+{
STACK_RES_DISCOVERY_NOFILTER = 0,
STACK_RES_DISCOVERY_IF_FILTER,
STACK_RES_DISCOVERY_RT_FILTER,
STACK_DEVICE_DISCOVERY_DN_FILTER
} StackQueryTypes;
-typedef enum {
+typedef enum
+{
OC_RESOURCE_VIRTUAL = 0,
OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER,
OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER,
OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult);
#endif //OC_RESOURCEHANDLER_H
+
OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse);
// following structure will be created in occoap and passed up the stack on the server side
-typedef struct OCServerRequest {
+typedef struct OCServerRequest
+{
// the REST method retrieved from received request PDU
OCMethod method;
// resourceUrl will be filled in occoap using the path options in received request PDU
- unsigned char resourceUrl[MAX_URI_LENGTH];
+ char resourceUrl[MAX_URI_LENGTH];
// resource query send by client
- unsigned char query[MAX_QUERY_LENGTH];
+ char query[MAX_QUERY_LENGTH];
// qos is indicating if the request is CON or NON
OCQualityOfService qos;
uint8_t slowFlag;
uint8_t notificationFlag;
// reqJSON is retrieved from the payload of the received request PDU
- unsigned char reqJSONPayload[1];
+ char reqJSONPayload[1];
} OCServerRequest;
// following structure will be created in ocstack to aggregate responses (in future: for block transfer)
typedef struct OCServerResponse {
struct OCServerResponse * next;
// this is the pointer to server payload data to be transferred
- unsigned char *payload;
+ char *payload;
uint16_t remainingPayloadSize;
OCRequestHandle requestHandle;
} OCServerResponse;
OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method,
uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
- OCQualityOfService qos, unsigned char * query,
+ OCQualityOfService qos, char * query,
OCHeaderOption * rcvdVendorSpecificHeaderOptions,
- unsigned char * reqJSONPayload, CAToken_t * requestToken,
- unsigned char * resourceUrl, size_t reqTotalSize,
+ char * reqJSONPayload, CAToken_t * requestToken,
+ char * resourceUrl, size_t reqTotalSize,
CAAddress_t *addressInfo, CAConnectivityType_t connectivityType);
OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle);
// Internal function to create OCEntityHandlerRequest at the server from a received coap pdu
OCStackResult FormOCEntityHandlerRequest(OCEntityHandlerRequest * entityHandlerRequest, OCRequestHandle request,
- OCMethod method, OCResourceHandle resource, unsigned char * queryBuf, unsigned char * bufReqPayload,
+ OCMethod method, OCResourceHandle resource, char * queryBuf, char * bufReqPayload,
uint8_t numVendorOptions, OCHeaderOption * vendorOptions, OCObserveAction observeAction,
OCObservationId observeID);
void DeleteServerResponse(OCServerResponse * serverResponse);
#endif //OC_SERVER_REQUEST_H
+
#define OC_COAP_SCHEME "coap://"
#define OC_OFFSET_SEQUENCE_NUMBER (4) // the first outgoing sequence number will be 5
-typedef struct {
+typedef struct
+{
// Observe option field
uint32_t option;
// IP address & port of client registered for observe
} OCObserveReq;
// following structure will be created in occoap and passed up the stack on the server side
-typedef struct {
+typedef struct
+{
// Observe option field
uint32_t observationOption;
// the REST method retrieved from received request PDU
OCMethod method;
// resourceUrl will be filled in occoap using the path options in received request PDU
- unsigned char resourceUrl[MAX_URI_LENGTH];
+ char resourceUrl[MAX_URI_LENGTH];
// resource query send by client
- unsigned char query[MAX_QUERY_LENGTH];
+ char query[MAX_QUERY_LENGTH];
// reqJSON is retrieved from the payload of the received request PDU
- unsigned char reqJSONPayload[MAX_REQUEST_LENGTH];
+ char reqJSONPayload[MAX_REQUEST_LENGTH];
// qos is indicating if the request is CON or NON
OCQualityOfService qos;
// An array of the received vendor specific header options
uint8_t slowFlag;
uint8_t notificationFlag;
// this is the pointer to server payload data to be transferred
- unsigned char *payload;
+ char *payload;
// size of server payload data. Don't rely on null terminated data for size
uint16_t payloadSize;
// An array of the vendor specific header options the entity handler wishes to use in response
uint8_t numSendVendorSpecificHeaderOptions;
OCHeaderOption *sendVendorSpecificHeaderOptions;
// URI of new resource that entity handler might create
- unsigned char * resourceUri;
+ char * resourceUri;
} OCServerProtocolResponse;
// following structure will be created in occoap and passed up the stack on the client side
-typedef struct {
+typedef struct
+{
// handle is retrieved by comparing the token-handle pair in the PDU.
ClientCB * cbNode;
// This is how long this response is valid for (in seconds).
uint32_t maxAge;
// This is the Uri of the resource. (ex. "coap://192.168.1.1/a/led")
- unsigned char * fullUri;
+ char * fullUri;
// This is the relative Uri of the resource. (ex. "/a/led")
- unsigned char * rcvdUri;
+ char * rcvdUri;
// This is the received payload.
- unsigned char * bufRes;
+ char * bufRes;
// This is the token received OTA.
CAToken_t * rcvdToken;
OCStackResult SendPresenceNotification(OCResourceType *resourceType);
OCStackResult SendStopNotification();
#endif // WITH_PRESENCE
-int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port);
+int ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port);
OCStackResult BindResourceInterfaceToResource(OCResource* resource,
const char *resourceInterfaceName);
#endif // __cplusplus
#endif /* OCSTACKINTERNAL_H_ */
+
#define OC_MULTICAST_PREFIX "224.0.1.187:5683"
#define OC_MULTICAST_IP "224.0.1.187"
-#define USE_RANDOM_PORT (0)
#ifdef WITH_PRESENCE
#define OC_DEFAULT_PRESENCE_TTL (60)
#define OC_PRESENCE_URI "/oc/presence"
{
uint32_t size; /**< length of the address stored in addr field. */
uint8_t addr[DEV_ADDR_SIZE_MAX]; /**< device address. */
-}OCDevAddr;
+} OCDevAddr;
/**
* OC Virtual resources supported by every OC device
/**
* Standard RESTful HTTP Methods
*/
-typedef enum {
+typedef enum
+{
OC_REST_NOMETHOD = 0,
OC_REST_GET = (1 << 0), // Read
OC_REST_PUT = (1 << 1), // Write
/**
* Host Mode of Operation
*/
-typedef enum {
+typedef enum
+{
OC_CLIENT = 0,
OC_SERVER,
OC_CLIENT_SERVER
} OCMode;
-extern OCMode myStackMode;
/**
* Quality of Service
*/
-typedef enum {
+typedef enum
+{
OC_LOW_QOS = 0,
OC_MEDIUM_QOS,
OC_HIGH_QOS,
* requests from clients.
* OC_SECURE - When this bit is set, the resource is a secure resource.
*/
-typedef enum {
+typedef enum
+{
OC_ACTIVE = (1 << 0),
OC_DISCOVERABLE = (1 << 1),
OC_OBSERVABLE = (1 << 2),
/**
* Transport Protocol IDs
*/
-typedef enum {
+typedef enum
+{
OC_INVALID_ID = (1 << 0),
OC_COAP_ID = (1 << 1)
} OCTransportProtocolID;
/**
* Adaptor types
*/
-typedef enum {
+typedef enum
+{
OC_ETHERNET = 0,
OC_WIFI,
OC_EDR,
/**
* Declares Stack Results & Errors
*/
-typedef enum {
+typedef enum
+{
/* Success status code - START HERE */
OC_STACK_OK = 0,
OC_STACK_RESOURCE_CREATED,
/**
* Action associated with observation
*/
-typedef enum {
+typedef enum
+{
OC_OBSERVE_REGISTER = 0,
OC_OBSERVE_DEREGISTER = 1,
OC_OBSERVE_NO_OPTION = 2
} OCObserveAction;
-typedef struct {
+typedef struct
+{
// Action associated with observation request
OCObserveAction action;
// Identifier for observation being registered/deregistered
/**
* Possible returned values from entity handler
*/
-typedef enum {
+typedef enum
+{
OC_EH_OK = 0,
OC_EH_ERROR,
OC_EH_RESOURCE_CREATED,
// following structure will be used to define the vendor specific header options to be included
// in communication packets
-typedef struct OCHeaderOption {
+typedef struct OCHeaderOption
+{
// The protocol ID this option applies to
OCTransportProtocolID protocolID;
// The header option ID which will be added to communication packets
} OCHeaderOption;
/**
- * Incoming requests handled by the server. Requests are passed in as a parameter to the @ref OCEntityHandler callback API.
- * @brief The @ref OCEntityHandler callback API must be implemented in the application in order to receive these requests.
+ * Incoming requests handled by the server. Requests are passed in as a parameter to the
+ * @ref OCEntityHandler callback API.
+ * @brief The @ref OCEntityHandler callback API must be implemented in the application in order
+ * to receive these requests.
*/
-typedef struct {
+typedef struct
+{
// Associated resource
OCResourceHandle resource;
OCRequestHandle requestHandle;
// the REST method retrieved from received request PDU
OCMethod method;
// resource query send by client
- unsigned char * query;
+ char * query;
// Information associated with observation - valid only when OCEntityHandler
// flag includes OC_OBSERVE_FLAG
OCObservationInfo obsInfo;
uint8_t numRcvdVendorSpecificHeaderOptions;
OCHeaderOption * rcvdVendorSpecificHeaderOptions;
// reqJSON is retrieved from the payload of the received request PDU
- unsigned char * reqJSONPayload;
-}OCEntityHandlerRequest;
+ char * reqJSONPayload;
+} OCEntityHandlerRequest;
/**
* Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
*/
-typedef struct {
+typedef struct
+{
// Address of remote server
OCDevAddr * addr;
// Indicates adaptor type on which the response was received
// If associated with observe, this will represent the sequence of notifications from server.
uint32_t sequenceNumber;
// resJSONPayload is retrieved from the payload of the received request PDU
- unsigned const char * resJSONPayload;
+ const char * resJSONPayload;
// An array of the received vendor specific header options
uint8_t numRcvdVendorSpecificHeaderOptions;
OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
-}OCClientResponse;
+} OCClientResponse;
/**
* Following structure describes the device properties. All non-Null properties will be included
// Allow the entity handler to pass a result with the response
OCEntityHandlerResult ehResult;
// this is the pointer to server payload data to be transferred
- unsigned char *payload;
+ char *payload;
// size of server payload data. I don't think we should rely on null terminated data for size
uint16_t payloadSize;
// An array of the vendor specific header options the entity handler wishes to use in response
uint8_t numSendVendorSpecificHeaderOptions;
OCHeaderOption sendVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
// URI of new resource that entity handler might create
- unsigned char resourceUri[MAX_URI_LENGTH];
+ char resourceUri[MAX_URI_LENGTH];
// Server sets to true for persistent response buffer, false for non-persistent response buffer
uint8_t persistentBufferFlag;
} OCEntityHandlerResponse;
-typedef enum {
+typedef enum
+{
OC_INIT_FLAG = (1 << 0),
OC_REQUEST_FLAG = (1 << 1),
OC_OBSERVE_FLAG = (1 << 2)
} OCEntityHandlerFlag; //entity_handler_flag_t ;
// possible returned values from client application
-typedef enum {
+typedef enum
+{
OC_STACK_DELETE_TRANSACTION = 0,
OC_STACK_KEEP_TRANSACTION
} OCStackApplicationResult;
/*
* This info is passed from application to OC Stack when initiating a request to Server
*/
-typedef struct {
+typedef struct
+{
void *context;
OCClientResponseHandler cb;
OCClientContextDeleter cd;
* the well-known multicast IP address, the qos will be forced to
* OC_LOW_QOS
* since it is impractical to send other QOS levels on such addresses.
- * @param clientApplicationCB- asynchronous callback function that is invoked
+ * @param cbData - asynchronous callback function that is invoked
* by the stack when discovery or resource interaction is complete
* @param options - The address of an array containing the vendor specific
* header options to be sent with the request
*
* @param handle - handle of resource
* @return
- * property bitmap - if resource found
- * NULL - resource not found
+ * OCResourceProperty Bitmask
+ * -1 if resource is not found
*/
-uint8_t OCGetResourceProperties(OCResourceHandle handle);
+OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
/**
* Get the number of resource types of the resource.
* Get the number of resource interfaces of the resource.
*
* @param handle - handle of resource
- * @param numResources - pointer to count variable
+ * @param numResourceInterfaces - pointer to count variable
*
* @return
* OC_STACK_OK - no errors
* OC_STACK_ERROR - stack process error
*/
-OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle, uint8_t *numResourceInterfaces);
+OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
+ uint8_t *numResourceInterfaces);
/**
* Get name of resource interface of the resource.
* handle to contained resource - if resource found
* NULL - resource not found
*/
-OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle, uint8_t index);
+OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
+ uint8_t index);
/**
* Get the entity handler for a resource.
* if the query is valid after the resource representation has changed.
*
* @param handle - handle of resource
+ * @param qos - desired quality of service for the observation notifications
*
* @return
* OC_STACK_OK - no errors
OCNotifyListOfObservers (OCResourceHandle handle,
OCObservationId *obsIdList,
uint8_t numberOfIds,
- unsigned char *notificationJSONPayload,
+ const char *notificationJSONPayload,
OCQualityOfService qos);
#endif // __cplusplus
#endif /* OCSTACK_H_ */
+
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
Import('env')
arduino_simplecs_env = env.Clone()
legacy_clean:
@rm -rf bin
@rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
+
response.requestHandle = entityHandlerRequest->requestHandle;
response.resourceHandle = entityHandlerRequest->resource;
response.ehResult = ehRet;
- response.payload = (unsigned char *)payload;
+ response.payload = payload;
response.payloadSize = strlen(payload);
response.numSendVendorSpecificHeaderOptions = 0;
- memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
+ 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;
(void)param;
OCStackResult result = OC_STACK_ERROR;
modCounter += 1;
- if(modCounter % 10 == 0) // Matching the timing that the Linux Sample Server App uses for the same functionality.
+ // Matching the timing that the Linux Sample Server App uses for the same functionality.
+ if(modCounter % 10 == 0)
{
Light.power += 5;
if (gLightUnderObservation)
void loop()
{
// This artificial delay is kept here to avoid endless spinning
- // of Arduino microcontroller. Modify it as per specfic application needs.
+ // of Arduino microcontroller. Modify it as per specific application needs.
delay(2000);
// This call displays the amount of free SRAM available on Arduino
return "UNKNOWN";
}
}
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Import('env')
env.AppendTarget('samples')
+
legacy_clean:
rm -f *.o $(PROGRAMS)
+
static void PrintUsage()
{
- OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3|4|5|6|7> -c <0|1>");
+ OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1..17> -c <0|1>");
OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
OC_LOG(INFO, TAG, "-c <0|1> : Send unicast messages over Ethernet or WIFI");
OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response",
clientResponse->resJSONPayload);
}
+ else
+ {
+ OC_LOG_V(INFO, TAG, "putReqCB received Null clientResponse");
+ }
return OC_STACK_DELETE_TRANSACTION;
}
OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
clientResponse->resJSONPayload);
}
+ else
+ {
+ OC_LOG_V(INFO, TAG, "postReqCB received Null clientResponse");
+ }
return OC_STACK_DELETE_TRANSACTION;
}
OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response",
clientResponse->resJSONPayload);
}
+ else
+ {
+ OC_LOG_V(INFO, TAG, "deleteReqCB received Null clientResponse");
+ }
return OC_STACK_DELETE_TRANSACTION;
}
{
if(clientResponse == NULL)
{
- OC_LOG(INFO, TAG, "The clientResponse is NULL");
+ OC_LOG(INFO, TAG, "getReqCB received NULL clientResponse");
return OC_STACK_DELETE_TRANSACTION;
}
+
if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
{
OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
return OC_STACK_DELETE_TRANSACTION;
}
}
+ else
+ {
+ OC_LOG_V(INFO, TAG, "obsReqCB received Null clientResponse");
+ }
return OC_STACK_KEEP_TRANSACTION;
}
#ifdef WITH_PRESENCE
return OC_STACK_DELETE_TRANSACTION;
}
}
+ else
+ {
+ OC_LOG_V(INFO, TAG, "presenceCB received Null clientResponse");
+ }
return OC_STACK_KEEP_TRANSACTION;
}
#endif
InitGetRequest(OC_LOW_QOS, 0);
break;
case TEST_PUT_REQ_NON:
- InitPutRequest();
+ InitPutRequest(OC_LOW_QOS);
break;
case TEST_POST_REQ_NON:
InitPostRequest(OC_LOW_QOS);
InitObserveRequest(OC_LOW_QOS);
break;
case TEST_GET_UNAVAILABLE_RES_REQ_NON:
- InitGetRequestToUnavailableResource();
+ InitGetRequestToUnavailableResource(OC_LOW_QOS);
break;
case TEST_GET_REQ_CON:
InitGetRequest(OC_HIGH_QOS, 0);
InitGetRequest(OC_LOW_QOS, 1);
break;
case TEST_DISCOVER_DEV_REQ:
- InitDeviceDiscovery();
+ InitDeviceDiscovery(OC_LOW_QOS);
break;
default:
PrintUsage();
break;
}
}
+ else
+ {
+ OC_LOG_V(INFO, TAG, "discoveryReqCB received Null clientResponse");
+ }
return OC_STACK_KEEP_TRANSACTION;
}
fprintf(stderr, "Discovery response: \n %s\n", clientResponse->resJSONPayload);
fflush(stderr);
}
+ else
+ {
+ OC_LOG_V(INFO, TAG, "DeviceDiscoveryReqCB received Null clientResponse");
+ }
return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
}
}
#endif
-int InitGetRequestToUnavailableResource()
+int InitGetRequestToUnavailableResource(OCQualityOfService qos)
{
OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
std::ostringstream query;
query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
- return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0));
+ return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
+ getReqCB, NULL, 0));
}
int InitObserveRequest(OCQualityOfService qos)
OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
}
-int InitPutRequest()
+int InitPutRequest(OCQualityOfService qos)
{
OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
std::ostringstream query;
query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
- return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
+ return (InvokeOCDoResource(query, OC_REST_PUT, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
+ putReqCB, NULL, 0));
}
int InitPostRequest(OCQualityOfService qos)
}
}
-int InitDeviceDiscovery()
+int InitDeviceDiscovery(OCQualityOfService qos)
{
OCStackResult ret;
OCCallbackData cbData;
if(UNICAST_DISCOVERY)
{
ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
- OC_LOW_QOS, &cbData, NULL, 0);
+ (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
}
else
{
ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
- OC_LOW_QOS, &cbData, NULL, 0);
+ (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
}
if (ret != OC_STACK_OK)
return ret;
}
-int InitDiscovery()
+int InitDiscovery(OCQualityOfService qos)
{
OCStackResult ret;
OCCallbackData cbData;
if(UNICAST_DISCOVERY)
{
ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
- OC_LOW_QOS, &cbData, NULL, 0);
+ (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
}
else
{
ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
- OC_LOW_QOS, &cbData, NULL, 0);
+ (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
}
if (ret != OC_STACK_OK)
{
if(UNICAST_DISCOVERY == 0 && TEST_CASE == TEST_DISCOVER_DEV_REQ)
{
- InitDeviceDiscovery();
+ InitDeviceDiscovery(OC_LOW_QOS);
}
else
{
- InitDiscovery();
+ InitDiscovery(OC_LOW_QOS);
}
// Break from loop with Ctrl+C
coapServerPort = getPortTBServer(clientResponse);
coapServerResource = getQueryStrForGetPut(clientResponse);
}
+
/* Following are initialization functions for GET, Observe, PUT
* POST, Delete & Discovery operations
*/
-int InitGetRequestToUnavailableResource();
+int InitGetRequestToUnavailableResource(OCQualityOfService qos);
int InitObserveRequest(OCQualityOfService qos);
-int InitPutRequest();
+int InitPutRequest(OCQualityOfService qos);
int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions);
int InitPostRequest(OCQualityOfService qos);
int InitDeleteRequest(OCQualityOfService qos);
int InitGetRequest(OCQualityOfService qos);
-int InitDeviceDiscovery();
-int InitDiscovery();
+int InitDeviceDiscovery(OCQualityOfService qos);
+int InitDiscovery(OCQualityOfService qos);
/* Function to retrieve ip address, port no. of the server
* and query for the operations to be performed.
#endif
+
OCStackResult ret;
OCCallbackData cbData;
/* Start a discovery query*/
- char szQueryUri[64] = { 0 };
+ char szQueryUri[64] = {};
if (UNICAST_DISCOVERY)
{
char ipv4addr[IPV4_ADDR_SIZE];
return port;
}
-int parseJSON(unsigned const char * resJSONPayload, char ** sid_c,
+int parseJSON(const char * resJSONPayload, char ** sid_c,
char *** uri_c, int * totalRes)
{
cJSON * root = NULL;
return 0;
}
+
OCClientResponse * clientResponse);
void StripNewLineChar(char* str);
#endif
+
const char *getResult(OCStackResult result);
std::string getIPAddrTBServer(OCClientResponse * clientResponse);
std::string getPortTBServer(OCClientResponse * clientResponse);
-std::string getQueryStrForGetPut(unsigned const char * responsePayload);
+std::string getQueryStrForGetPut(const char * responsePayload);
#define TAG PCF("occlient")
#define DEFAULT_CONTEXT_VALUE 0x99
typedef struct
{
- unsigned char text[30];
+ char text[30];
CLIENT_TEST test;
} testToTextMap;
return ss.str();
}
-std::string getQueryStrForGetPut(unsigned const char * responsePayload)
+std::string getQueryStrForGetPut(const char * responsePayload)
{
- std::string jsonPayload(reinterpret_cast<char*>(const_cast<unsigned char*>(responsePayload)));
+ std::string jsonPayload(responsePayload);
return "/a/room";
}
+
static void PrintUsage()
{
- OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
+ OC_LOG(INFO, TAG, "Usage : occlient -c <0|1> -u <0|1> -t <1|2|3>");
OC_LOG(INFO, TAG, "-c <0|1> : Send unicast messages over Ethernet or WIFI");
OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
coapServerPort = getPortTBServer(clientResponse);
coapServerResource = getQueryStrForGetPut(clientResponse);
}
+
OCClientResponse * clientResponse);
#endif
+
response.requestHandle = entityHandlerRequest->requestHandle;
response.resourceHandle = entityHandlerRequest->resource;
response.ehResult = ehResult;
- response.payload = (unsigned char *)payload;
+ response.payload = payload;
response.payloadSize = strlen(payload);
// Indicate that response is NOT in a persistent buffer
response.persistentBufferFlag = 0;
response.requestHandle = entityHandlerRequest->requestHandle;
response.resourceHandle = entityHandlerRequest->resource;
response.ehResult = ehResult;
- response.payload = (unsigned char *)payload;
+ response.payload = payload;
response.payloadSize = strlen(payload);
// Indicate that response is NOT in a persistent buffer
response.persistentBufferFlag = 0;
char * obsResp = cJSON_Print(json);
cJSON_Delete(json);
result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
- (unsigned char *)obsResp, OC_NA_QOS);
+ obsResp, OC_NA_QOS);
free(obsResp);
}
else if (gObserveNotifyType == 0)
DeleteDeviceInfo();
return OC_STACK_ERROR;
}
+
char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
{
cJSON *json = cJSON_CreateObject();
+
+ if(!json)
+ {
+ OC_LOG (ERROR, TAG, "json object not created properly");
+ return NULL;
+ }
+
cJSON *format;
char *jsonResponse;
LEDResource *currLEDResource = &LED;
if(OC_REST_PUT == ehRequest->method)
{
cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
+
+ if(!putJson)
+ {
+ OC_LOG (ERROR, TAG, "putJson object not created properly");
+ cJSON_Delete(json);
+ return NULL;
+ }
currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
"on") ? true:false);
currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
}
cJSON_AddStringToObject(json,"href",gResourceUri);
- cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
+ format = cJSON_CreateObject();
+
+ if(!format)
+ {
+ OC_LOG (ERROR, TAG, "format object not created properly");
+ cJSON_Delete(json);
+ return NULL;
+ }
+
+ cJSON_AddItemToObject(json, "rep", format);
cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
cJSON_AddNumberToObject(format, "power", currLEDResource->power);
return jsonResponse;
}
-OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload,
+ uint16_t maxPayloadSize)
{
OCEntityHandlerResult ehResult;
char *getResp = constructJsonResponse(ehRequest);
- if (maxPayloadSize > strlen ((char *)getResp))
+ if(getResp)
{
- strncpy(payload, getResp, strlen((char *)getResp));
- ehResult = OC_EH_OK;
+ if (maxPayloadSize > strlen ((char *)getResp))
+ {
+ strncpy(payload, getResp, strlen((char *)getResp));
+ ehResult = OC_EH_OK;
+ }
+ else
+ {
+ OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+ maxPayloadSize);
+ ehResult = OC_EH_ERROR;
+ }
+
+ free(getResp);
}
else
{
- OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
- maxPayloadSize);
ehResult = OC_EH_ERROR;
}
- free(getResp);
-
return ehResult;
}
-OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload,
+ uint16_t maxPayloadSize)
{
OCEntityHandlerResult ehResult;
char *putResp = constructJsonResponse(ehRequest);
- if (maxPayloadSize > strlen ((char *)putResp))
+ if(putResp)
{
- strncpy(payload, putResp, strlen((char *)putResp));
- ehResult = OC_EH_OK;
+ if (maxPayloadSize > strlen ((char *)putResp))
+ {
+ strncpy(payload, putResp, strlen((char *)putResp));
+ ehResult = OC_EH_OK;
+ }
+ else
+ {
+ OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+ maxPayloadSize);
+ ehResult = OC_EH_ERROR;
+ }
+
+ free(putResp);
}
else
{
- OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
- maxPayloadSize);
ehResult = OC_EH_ERROR;
}
- free(putResp);
-
return ehResult;
}
-OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload,
+ uint16_t maxPayloadSize)
{
char *respPLPost_led = NULL;
cJSON *json;
snprintf(newLedUri, URI_MAXSIZE, "/a/led/%d", gCurrLedInstance);
json = cJSON_CreateObject();
+ if(!json)
+ {
+ return OC_EH_ERROR;
+ }
cJSON_AddStringToObject(json,"href",gResourceUri);
- cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
+ format = cJSON_CreateObject();
+
+ if(!format)
+ {
+ return OC_EH_ERROR;
+ }
+
+ cJSON_AddItemToObject(json, "rep", format);
cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
response.requestHandle = entityHandlerRequest->requestHandle;
response.resourceHandle = entityHandlerRequest->resource;
response.ehResult = ehResult;
- response.payload = (unsigned char *)payload;
+ response.payload = payload;
response.payloadSize = strlen(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
return 0;
}
+
OCEntityHandlerRequest *entityHandlerRequest);
#endif
+
response.requestHandle = ehRequest->requestHandle;
response.resourceHandle = ehRequest->resource;
response.ehResult = ret;
- response.payload = (unsigned char *)payload;
+ response.payload = payload;
response.payloadSize = strlen(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions,
response.requestHandle = ehRequest->requestHandle;
response.resourceHandle = ehRequest->resource;
response.ehResult = ret;
- response.payload = (unsigned char *)payload;
+ response.payload = payload;
response.payloadSize = strlen(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions,
response.requestHandle = ehRequest->requestHandle;
response.resourceHandle = ehRequest->resource;
response.ehResult = ret;
- response.payload = (unsigned char *)payload;
+ response.payload = payload;
response.payloadSize = strlen(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions,
response.requestHandle = ehRequest->requestHandle;
response.resourceHandle = ehRequest->resource;
response.ehResult = ret;
- response.payload = (unsigned char *)payload;
+ response.payload = payload;
response.payloadSize = strlen(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions,
res = OCBindResource(room, fan);
OC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res));
}
+
char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
{
cJSON *json = cJSON_CreateObject();
+
+ if(!json)
+ {
+ OC_LOG(ERROR, TAG, "CreateObject result in null for json");
+ return NULL;
+ }
+
cJSON *format;
char *jsonResponse;
LEDResource *currLEDResource = &LED;
if(OC_REST_PUT == ehRequest->method)
{
cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
+
+ if(!putJson)
+ {
+ OC_LOG(ERROR, TAG, "CreateObject result in null for putJson");
+ cJSON_Delete(json);
+ return NULL;
+ }
+
currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
"on") ? true:false);
currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
}
cJSON_AddStringToObject(json,"href",gResourceUri);
- cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
+ format = cJSON_CreateObject();
+
+ if(!format)
+ {
+ OC_LOG(ERROR, TAG, "CreateObject result in null for format");
+ cJSON_Delete(json);
+ return NULL;
+ }
+
+ cJSON_AddItemToObject(json, "rep", format);
cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
cJSON_AddNumberToObject(format, "power", currLEDResource->power);
response.requestHandle = ehRequest->requestHandle;
response.resourceHandle = ehRequest->resource;
response.ehResult = OC_EH_OK;
- response.payload = (unsigned char *)getResp;
+ response.payload = getResp;
response.payloadSize = strlen(getResp) + 1;
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions,
memcpy(request, entityHandlerRequest, sizeof(OCEntityHandlerRequest));
// Do deep copy of query
request->query =
- (unsigned char * )OCMalloc(strlen((const char *)entityHandlerRequest->query) + 1);
+ (char * )OCMalloc(strlen((const char *)entityHandlerRequest->query) + 1);
if (request->query)
{
strcpy((char *)request->query, (const char *)entityHandlerRequest->query);
// Copy the request payload
- request->reqJSONPayload = (unsigned char * )OCMalloc(
+ request->reqJSONPayload = (char * )OCMalloc(
strlen((const char *)entityHandlerRequest->reqJSONPayload) + 1);
if (request->reqJSONPayload)
{
return 0;
}
+
OCEntityHandlerRequest *entityHandlerRequest);
#endif
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Import('env')
Alias("samples", [ocserverbasicops, occlientbasicops])
env.AppendTarget('samples')
+
#endif //OCSAMPLE_COMMON_H_
+
legacy_clean:
rm -f *.o $(PROGRAMS)
+
{
case TEST_NON_CON_OP:
InitGetRequest(OC_LOW_QOS);
- InitPutRequest();
+ InitPutRequest(OC_LOW_QOS);
//InitPostRequest(OC_LOW_QOS);
break;
case TEST_CON_OP:
InitGetRequest(OC_HIGH_QOS);
- InitPutRequest();
+ InitPutRequest(OC_HIGH_QOS);
//InitPostRequest(OC_HIGH_QOS);
break;
}
}
-int InitPutRequest()
+int InitPutRequest(OCQualityOfService qos)
{
OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
std::ostringstream query;
query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
<< ":" << coapServerPort << coapServerResource;
- return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
+ return (InvokeOCDoResource(query, OC_REST_PUT,
+ ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
}
int InitPostRequest(OCQualityOfService qos)
OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
}
-int InitDiscovery()
+int InitDiscovery(OCQualityOfService qos)
{
OCStackResult ret;
OCCallbackData cbData;
szQueryUri);
ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0,
- discoveryReqConnType, OC_LOW_QOS, &cbData, NULL, 0);
+ discoveryReqConnType, ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
+ &cbData, NULL, 0);
if (ret != OC_STACK_OK)
{
OC_LOG(ERROR, TAG, "OCStack resource error");
return 0;
}
- InitDiscovery();
+ if(TEST_CASE == TEST_NON_CON_OP)
+ {
+ InitDiscovery(OC_LOW_QOS);
+ }
+ else if(TEST_CASE == TEST_CON_OP)
+ {
+ InitDiscovery(OC_HIGH_QOS);
+ }
timeout.tv_sec = 0;
timeout.tv_nsec = 100000000L;
}
return 0;
}
+
/* Following are initialization functions for GET, PUT
* POST & Discovery operations
*/
-int InitPutRequest();
+int InitPutRequest(OCQualityOfService qos);
int InitGetRequest(OCQualityOfService qos);
int InitPostRequest(OCQualityOfService qos);
-int InitDiscovery();
+int InitDiscovery(OCQualityOfService qos);
/* Function to retrieve ip address, port no. of the server
* and query for the operations to be performed.
OCEntityHandlerResult ehResult;
char *getResp = constructJsonResponse(ehRequest);
- if (maxPayloadSize > strlen (getResp))
+ if(getResp)
{
- strcpy(payload, getResp);
- ehResult = OC_EH_OK;
+ if (maxPayloadSize > strlen (getResp))
+ {
+ strcpy(payload, getResp);
+ ehResult = OC_EH_OK;
+ }
+ else
+ {
+ OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+ maxPayloadSize);
+ ehResult = OC_EH_ERROR;
+ }
+
+ free(getResp);
}
else
{
- OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
- maxPayloadSize);
ehResult = OC_EH_ERROR;
}
- free(getResp);
-
return ehResult;
}
OCEntityHandlerResult ehResult;
char *putResp = constructJsonResponse(ehRequest);
- if (maxPayloadSize > strlen (putResp))
+
+ if(putResp)
{
- strcpy(payload, putResp);
- ehResult = OC_EH_OK;
+ if (maxPayloadSize > strlen (putResp))
+ {
+ strcpy(payload, putResp);
+ ehResult = OC_EH_OK;
+ }
+ else
+ {
+ OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+ maxPayloadSize);
+ ehResult = OC_EH_ERROR;
+ }
+
+ free(putResp);
}
else
{
- OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
- maxPayloadSize);
ehResult = OC_EH_ERROR;
}
- free(putResp);
-
return ehResult;
}
response.requestHandle = entityHandlerRequest->requestHandle;
response.resourceHandle = entityHandlerRequest->resource;
response.ehResult = ehResult;
- response.payload = (unsigned char *)payload;
+ response.payload = payload;
response.payloadSize = strlen(payload);
response.numSendVendorSpecificHeaderOptions = 0;
memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
return 0;
}
+
#define TAG PCF("occlientcb")
struct ClientCB *cbList = NULL;
-OCMulticastNode * mcPresenceNodes = NULL;
+static OCMulticastNode * mcPresenceNodes = NULL;
OCStackResult
AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
CAToken_t * token, OCDoHandle *handle, OCMethod method,
- unsigned char * requestUri, unsigned char * resourceTypeName)
+ char * requestUri, char * resourceTypeName)
{
+ if(!clientCB || !cbData || !token || !handle || !requestUri)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
ClientCB *cbNode = NULL;
return OC_STACK_NO_MEMORY;
}
-void DeleteClientCB(ClientCB * cbNode) {
+void DeleteClientCB(ClientCB * cbNode)
+{
if(cbNode) {
LL_DELETE(cbList, cbNode);
OC_LOG(INFO, TAG, PCF("deleting tokens"));
}
}
-ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const unsigned char * requestUri)
+ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const char * requestUri)
{
ClientCB* out = NULL;
if(token) {
}
else if(requestUri) {
LL_FOREACH(cbList, out) {
- if(out->requestUri && strcmp((char *)out->requestUri, (char *)requestUri) == 0) {
+ if(out->requestUri && strcmp(out->requestUri, requestUri ) == 0)
+ {
return out;
}
}
}
}
-OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, unsigned char* uri, uint32_t nonce)
+OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, char* uri, uint32_t nonce)
{
+ if(!outnode)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCMulticastNode *node;
node = (OCMulticastNode*) OCMalloc(sizeof(OCMulticastNode));
return OC_STACK_NO_MEMORY;
}
-OCMulticastNode* GetMCPresenceNode(const unsigned char * uri) {
+OCMulticastNode* GetMCPresenceNode(const char * uri) {
OCMulticastNode* out = NULL;
if(uri) {
LL_FOREACH(mcPresenceNodes, out) {
- if(out->uri && strcmp((char *)out->uri, (char *)uri) == 0) {
+ if(out->uri && strcmp(out->uri, uri) == 0) {
return out;
}
}
OC_LOG(INFO, TAG, PCF("MulticastNode Not found !!"));
return NULL;
}
+
static OCStackResult CheckRTParamSupport(const OCResource* resource, const char* rtPtr)
{
+ if(!resource || !rtPtr)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCResourceType* rTPointer = resource->rsrcType;
while (rTPointer)
{
if( strcmp (rTPointer->resourcetypename, rtPtr) == 0)
+ {
return OC_STACK_OK;
+ }
rTPointer = rTPointer->next;
}
static OCStackResult CheckIFParamSupport(const OCResource* resource, const char* ifPtr)
{
+ if(!resource || !ifPtr)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCResourceInterface* iFPointer = resource->rsrcInterface;
while (iFPointer)
{
if( strcmp (iFPointer->name, ifPtr) == 0)
- return OC_STACK_OK;
+ {
+ return OC_STACK_OK;
+ }
iFPointer = iFPointer->next;
}
}
static OCStackResult
-ValidateQuery (const unsigned char *query, OCResourceHandle resource,
+ValidateQuery (const char *query, OCResourceHandle resource,
OCStackIfTypes *ifParam, char **rtParam)
{
- uint8_t numFields = 0, numParam;
+ uint8_t numFields = 0;
+ uint8_t numParam;
//TODO: Query and URL validation is being done for virtual resource case
// using ValidateUrlQuery function. We should be able to merge it with this
if (!query)
return OC_STACK_ERROR;
+ if(!ifParam || !rtParam)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
if (!(*query))
{
// Query string is empty
while (innerToken != NULL)
{
numParam++;
- if (strcmp (innerToken, OC_RSRVD_INTERFACE) == 0)
+ if (strncmp (innerToken, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE)) == 0)
{
// Determine the value of IF parameter
innerToken = strtok_r (NULL, "=", &endToken);
ifPtr = innerToken;
- } else if (strcmp (innerToken, OC_RSRVD_RESOURCE_TYPE) == 0) {
+ }
+ else if (strcmp (innerToken, OC_RSRVD_RESOURCE_TYPE) == 0)
+ {
// Determine the value of RT parameter
innerToken = strtok_r (NULL, "=", &endToken);
rtPtr = innerToken;
- } else {
+ }
+ else
+ {
innerToken = strtok_r (NULL, "=", &endToken);
}
}
}
if (numFields > NUM_PARAM_IN_QUERY)
{
- // M1 release supports one IF value, one RT value and no other params
+ // current release supports one IF value, one RT value and no other params
return OC_STACK_INVALID_QUERY;
}
static OCStackResult BuildRootResourceJSON(OCResource *resource,
- unsigned char * bufferPtr, uint16_t *remaining)
+ char * bufferPtr, uint16_t *remaining)
{
OCStackResult ret = OC_STACK_ERROR;
cJSON *resObj;
jsonLen = strlen(jsonStr);
if (jsonLen < *remaining)
{
- strcpy((char*) bufferPtr, jsonStr);
+ strncpy(bufferPtr, jsonStr, jsonLen);
*remaining -= jsonLen;
bufferPtr += jsonLen;
ret = OC_STACK_OK;
}
cJSON_Delete (resObj);
- free (jsonStr);
+ OCFree(jsonStr);
return ret;
}
HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest,
uint8_t filterOn, char *filterValue)
{
+ if(!ehRequest)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCStackResult ret = OC_STACK_ERROR;
- unsigned char jsonbuffer[MAX_RESPONSE_LENGTH] = {0};
+ char jsonbuffer[MAX_RESPONSE_LENGTH] = {};
size_t jsonbufferLength = 0;
uint16_t remaining = 0;
- unsigned char * ptr = NULL;
+ char * ptr = NULL;
OCResource * collResource = (OCResource *) ehRequest->resource;
ptr = jsonbuffer;
jsonbufferLength = strlen((const char *)jsonbuffer);
if(ret == OC_STACK_OK && jsonbufferLength)
{
- OCEntityHandlerResponse response = {0};
+ OCEntityHandlerResponse response = {};
response.ehResult = OC_EH_OK;
response.payload = jsonbuffer;
response.payloadSize = jsonbufferLength + 1;
{
OCStackResult stackRet = OC_STACK_ERROR;
OCEntityHandlerResult ehResult = OC_EH_ERROR;
- unsigned char jsonbuffer[MAX_RESPONSE_LENGTH] = {0};
+ char jsonbuffer[MAX_RESPONSE_LENGTH] = {0};
size_t jsonbufferLength = 0;
uint16_t remaining = 0;
- unsigned char * ptr = NULL;
+ char * ptr = NULL;
OCResource * collResource = (OCResource *) ehRequest->resource;
ptr = jsonbuffer;
jsonbufferLength = strlen((const char *)jsonbuffer);
if(jsonbufferLength)
{
- OCEntityHandlerResponse response = {0};
+ OCEntityHandlerResponse response = {};
response.ehResult = OC_EH_OK;
response.payload = jsonbuffer;
response.payloadSize = jsonbufferLength + 1;
uint8_t GetNumOfResourcesInCollection (OCResource *resource)
{
- uint8_t num = 0;
- for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+ if(resource)
{
- if (resource->rsrcResources[i])
+ uint8_t num = 0;
+ for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
{
- num++;
+ if (resource->rsrcResources[i])
+ {
+ num++;
+ }
}
+ return num;
+ }
+ else
+ {
+ return -1;
}
- return num;
}
OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
OCEntityHandlerRequest *ehRequest)
{
+ if(!ehRequest || !ehRequest->query)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCStackResult result = OC_STACK_ERROR;
OCStackIfTypes ifQueryParam = STACK_IF_INVALID;
char *rtQueryParam = NULL;
OC_LOG_V(INFO, TAG, "DefaultCollectionEntityHandler with query %s", ehRequest->query);
if (flag != OC_REQUEST_FLAG)
+ {
return OC_STACK_ERROR;
+ }
- result = ValidateQuery ((const unsigned char *)ehRequest->query,
+ result = ValidateQuery (ehRequest->query,
ehRequest->resource, &ifQueryParam, &rtQueryParam);
if (result != OC_STACK_OK)
+ {
return result;
+ }
-
- if(!((ehRequest->method == OC_REST_GET) ||
+ if(!((ehRequest->method == OC_REST_GET) ||
(ehRequest->method == OC_REST_PUT) ||
(ehRequest->method == OC_REST_POST)))
+ {
return OC_STACK_ERROR;
+ }
if (ehRequest->method == OC_REST_GET)
{
case STACK_IF_BATCH:
OC_LOG(INFO, TAG, PCF("STACK_IF_BATCH"));
- ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler = HandleAggregateResponse;
+ ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler =
+ HandleAggregateResponse;
((OCServerRequest *)ehRequest->requestHandle)->numResponses =
GetNumOfResourcesInCollection((OCResource *)ehRequest->resource) + 1;
return HandleBatchInterface(ehRequest);
default:
return OC_STACK_ERROR;
}
- } else if (ehRequest->method == OC_REST_PUT) {
+ }
+ else if (ehRequest->method == OC_REST_PUT)
+ {
switch (ifQueryParam)
{
case STACK_IF_DEFAULT:
return OC_STACK_ERROR;
case STACK_IF_BATCH:
- ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler = HandleAggregateResponse;
+ ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler =
+ HandleAggregateResponse;
((OCServerRequest *)ehRequest->requestHandle)->numResponses =
GetNumOfResourcesInCollection((OCResource *)ehRequest->resource) + 1;
return HandleBatchInterface(ehRequest);
else if (ehRequest->method == OC_REST_POST)
{
- switch (ifQueryParam)
+ if(ifQueryParam == STACK_IF_GROUP)
{
- case STACK_IF_GROUP:
- {
- OC_LOG_V(INFO, TAG, "IF_COLLECTION POST with request :: \n%s\n ",
- ehRequest->reqJSONPayload);
- return BuildCollectionGroupActionJSONResponse(OC_REST_POST/*flag*/,
- (OCResource *) ehRequest->resource, ehRequest);
- }
- default:
- return OC_STACK_ERROR;
+ OC_LOG_V(INFO, TAG, "IF_COLLECTION POST with request :: \n%s\n ",
+ ehRequest->reqJSONPayload);
+ return BuildCollectionGroupActionJSONResponse(OC_REST_POST/*flag*/,
+ (OCResource *) ehRequest->resource, ehRequest);
+ }
+ else
+ {
+ return OC_STACK_ERROR;
}
}
return result;
}
+
OCQualityOfService DetermineObserverQoS(OCMethod method, ResourceObserver * resourceObserver,
OCQualityOfService appQoS)
{
+ if(!resourceObserver)
+ {
+ OC_LOG(ERROR, TAG, "DetermineObserverQoS called with invalid resourceObserver");
+ return -1;
+ }
+
OCQualityOfService decidedQoS = appQoS;
if(appQoS == OC_NA_QOS)
{
if(resourceObserver->forceHighQos \
|| resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT)
#endif
- {
+ {
resourceObserver->lowQosCount = 0;
// at some point we have to to send CON to check on the
// availability of observer
OC_LOG(INFO, TAG, PCF("This time we are sending the notification as High qos"));
decidedQoS = OC_HIGH_QOS;
- }
+ }
else
{
(resourceObserver->lowQosCount)++;
#endif
{
OC_LOG(INFO, TAG, PCF("Entering SendObserverNotification"));
+ if(!resPtr)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCStackResult result = OC_STACK_ERROR;
ResourceObserver * resourceObserver = serverObsList;
uint8_t numObs = 0;
OCServerRequest * request = NULL;
- OCEntityHandlerRequest ehRequest = {0};
+ OCEntityHandlerRequest ehRequest = {};
OCEntityHandlerResult ehResult = OC_EH_ERROR;
// Find clients that are observing this resource
{
result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
request->method, (OCResourceHandle) resPtr, request->query,
- request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions,
- request->rcvdVendorSpecificHeaderOptions, OC_OBSERVE_NO_OPTION, 0);
+ request->reqJSONPayload,
+ request->numRcvdVendorSpecificHeaderOptions,
+ request->rcvdVendorSpecificHeaderOptions,
+ OC_OBSERVE_NO_OPTION, 0);
if(result == OC_STACK_OK)
{
ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest);
}
else
{
- OCEntityHandlerResponse ehResponse = {0};
- unsigned char presenceResBuf[MAX_RESPONSE_LENGTH] = {0};
+ OCEntityHandlerResponse ehResponse = {};
+ char presenceResBuf[MAX_RESPONSE_LENGTH] = {};
//This is effectively the implementation for the presence entity handler.
OC_LOG(DEBUG, TAG, PCF("This notification is for Presence"));
result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
OCStackResult SendListObserverNotification (OCResource * resource,
OCObservationId *obsIdList, uint8_t numberOfIds,
- unsigned char *notificationJSONPayload, uint32_t maxAge,
+ const char *notificationJSONPayload, uint32_t maxAge,
OCQualityOfService qos)
{
+ if(!resource || !obsIdList || !notificationJSONPayload)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
uint8_t numIds = numberOfIds;
ResourceObserver *observation = NULL;
uint8_t numSentNotification = 0;
OCServerRequest * request = NULL;
OCStackResult result = OC_STACK_ERROR;
- OCEntityHandlerResponse ehResponse = {0};
OC_LOG(INFO, TAG, PCF("Entering SendListObserverNotification"));
while(numIds)
request->observeResult = OC_STACK_OK;
if(result == OC_STACK_OK)
{
- memset(&ehResponse, 0, sizeof(OCEntityHandlerResponse));
+ OCEntityHandlerResponse ehResponse = {};
ehResponse.ehResult = OC_EH_OK;
- ehResponse.payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
+ ehResponse.payload = (char *) OCMalloc(MAX_RESPONSE_LENGTH);
if(!ehResponse.payload)
{
FindAndDeleteServerRequest(request);
continue;
}
- strcpy((char *)ehResponse.payload, (const char *)notificationJSONPayload);
- ehResponse.payloadSize = strlen((const char *)ehResponse.payload) + 1;
+ strncpy(ehResponse.payload, notificationJSONPayload, MAX_RESPONSE_LENGTH-1);
+ ehResponse.payloadSize = strlen(ehResponse.payload) + 1;
ehResponse.persistentBufferFlag = 0;
ehResponse.requestHandle = (OCRequestHandle) request;
ehResponse.resourceHandle = (OCResourceHandle) resource;
CAToken_t *token,
OCResource *resHandle,
OCQualityOfService qos,
- CAAddress_t *addressInfo,
+ const CAAddress_t *addressInfo,
CAConnectivityType_t connectivityType)
{
ResourceObserver *obsNode = NULL;
+ if(!resUri || !token || !*token)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
obsNode = (ResourceObserver *) OCCalloc(1, sizeof(ResourceObserver));
if (obsNode)
{
obsNode->observeId = obsId;
- obsNode->resUri = (unsigned char *)OCMalloc(strlen(resUri)+1);
+ obsNode->resUri = (char *)OCMalloc(strlen(resUri)+1);
VERIFY_NON_NULL (obsNode->resUri);
memcpy (obsNode->resUri, resUri, strlen(resUri)+1);
obsNode->qos = qos;
if(query)
{
- obsNode->query = (unsigned char *)OCMalloc(strlen(query)+1);
+ obsNode->query = (char *)OCMalloc(strlen(query)+1);
VERIFY_NON_NULL (obsNode->query);
memcpy (obsNode->query, query, strlen(query)+1);
}
obsNode->token = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
VERIFY_NON_NULL (obsNode->token);
- memset(obsNode->token, 0, CA_MAX_TOKEN_LEN + 1);
memcpy(obsNode->token, *token, CA_MAX_TOKEN_LEN);
+ obsNode->token[CA_MAX_TOKEN_LEN]='\0';
obsNode->addressInfo = *addressInfo;
obsNode->connectivityType = connectivityType;
{
ResourceObserver *out = NULL;
- if(token)
+ if(token && *token)
{
LL_FOREACH (serverObsList, out)
{
OCStackResult DeleteObserverUsingToken (CAToken_t * token)
{
+ if(!token || !*token)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
ResourceObserver *obsNode = NULL;
obsNode = GetObserverUsingToken (token);
ResourceObserver *tmp = NULL;
LL_FOREACH_SAFE (serverObsList, out, tmp)
{
- DeleteObserverUsingToken (&(out->token));
+ if(out)
+ {
+ DeleteObserverUsingToken (&(out->token));
+ }
}
serverObsList = NULL;
}
uint8_t numOptions,
uint8_t observeFlag)
{
+ if(!caHdrOpt)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
CAHeaderOption_t *tmpHdrOpt = NULL;
tmpHdrOpt = (CAHeaderOption_t *) OCMalloc ((numOptions+1)*sizeof(CAHeaderOption_t));
CAHeaderOption_t *options,
uint8_t * numOptions)
{
+ if(!observationOption)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
*observationOption = OC_OBSERVE_NO_OPTION;
- uint8_t i = 0;
- uint8_t c = 0;
- for(i = 0; i < *numOptions; i++)
+
+ if(!options || !numOptions)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ for(uint8_t i = 0; i < *numOptions; i++)
{
if(options[i].protocolID == CA_COAP_ID &&
options[i].optionID == COAP_OPTION_OBSERVE)
{
*observationOption = options[i].optionData[0];
- for(c = i; c < *numOptions-1; c++)
+ for(uint8_t c = i; c < *numOptions-1; c++)
{
options[i].protocolID = options[i+1].protocolID;
options[i].optionID = options[i+1].optionID;
}
return OC_STACK_OK;
}
+
#include "ocresourcehandler.h"
#include "ocobserve.h"
#include "occollection.h"
+#include "ocmalloc.h"
#include "logger.h"
#include "cJSON.h"
return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
}
-/* This method will return the port at which the secure resource is hosted */
-static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint32_t *port)
+/* This method will retrieve the port at which the secure resource is hosted */
+static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint16_t *port)
{
CALocalConnectivity_t* info = NULL;
uint32_t size = 0;
{
while (size--)
{
- if (info[size].isSecured == true && info[size].type == connType)
+ if (info[size].isSecured && info[size].type == connType)
{
if (info[size].type == CA_ETHERNET ||
info[size].type == CA_WIFI)
}
}
- free(info);
+ OCFree(info);
return ret;
}
-static OCStackResult ValidateUrlQuery (unsigned char *url, unsigned char *query,
+static OCStackResult ValidateUrlQuery (char *url, char *query,
uint8_t *filterOn, char **filterValue)
{
- char *filterParam;
+ if(!filterOn || !filterValue)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ char *filterParam = NULL;
OC_LOG(INFO, TAG, PCF("Entering ValidateUrlQuery"));
if (!url)
+ {
return OC_STACK_INVALID_URI;
+ }
if (strcmp ((char *)url, GetVirtualResourceUri(OC_WELL_KNOWN_URI)) == 0 ||
- strcmp ((char *)url, GetVirtualResourceUri(OC_DEVICE_URI)) == 0) {
+ strcmp ((char *)url, GetVirtualResourceUri(OC_DEVICE_URI)) == 0)
+ {
*filterOn = STACK_RES_DISCOVERY_NOFILTER;
- if (query && *query) {
- char* strTokPtr;
+ if (query && *query)
+ {
+ char* strTokPtr = NULL;
filterParam = strtok_r((char *)query, "=", &strTokPtr);
*filterValue = strtok_r(NULL, " ", &strTokPtr);
- if (!(*filterValue)) {
+ if (!(*filterValue))
+ {
return OC_STACK_INVALID_QUERY;
- } else if (strcmp (filterParam, OC_RSRVD_INTERFACE) == 0) {
+ }
+ else if (strcmp (filterParam, OC_RSRVD_INTERFACE) == 0)
+ {
// Resource discovery with interface filter
*filterOn = STACK_RES_DISCOVERY_IF_FILTER;
- } else if (strcmp (filterParam, OC_RSRVD_RESOURCE_TYPE) == 0) {
+ }
+ else if (strcmp (filterParam, OC_RSRVD_RESOURCE_TYPE) == 0)
+ {
// Resource discovery with resource type filter
*filterOn = STACK_RES_DISCOVERY_RT_FILTER;
- } else if (strcmp (filterParam, OC_RSRVD_DEVICE_ID) == 0) {
+ }
+ else if (strcmp (filterParam, OC_RSRVD_DEVICE_ID) == 0)
+ {
//Device ID filter
*filterOn = STACK_DEVICE_DISCOVERY_DI_FILTER;
- } else if (strcmp (filterParam, OC_RSRVD_DEVICE_NAME) == 0) {
+ }
+ else if (strcmp (filterParam, OC_RSRVD_DEVICE_NAME) == 0)
+ {
//Device Name filter
*filterOn = STACK_DEVICE_DISCOVERY_DN_FILTER;
- } else {
+ }
+ else
+ {
// Other filter types not supported
return OC_STACK_INVALID_QUERY;
}
}
}
#ifdef WITH_PRESENCE
- else if (strcmp((char *)url, GetVirtualResourceUri(OC_PRESENCE)) == 0) {
+ else if (strcmp((char *)url, GetVirtualResourceUri(OC_PRESENCE)) == 0)
+ {
//Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
OC_LOG(INFO, TAG, PCF("OC_PRESENCE Request"));
*filterOn = STACK_RES_DISCOVERY_NOFILTER;
}
#endif
- else {
+ else
+ {
// Other URIs not yet supported
return OC_STACK_INVALID_URI;
}
char *filterValue, char * out, uint16_t *remaining,
CAConnectivityType_t connType )
{
- OCResourceType *resourceTypePtr;
- OCResourceInterface *interfacePtr;
- cJSON *resObj, *propObj, *rtArray;
- char *jsonStr;
+ if(!resourcePtr || !out || !remaining)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCResourceType *resourceTypePtr = NULL;
+ OCResourceInterface *interfacePtr = NULL;
+ cJSON *resObj = NULL;
+ cJSON *propObj = NULL;
+ cJSON *rtArray = NULL;
+ char *jsonStr = NULL;
uint8_t encodeRes = 0;
OCStackResult ret = OC_STACK_OK;
- uint16_t jsonLen;
+ uint16_t jsonLen = 0;
OC_LOG(INFO, TAG, PCF("Entering BuildVirtualResourceResponse"));
resObj = cJSON_CreateObject();
if (resourcePtr)
{
encodeRes = 0;
- if (filterOn == STACK_RES_DISCOVERY_RT_FILTER) {
+ if (filterOn == STACK_RES_DISCOVERY_RT_FILTER)
+ {
resourceTypePtr = resourcePtr->rsrcType;
- while (resourceTypePtr) {
- if (strcmp (resourceTypePtr->resourcetypename, filterValue) == 0) {
+ while (resourceTypePtr)
+ {
+ if (strcmp (resourceTypePtr->resourcetypename, filterValue) == 0)
+ {
encodeRes = 1;
break;
}
resourceTypePtr = resourceTypePtr->next;
}
- } else if (filterOn == STACK_RES_DISCOVERY_IF_FILTER) {
+ }
+ else if (filterOn == STACK_RES_DISCOVERY_IF_FILTER)
+ {
interfacePtr = resourcePtr->rsrcInterface;
- while (interfacePtr) {
- if (strcmp (interfacePtr->name, filterValue) == 0) {
+ while (interfacePtr)
+ {
+ if (strcmp (interfacePtr->name, filterValue) == 0)
+ {
encodeRes = 1;
break;
}
interfacePtr = interfacePtr->next;
}
- } else if (filterOn == STACK_RES_DISCOVERY_NOFILTER) {
+ }
+ else if (filterOn == STACK_RES_DISCOVERY_NOFILTER)
+ {
encodeRes = 1;
- } else {
+ }
+ else
+ {
//TODO: Unsupported query filter
return OC_STACK_INVALID_QUERY;
}
- if (encodeRes) {
+ if (encodeRes)
+ {
// Add URIs
cJSON_AddItemToObject (resObj, OC_RSRVD_HREF, cJSON_CreateString(resourcePtr->uri));
// Add server instance id
- const char* serverInstanceId = OCGetServerInstanceIDString();
cJSON_AddItemToObject (resObj,
OC_RSRVD_SERVER_INSTANCE_ID,
- cJSON_CreateString(serverInstanceId));
- serverInstanceId = NULL;
+ cJSON_CreateString(OCGetServerInstanceIDString()));
cJSON_AddItemToObject (resObj, "prop", propObj = cJSON_CreateObject());
// Add resource types
cJSON_AddItemToObject (propObj, OC_RSRVD_RESOURCE_TYPE, rtArray = cJSON_CreateArray());
resourceTypePtr = resourcePtr->rsrcType;
- while (resourceTypePtr) {
+ while (resourceTypePtr)
+ {
cJSON_AddItemToArray (rtArray,
cJSON_CreateString(resourceTypePtr->resourcetypename));
resourceTypePtr = resourceTypePtr->next;
// Add interface types
cJSON_AddItemToObject (propObj, OC_RSRVD_INTERFACE, rtArray = cJSON_CreateArray());
interfacePtr = resourcePtr->rsrcInterface;
- while (interfacePtr) {
+ while (interfacePtr)
+ {
cJSON_AddItemToArray (rtArray, cJSON_CreateString(interfacePtr->name));
interfacePtr = interfacePtr->next;
}
// If resource is observable, set observability flag.
// Resources that are not observable will not have the flag.
- if (resourcePtr->resourceProperties & OC_OBSERVABLE) {
+ if (resourcePtr->resourceProperties & OC_OBSERVABLE)
+ {
cJSON_AddItemToObject (propObj, OC_RSRVD_OBSERVABLE,
cJSON_CreateNumber(OC_RESOURCE_OBSERVABLE));
}
// Set secure flag for secure resources
- if (resourcePtr->resourceProperties & OC_SECURE) {
+ if (resourcePtr->resourceProperties & OC_SECURE)
+ {
cJSON_AddNumberToObject (propObj, OC_RSRVD_SECURE, OC_RESOURCE_SECURE);
//Set the IP port also as secure resources are hosted on a different port
- uint32_t port;
- if (GetSecurePortInfo (connType, &port) == OC_STACK_OK) {
+ uint16_t port = 0;
+ if (GetSecurePortInfo (connType, &port) == OC_STACK_OK)
+ {
cJSON_AddNumberToObject (propObj, OC_RSRVD_HOSTING_PORT, port);
}
}
ret = OC_STACK_ERROR;
}
cJSON_Delete (resObj);
- free (jsonStr);
+ OCFree (jsonStr);
OC_LOG(INFO, TAG, PCF("Exiting BuildVirtualResourceResponse"));
return ret;
OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filterValue,
char *out, uint16_t *remaining)
{
+ if(!out || !remaining)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCStackResult ret = OC_STACK_ERROR;
if (savedDeviceInfo != NULL)
if (filterOn == STACK_DEVICE_DISCOVERY_DI_FILTER)
{
- if((cJSON_GetObjectItem(repObj,"di") != NULL) &&
- strcmp(cJSON_GetObjectItem(repObj,"di")->valuestring, filterValue) == 0)
+ if((cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_ID) != NULL) &&
+ strcmp(cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_ID)->valuestring, filterValue)
+ == 0)
{
ret = OC_STACK_OK;
}
}
else if (filterOn == STACK_DEVICE_DISCOVERY_DN_FILTER)
{
- if((cJSON_GetObjectItem(repObj,"dn") != NULL) &&
- strcmp(cJSON_GetObjectItem(repObj,"dn")->valuestring, filterValue) == 0)
+ if((cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_NAME) != NULL) &&
+ strcmp(cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_NAME)->valuestring,
+ filterValue) == 0)
{
ret = OC_STACK_OK;
}
ret = OC_STACK_ERROR;
}
- free(jsonStr);
+ OCFree(jsonStr);
}
else
{
return ret;
}
-//TODO ("Does it make sense to make this method as inline")
const char * GetVirtualResourceUri( OCVirtualResources resource)
{
if (resource < OC_MAX_VIRTUAL_RESOURCES)
uint8_t IsVirtualResource(const char* resourceUri)
{
+ if(!resourceUri)
+ {
+ return 0;
+ }
+
for (int i = 0; i < OC_MAX_VIRTUAL_RESOURCES; i++)
{
if (strcmp(resourceUri, GetVirtualResourceUri((OCVirtualResources)i)) == 0)
uint8_t IsCollectionResource (OCResource *resource)
{
+ if(!resource)
+ {
+ return 0;
+ }
+
for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
{
if (resource->rsrcResources[i])
OCResource *FindResourceByUri(const char* resourceUri)
{
+ if(!resourceUri)
+ {
+ return NULL;
+ }
+
OCResource * pointer = headResource;
while (pointer) {
if (strcmp(resourceUri, pointer->uri) == 0) {
ResourceHandling *handling,
OCResource **resource)
{
+ if(!request || !handling || !resource)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
OC_LOG(INFO, TAG, PCF("Entering DetermineResourceHandling"));
{
// Resource URL not specified
*handling = OC_RESOURCE_NOT_SPECIFIED;
- return OC_STACK_OK;
+ return OC_STACK_NO_RESOURCE;
}
else
{
// secure resource will entertain only authorized requests
if ((resourcePtr->resourceProperties & OC_SECURE) && (request->secured == 0))
{
- OC_LOG(INFO, TAG, PCF("Un-authorized request. Ignore it!"));
+ OC_LOG(ERROR, TAG, PCF("Un-authorized request. Ignoring"));
return OC_STACK_RESOURCE_ERROR;
}
{
*handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
return OC_STACK_OK;
- } else {
+ }
+ else
+ {
*handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
return OC_STACK_OK;
}
- } else {
+ }
+ else
+ {
// Resource not a collection
if (resourcePtr->entityHandler != defaultResourceEHandler)
{
*handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
return OC_STACK_OK;
- } else {
+ }
+ else
+ {
*handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
return OC_STACK_OK;
}
static OCStackResult
HandleVirtualResource (OCServerRequest *request, OCResource* resource)
{
+ if(!request || !resource)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCStackResult result = OC_STACK_ERROR;
char *filterValue = NULL;
uint8_t filterOn = 0;
uint16_t remaining = 0;
- unsigned char * ptr = NULL;
+ char * ptr = NULL;
uint8_t firstLoopDone = 0;
- unsigned char discoveryResBuf[MAX_RESPONSE_LENGTH] = {0};
+ char discoveryResBuf[MAX_RESPONSE_LENGTH] = {};
OC_LOG(INFO, TAG, PCF("Entering HandleVirtualResource"));
if(strlen((const char *)discoveryResBuf) > 0)
{
- OCEntityHandlerResponse response = {0};
+ OCEntityHandlerResponse response = {};
response.ehResult = OC_EH_OK;
response.payload = discoveryResBuf;
static OCStackResult
HandleDefaultDeviceEntityHandler (OCServerRequest *request)
{
+ if(!request)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCStackResult result = OC_STACK_OK;
OCEntityHandlerResult ehResult = OC_EH_ERROR;
- OCEntityHandlerRequest ehRequest = {0};
+ OCEntityHandlerRequest ehRequest = {};
OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithDefaultDeviceEntityHandler"));
result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
request->method, (OCResourceHandle) NULL, request->query,
request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions,
- request->rcvdVendorSpecificHeaderOptions, (OCObserveAction)request->observationOption, (OCObservationId)0);
+ request->rcvdVendorSpecificHeaderOptions,
+ (OCObserveAction)request->observationOption, (OCObservationId)0);
VERIFY_SUCCESS(result, OC_STACK_OK);
// At this point we know for sure that defaultDeviceHandler exists
OCResource *resource,
uint8_t collectionResource)
{
+ if(!request || ! resource)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCStackResult result = OC_STACK_ERROR;
OCEntityHandlerResult ehResult = OC_EH_ERROR;
OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
ResourceObserver *resObs = NULL;
- OCEntityHandlerRequest ehRequest = {0};
+ OCEntityHandlerRequest ehRequest = {};
OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithEntityHandler"));
result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
&request->addressInfo, request->connectivityType);
if(result == OC_STACK_OK)
{
- OC_LOG(DEBUG, TAG, PCF("Added observer successfully"));
+ OC_LOG(INFO, TAG, PCF("Added observer successfully"));
request->observeResult = OC_STACK_OK;
ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
}
{
result = OC_STACK_OK;
request->observeResult = OC_STACK_ERROR;
- OC_LOG(DEBUG, TAG, PCF("Observer Addition failed"));
+ OC_LOG(ERROR, TAG, PCF("Observer Addition failed"));
ehFlag = OC_REQUEST_FLAG;
}
if(result == OC_STACK_OK)
{
- OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
+ OC_LOG(INFO, TAG, PCF("Removed observer successfully"));
request->observeResult = OC_STACK_OK;
}
else
{
result = OC_STACK_OK;
request->observeResult = OC_STACK_ERROR;
- OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
+ OC_LOG(ERROR, TAG, PCF("Observer Removal failed"));
}
}
else
HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
OCResource *resource)
{
+ if(!request || !resource)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCStackResult result = OC_STACK_ERROR;
- OCEntityHandlerRequest ehRequest = {0};
+ OCEntityHandlerRequest ehRequest = {};
result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
request->method, (OCResourceHandle) resource, request->query,
cJSON_AddItemToObject (savedDeviceInfo, OC_RSRVD_HREF,
cJSON_CreateString(GetVirtualResourceUri(OC_DEVICE_URI)));
- cJSON_AddItemToObject (savedDeviceInfo, "rep", repObj = cJSON_CreateObject());
+ cJSON_AddItemToObject (savedDeviceInfo, OC_RSRVD_REPRESENTATION, repObj = cJSON_CreateObject());
if (deviceInfo.contentType)
{
- cJSON_AddItemToObject (repObj, "ct",
+ cJSON_AddItemToObject (repObj, OC_RSRVD_CONTENT_TYPE,
cJSON_CreateString(deviceInfo.contentType));
}
if (deviceInfo.dateOfManufacture)
{
- cJSON_AddItemToObject (repObj, "mndt",
+ cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_DATE,
cJSON_CreateString(deviceInfo.dateOfManufacture));
}
if (deviceInfo.deviceName)
{
- cJSON_AddItemToObject (repObj, "dn",
+ cJSON_AddItemToObject (repObj, OC_RSRVD_DEVICE_NAME,
cJSON_CreateString(deviceInfo.deviceName));
}
if (deviceInfo.deviceUUID)
{
- cJSON_AddItemToObject (repObj, "di",
+ cJSON_AddItemToObject (repObj, OC_RSRVD_DEVICE_ID,
cJSON_CreateString(deviceInfo.deviceUUID));
}
if (deviceInfo.firmwareVersion)
{
- cJSON_AddItemToObject (repObj, "mnfv",
+ cJSON_AddItemToObject (repObj, OC_RSRVD_FW_VERSION,
cJSON_CreateString(deviceInfo.firmwareVersion));
}
if (deviceInfo.hostName)
{
- cJSON_AddItemToObject (repObj, "hn", cJSON_CreateString(deviceInfo.hostName));
+ cJSON_AddItemToObject (repObj, OC_RSRVD_HOST_NAME,
+ cJSON_CreateString(deviceInfo.hostName));
}
if (deviceInfo.manufacturerName)
return OC_STACK_INVALID_PARAM;
}
- cJSON_AddItemToObject (repObj, "mnmn",
+ cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_NAME,
cJSON_CreateString(deviceInfo.manufacturerName));
}
return OC_STACK_INVALID_PARAM;
}
- cJSON_AddItemToObject (repObj, "mnml",
+ cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_URL,
cJSON_CreateString(deviceInfo.manufacturerUrl));
}
if (deviceInfo.modelNumber)
{
- cJSON_AddItemToObject (repObj, "mnmo",
+ cJSON_AddItemToObject (repObj, OC_RSRVD_MODEL_NUM,
cJSON_CreateString(deviceInfo.modelNumber));
}
if (deviceInfo.platformVersion)
{
- cJSON_AddItemToObject (repObj, "mnpv",
+ cJSON_AddItemToObject (repObj, OC_RSRVD_PLATFORM_VERSION,
cJSON_CreateString(deviceInfo.platformVersion));
}
if (deviceInfo.supportUrl)
{
- cJSON_AddItemToObject (repObj, "mnsl",
+ cJSON_AddItemToObject (repObj, OC_RSRVD_SUPPORT_URL,
cJSON_CreateString(deviceInfo.supportUrl));
}
if (deviceInfo.version)
{
- cJSON_AddItemToObject (repObj, "icv",
+ cJSON_AddItemToObject (repObj, OC_RSRVD_VERSION,
cJSON_CreateString(deviceInfo.version));
}
return OC_STACK_OK;
}
+
OCServerRequest * GetServerRequestUsingToken (const CAToken_t token)
{
+ if(!token)
+ {
+ OC_LOG(ERROR, TAG, PCF("Invalid Parameter Token"));
+ return NULL;
+ }
+
OCServerRequest * out = NULL;
LL_FOREACH (serverRequestList, out)
{
return out;
}
}
- OC_LOG(INFO, TAG, PCF("Server Request not found!!"));
+ OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
return NULL;
}
return out;
}
}
- OC_LOG(INFO, TAG, PCF("Server Request not found!!"));
+ OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
return NULL;
}
return out;
}
}
- OC_LOG(INFO, TAG, PCF("Server Response not found!!"));
+ OC_LOG(ERROR, TAG, PCF("Server Response not found!!"));
return NULL;
}
OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method,
uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
- OCQualityOfService qos, unsigned char * query,
+ OCQualityOfService qos, char * query,
OCHeaderOption * rcvdVendorSpecificHeaderOptions,
- unsigned char * reqJSONPayload, CAToken_t * requestToken,
- unsigned char * resourceUrl, size_t reqTotalSize,
+ char * reqJSONPayload, CAToken_t * requestToken,
+ char * resourceUrl, size_t reqTotalSize,
CAAddress_t *addressInfo, CAConnectivityType_t connectivityType)
{
OCServerRequest * serverRequest = NULL;
{
serverRequest->requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
VERIFY_NON_NULL (serverRequest->requestToken);
- memset(serverRequest->requestToken, 0, CA_MAX_TOKEN_LEN + 1);
memcpy(serverRequest->requestToken, *requestToken, CA_MAX_TOKEN_LEN);
+ serverRequest->requestToken[CA_MAX_TOKEN_LEN]='\0';
}
if(resourceUrl)
serverResponse = (OCServerResponse *) OCCalloc(1, sizeof(OCServerResponse));
VERIFY_NON_NULL(serverResponse);
- serverResponse->payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
+ serverResponse->payload = (char *) OCCalloc(1, MAX_RESPONSE_LENGTH);
VERIFY_NON_NULL(serverResponse->payload);
- memset(serverResponse->payload, 0, MAX_RESPONSE_LENGTH);
serverResponse->remainingPayloadSize = MAX_RESPONSE_LENGTH;
serverResponse->requestHandle = requestHandle;
OCRequestHandle request,
OCMethod method,
OCResourceHandle resource,
- unsigned char * queryBuf,
- unsigned char * bufReqPayload,
+ char * queryBuf,
+ char * bufReqPayload,
uint8_t numVendorOptions,
OCHeaderOption * vendorOptions,
OCObserveAction observeAction,
break;
}
- responseInfo.info.token = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
+ responseInfo.info.token = (CAToken_t)OCCalloc(1, CA_MAX_TOKEN_LEN+1);
if (!responseInfo.info.token)
{
OC_LOG(FATAL, TAG, "Response Info Token is NULL");
return result;
}
- memset(responseInfo.info.token, 0, CA_MAX_TOKEN_LEN + 1);
memcpy(responseInfo.info.token, serverRequest->requestToken, CA_MAX_TOKEN_LEN);
if(serverRequest->observeResult == OC_STACK_OK)
}
responseInfo.info.options = (CAHeaderOption_t *)
- malloc(sizeof(CAHeaderOption_t) * responseInfo.info.numOptions);
+ OCMalloc(sizeof(CAHeaderOption_t) * responseInfo.info.numOptions);
optionsPointer = responseInfo.info.options;
- if(serverRequest->observeResult == OC_STACK_OK)
- {
- responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
- }
-
// TODO: This exposes CoAP specific details. At some point, this should be
// re-factored and handled in the CA layer.
if(serverRequest->observeResult == OC_STACK_OK)
OCServerResponse * serverResponse = NULL;
uint16_t bufferNeeded = 0;
+ if(!ehResponse || !ehResponse->payload)
+ {
+ OC_LOG(ERROR, TAG, PCF("HandleAggregateResponse invalid parameters"));
+ return OC_STACK_INVALID_PARAM;
+ }
+
OC_LOG_V(INFO, TAG, "Inside HandleAggregateResponse: %s", ehResponse->payload);
serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
}
if(serverResponse->remainingPayloadSize >= bufferNeeded)
{
- OC_LOG(INFO, TAG, PCF("There is room in response buffer"));
+ OC_LOG(ERROR, TAG, PCF("There is room in response buffer"));
// append
strncat((char *)serverResponse->payload,
(char *)ehResponse->payload,
}
else
{
- OC_LOG(INFO, TAG, PCF("No room in response buffer"));
+ OC_LOG(ERROR, TAG, PCF("No room in response buffer"));
//Delete the request and response
FindAndDeleteServerRequest(serverRequest);
FindAndDeleteServerResponse(serverResponse);
exit:
return stackRet;
}
+
static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
#endif
-OCMode myStackMode;
+static OCMode myStackMode;
OCDeviceEntityHandler defaultDeviceHandler;
-OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
+OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
//-----------------------------------------------------------------------------
// Macros
static OCStackResult FormOCResponse(OCResponse * * responseLoc,
ClientCB * cbNode,
uint32_t maxAge,
- unsigned char * fullUri,
- unsigned char * rcvdUri,
+ char * fullUri,
+ char * rcvdUri,
CAToken_t * rcvdToken,
OCClientResponse * clientResponse,
- unsigned char * bufRes)
+ char * bufRes)
{
OCResponse * response = (OCResponse *) OCMalloc(sizeof(OCResponse));
if (!response)
/// This method is used to create the IPv4 dev_addr structure.
/// TODO: Remove in future. Temporary helper function.
/// Builds a socket interface address using IP address and port number
-static int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
+static OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
uint16_t port, OCDevAddr *ipAddr)
{
if ( !ipAddr ) {
- OC_LOG(FATAL, TAG, "Invalid argument");
- return 1;
+ OC_LOG(FATAL, TAG, PCF("Invalid argument"));
+ return OC_STACK_INVALID_PARAM;
}
ipAddr->addr[0] = a;
ipAddr->addr[3] = d;
*((uint16_t*)&(ipAddr->addr[4])) = port;
- return 0;
+ return OC_STACK_OK;
}
//-----------------------------------------------------------------------------
{
OCStackResult result = OC_STACK_ERROR;
ResourceObserver * observer = NULL;
- OCEntityHandlerRequest ehRequest = {0};
+ OCEntityHandlerRequest ehRequest = {};
switch(status)
{
OCStackResult UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
{
OCStackResult ret = OC_STACK_ERROR;
- static OCDevAddr address = {0};
+ static OCDevAddr address = {};
char * tok = NULL;
char * savePtr = NULL;
char * cpAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
{
char * tok = NULL;
- char * savePtr;
+ char * savePtr = NULL;
// The format of the payload is {"oc":[%u:%u:%s]}
// %u : sequence number,
// %u : max age
}
payload[strlen((char *)payload)] = ':';
strcpy(*resType, tok);
- OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s", *resType);
+ OC_LOG_V(DEBUG, TAG, "resourceTypeName %s", *resType);
}
payload[strlen((char *)payload)] = ']';
}
goto exit;
}
- ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
+ size_t addressLen = strlen(endPoint->addressInfo.IP.ipAddress);
+ ipAddress = (char *) OCMalloc(addressLen + 1);
if(NULL == ipAddress)
{
goto exit;
}
- strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress,
- strlen(endPoint->addressInfo.IP.ipAddress));
- ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
+ strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress, addressLen);
+ ipAddress[addressLen] = '\0';
snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
OC_PRESENCE_URI);
- cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
+ cbNode = GetClientCB(NULL, NULL, fullUri);
if(cbNode)
{
else
{
snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
- cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
+ cbNode = GetClientCB(NULL, NULL, fullUri);
if(cbNode)
{
multicastPresenceSubscribe = 1;
if(!presenceSubscribe && !multicastPresenceSubscribe)
{
- OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
- ------------ ignoring"));
+ OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
goto exit;
}
OC_LOG(INFO, TAG, PCF("===============No presence change"));
goto exit;
}
-
if(maxAge == 0)
{
OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
if(!cbNode->presence)
{
cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
-
if(!(cbNode->presence))
{
OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
// This is the multicast case
OCMulticastNode* mcNode = NULL;
- mcNode = GetMCPresenceNode((const unsigned char *)fullUri);
+ mcNode = GetMCPresenceNode(fullUri);
if(mcNode != NULL)
{
if(mcNode->nonce == response.sequenceNumber)
{
- OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
+ OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
goto exit;
}
mcNode->nonce = response.sequenceNumber;
}
else
{
- uint32_t uriLen = strlen((char*)fullUri);
- unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
+ uint32_t uriLen = strlen(fullUri);
+ char* uri = (char *) OCMalloc(uriLen + 1);
if(uri)
{
memcpy(uri, fullUri, (uriLen + 1));
}
else
{
- OC_LOG(INFO, TAG,
- PCF("===============No Memory for URI to store in the presence node"));
+ OC_LOG(ERROR, TAG,
+ PCF("No Memory for URI to store in the presence node"));
result = OC_STACK_NO_MEMORY;
goto exit;
}
- result = AddMCPresenceNode(&mcNode, (unsigned char*) uri, response.sequenceNumber);
+ result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
if(result == OC_STACK_NO_MEMORY)
{
- OC_LOG(INFO, TAG,
- PCF("===============No Memory for Multicast Presence Node"));
+ OC_LOG(ERROR, TAG,
+ PCF("No Memory for Multicast Presence Node"));
result = OC_STACK_NO_MEMORY;
OCFree(uri);
goto exit;
{
OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
- OCStackApplicationResult appResult = OC_STACK_DELETE_TRANSACTION;
-
if(NULL == endPoint)
{
OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
return;
}
- ClientCB *cbNode = GetClientCB((CAToken_t *)&(responseInfo->info.token), NULL, NULL);
+ ClientCB *cbNode = GetClientCB(&(responseInfo->info.token), NULL, NULL);
if (cbNode)
{
}
response.result = CAToOCStackResult(responseInfo->result);
- response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
+ response.resJSONPayload = responseInfo->info.payload;
response.numRcvdVendorSpecificHeaderOptions = 0;
if(responseInfo->info.options && responseInfo->info.numOptions > 0)
{
&(responseInfo->info.options[i]), sizeof(OCHeaderOption));
}
}
- appResult = cbNode->callBack(cbNode->context,
- cbNode->handle, &response);
- if (appResult == OC_STACK_DELETE_TRANSACTION)
+ if (cbNode->callBack(cbNode->context,cbNode->handle, &response)
+ == OC_STACK_DELETE_TRANSACTION)
{
FindAndDeleteClientCB(cbNode);
}
OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
- char * newUri = (char *)endPoint->resourceUri;
- unsigned char * query = NULL;
+ char * newUri = NULL;
+ char * query = NULL;
getQueryFromUri(endPoint->resourceUri, &query, &newUri);
OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
//copy request payload
if (requestInfo->info.payload)
{
- serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
+ size_t payloadLen = strlen(requestInfo->info.payload);
+ serverRequest.reqTotalSize = payloadLen + 1;
memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
- strlen(requestInfo->info.payload));
- serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
+ payloadLen);
}
else
{
serverRequest.reqTotalSize = 1;
+ serverRequest.reqJSONPayload[0] = '\0';
}
switch (requestInfo->method)
OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", CA_MAX_TOKEN_LEN);
OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token, CA_MAX_TOKEN_LEN);
- serverRequest.requestToken = (CAToken_t)OCCalloc(1, CA_MAX_TOKEN_LEN+1);
+ serverRequest.requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
// Module Name
if (!serverRequest.requestToken)
{
OC_LOG(ERROR, TAG, PCF("Error adding server request"));
return result;
}
- VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
+
+ if(!request)
+ {
+ OC_LOG(ERROR, TAG, PCF("Out of Memory"));
+ return OC_STACK_NO_MEMORY;
+ }
if(!protocolRequest->reqMorePacket)
{
}
else
{
- OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
+ OC_LOG(INFO, TAG,
+ PCF("This is either a repeated Server Request or blocked Server Request"));
}
if(request->requestComplete)
return result;
}
-int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
+int ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
{
size_t index = 0;
- unsigned char *itr, *coap;
+ char *itr, *coap;
uint8_t dotCount = 0;
ipAddr[index] = 0;
*port = 0;
/* search for scheme */
itr = ipAddrStr;
- if (!isdigit((unsigned char) *ipAddrStr))
+ if (!isdigit((char) *ipAddrStr))
{
- coap = (unsigned char *) OC_COAP_SCHEME;
+ coap = OC_COAP_SCHEME;
while (*coap && tolower(*itr) == *coap)
{
coap++;
ipAddrStr = itr;
while (*ipAddrStr) {
- if (isdigit((unsigned char) *ipAddrStr))
+ if (isdigit(*ipAddrStr))
{
ipAddr[index] *= 10;
ipAddr[index] += *ipAddrStr - '0';
}
- else if ((unsigned char) *ipAddrStr == '.')
+ else if (*ipAddrStr == '.')
{
index++;
dotCount++;
{
ipAddrStr++;
while (*ipAddrStr){
- if (isdigit((unsigned char) *ipAddrStr))
+ if (isdigit(*ipAddrStr))
{
*port *= 10;
*port += *ipAddrStr - '0';
}
- if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
- && dotCount == 3)
+ if (dotCount == 3)
{
return 1;
}
static void deleteResourceType(OCResourceType *resourceType);
static void deleteResourceInterface(OCResourceInterface *resourceInterface);
static void deleteResourceElements(OCResource *resource);
-static int deleteResource(OCResource *resource);
+static OCStackResult deleteResource(OCResource *resource);
static void deleteAllResources();
static void incrementSequenceNumber(OCResource * resPtr);
static OCStackResult verifyUriQueryLength(const char * inputUri,
uint16_t uriLen);
static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
-OCStackResult getResourceType(const char * query, unsigned char** resourceType);
+OCStackResult getResourceType(const char * query, char** resourceType);
static CAResult_t OCSelectNetwork();
//-----------------------------------------------------------------------------
* OC_STACK_INVALID_METHOD - invalid resource method
* OC_STACK_INVALID_URI - invalid required or reference URI
*
- * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
+ * Note: when using multicast, the required URI should not contain IP address.
* Instead, it just contains the URI to the resource such as "/oc/core".
*/
OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
{
OCStackResult result = OC_STACK_ERROR;
ClientCB *clientCB = NULL;
- unsigned char * requestUri = NULL;
- unsigned char * resourceType = NULL;
- unsigned char * query = NULL;
+ char * requestUri = NULL;
+ char * resourceType = NULL;
+ char * query = NULL;
char * newUri = (char *)requiredUri;
(void) referenceUri;
CARemoteEndpoint_t* endpoint = NULL;
CAResult_t caResult;
CAToken_t token = NULL;
- CAInfo_t requestData;
- CARequestInfo_t requestInfo;
- CAGroupEndpoint_t grpEnd = {0};
OCDoHandle resHandle = NULL;
+ CAInfo_t requestData ={};
+ CARequestInfo_t requestInfo ={};
+ CAGroupEndpoint_t grpEnd = {};
// To track if memory is allocated for additional header options
- uint8_t hdrOptionMemAlloc = 0;
OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
}
#endif // WITH_PRESENCE
- requestUri = (unsigned char *) OCMalloc(uriLen + 1);
+ requestUri = (char *) OCMalloc(uriLen + 1);
if(requestUri)
{
memcpy(requestUri, newUri, (uriLen + 1));
goto exit;
}
- memset(&requestData, 0, sizeof(CAInfo_t));
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
switch (method)
{
case OC_REST_GET:
{
goto exit;
}
- hdrOptionMemAlloc = 1;
requestData.numOptions = numOptions + 1;
}
else
}
CADestroyRemoteEndpoint(endpoint);
OCFree(grpEnd.resourceUri);
-
- if (hdrOptionMemAlloc)
+ if (requestData.options && requestData.numOptions > 0)
{
- OCFree(requestData.options);
+ if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
+ {
+ OCFree(requestData.options);
+ }
}
return result;
}
*/
OCStackResult ret = OC_STACK_OK;
CARemoteEndpoint_t* endpoint = NULL;
- CAResult_t caResult;
- CAInfo_t requestData;
- CARequestInfo_t requestInfo;
- // Track if memory is allocated for additional header options
- uint8_t hdrOptionMemAlloc = 0;
+ CAResult_t caResult= CA_STATUS_OK;
+ CAInfo_t requestData = {};
+ CARequestInfo_t requestInfo = {};
- if(!handle) {
+ if(!handle)
+ {
return OC_STACK_INVALID_PARAM;
}
ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
- if(clientCB) {
+ if(clientCB)
+ {
switch (clientCB->method)
{
case OC_REST_OBSERVE:
{
return OC_STACK_ERROR;
}
- hdrOptionMemAlloc = 1;
requestData.numOptions = numOptions + 1;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
requestInfo.method = CA_GET;
requestInfo.info = requestData;
// send request
}
}
CADestroyRemoteEndpoint(endpoint);
- if (hdrOptionMemAlloc)
+ if (requestData.numOptions > 0)
{
OCFree(requestData.options);
}
OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
ClientCB* cbNode = NULL;
- OCDevAddr dst;
- OCClientResponse clientResponse;
+ OCDevAddr dst = {};
+ OCClientResponse clientResponse ={};
OCResponse * response = NULL;
OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
- LL_FOREACH(cbList, cbNode) {
+ LL_FOREACH(cbList, cbNode)
+ {
if(OC_REST_PRESENCE == cbNode->method)
{
if(cbNode->presence)
{
uint32_t now = GetTime(0);
- OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
+ OC_LOG_V(DEBUG, TAG, "this TTL level %d",
cbNode->presence->TTLlevel);
- OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
+ OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
goto exit;
}
- if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
- OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
+ if(cbNode->presence->TTLlevel < PresenceTimeOutSize)
+ {
+ OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
}
if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
{
- OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
+ OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
{
OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
// Increment the TTLLevel (going to a next state), so we don't keep
// sending presence notification to client.
cbNode->presence->TTLlevel++;
- OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
+ OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
cbNode->presence->TTLlevel);
}
else
if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
{
- CAResult_t caResult;
+ CAResult_t caResult = CA_STATUS_OK;
CARemoteEndpoint_t* endpoint = NULL;
- CAInfo_t requestData;
- CARequestInfo_t requestInfo;
+ CAInfo_t requestData ={};
+ CARequestInfo_t requestInfo = {};
- OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
+ OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
//TODO-CA : Why CA_WIFI alone?
caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
goto exit;
}
- memset(&requestData, 0, sizeof(CAInfo_t));
requestData.type = CA_MSG_NONCONFIRM;
requestData.token = cbNode->token;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
requestInfo.method = CA_GET;
requestInfo.info = requestData;
}
cbNode->presence->TTLlevel++;
- OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
+ OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
cbNode->presence->TTLlevel);
}
}
presenceState = OC_PRESENCE_INITIALIZED;
CAAddress_t addressInfo;
- strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
+ strncpy(addressInfo.IP.ipAddress, OC_MULTICAST_IP, CA_IPADDR_SIZE);
addressInfo.IP.port = 5683;
//TODO make sure there is no memory leak here since another copy
{
OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
- if(myStackMode == OC_CLIENT)
+ if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER)
+ {
+ return SaveDeviceInfo(deviceInfo);
+ }
+ else
{
return OC_STACK_ERROR;
}
-
- return SaveDeviceInfo(deviceInfo);
}
/**
OCResource *pointer = NULL;
char *str = NULL;
- size_t size;
+ size_t size = 0;
OCStackResult result = OC_STACK_ERROR;
OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
if(myStackMode == OC_CLIENT)
{
- return result;
+ return OC_STACK_INVALID_PARAM;
}
// Validate parameters
- if(!uri || (strlen(uri) == 0))
+ if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
{
OC_LOG(ERROR, TAG, PCF("URI is invalid"));
return OC_STACK_INVALID_URI;
return OC_STACK_INVALID_PARAM;
}
- if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
+ if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
+ {
resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
}
uint8_t resourceProperties)
{
char *str = NULL;
- size_t size;
+ size_t size = 0;
+
+ if(!host)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
OCStackResult result = OC_STACK_ERROR;
result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
str = (char *) OCMalloc(size);
if (!str)
{
- return OC_STACK_ERROR;
+ return OC_STACK_NO_MEMORY;
}
strncpy(str, host, size);
((OCResource *) *handle)->host = str;
OCStackResult OCBindResource(
OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
{
- OCResource *resource;
- uint8_t i;
+ OCResource *resource = NULL;
+ uint8_t i = 0;
OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
{
resource->rsrcResources[i] = (OCResource *) resourceHandle;
OC_LOG(INFO, TAG, PCF("resource bound"));
+
+ #ifdef WITH_PRESENCE
+ if(presenceResource.handle)
+ {
+ ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
+ SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
+ }
+ #endif
return OC_STACK_OK;
- }
- }
- #ifdef WITH_PRESENCE
- if(presenceResource.handle)
- {
- ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
- SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
+ }
}
- #endif
// Unable to add resourceHandle, so return error
return OC_STACK_ERROR;
* OC_STACK_INVALID_PARAM - invalid collectionHandle
*/
OCStackResult OCUnBindResource(
- OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
- OCResource *resource;
- uint8_t i;
+ OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
+{
+ OCResource *resource = NULL;
+ uint8_t i = 0;
OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
// Container cannot contain itself
- if (collectionHandle == resourceHandle) {
+ if (collectionHandle == resourceHandle)
+ {
OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
return OC_STACK_INVALID_PARAM;
}
// Use the handle to find the resource in the resource linked list
resource = findResource((OCResource *) collectionHandle);
- if (!resource) {
+ if (!resource)
+ {
OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
return OC_STACK_INVALID_PARAM;
}
// Look for an open slot to add add the child resource.
// If found, add it and return success
- for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
- if (resourceHandle == resource->rsrcResources[i]) {
+ for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+ {
+ if (resourceHandle == resource->rsrcResources[i])
+ {
resource->rsrcResources[i] = (OCResource *) NULL;
OC_LOG(INFO, TAG, PCF("resource unbound"));
SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
}
#endif
-
return OC_STACK_OK;
}
}
{
OCResourceType *pointer = NULL;
char *str = NULL;
- size_t size;
+ size_t size = 0;
OCStackResult result = OC_STACK_ERROR;
OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
{
OCResourceInterface *pointer = NULL;
char *str = NULL;
- size_t size;
+ size_t size = 0;
OCStackResult result = OC_STACK_ERROR;
OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
* OC_STACK_ERROR - stack process error
*/
OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
- const char *resourceTypeName) {
+ const char *resourceTypeName)
+{
OCStackResult result = OC_STACK_ERROR;
- OCResource *resource;
+ OCResource *resource = NULL;
// Make sure resource exists
resource = findResource((OCResource *) handle);
- if (!resource) {
+ if (!resource)
+ {
OC_LOG(ERROR, TAG, PCF("Resource not found"));
return OC_STACK_ERROR;
}
*/
OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
- const char *resourceInterfaceName) {
+ const char *resourceInterfaceName)
+{
OCStackResult result = OC_STACK_ERROR;
- OCResource *resource;
+ OCResource *resource = NULL;
// Make sure resource exists
resource = findResource((OCResource *) handle);
- if (!resource) {
+ if (!resource)
+ {
OC_LOG(ERROR, TAG, PCF("Resource not found"));
return OC_STACK_ERROR;
}
* OC_STACK_ERROR - stack process error
*/
-OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
+OCStackResult OCGetNumberOfResources(uint8_t *numResources)
+{
OCResource *pointer = headResource;
OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
*numResources = 0;
- while (pointer) {
+ while (pointer)
+ {
*numResources = *numResources + 1;
pointer = pointer->next;
}
* Resource handle - if found
* NULL - if not found
*/
-OCResourceHandle OCGetResourceHandle(uint8_t index) {
+OCResourceHandle OCGetResourceHandle(uint8_t index)
+{
OCResource *pointer = headResource;
- uint8_t i = 0;
OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
// Iterate through the list
- while ((i < index) && pointer) {
- i++;
+ for( uint8_t i = 0; i < index && pointer; ++i)
+ {
pointer = pointer->next;
}
return (OCResourceHandle) pointer;
* OC_STACK_NO_RESOURCE - resource not found
* OC_STACK_INVALID_PARAM - invalid param
*/
-OCStackResult OCDeleteResource(OCResourceHandle handle) {
+OCStackResult OCDeleteResource(OCResourceHandle handle)
+{
OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
- if (!handle) {
+ if (!handle)
+ {
OC_LOG(ERROR, TAG, PCF("Invalid param"));
return OC_STACK_INVALID_PARAM;
}
OCResource *resource = findResource((OCResource *) handle);
- if (resource == NULL) {
+ if (resource == NULL)
+ {
OC_LOG(ERROR, TAG, PCF("Resource not found"));
return OC_STACK_NO_RESOURCE;
}
- if (deleteResource((OCResource *) handle) == 0) {
+ if (deleteResource((OCResource *) handle) != OC_STACK_OK)
+ {
OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
return OC_STACK_ERROR;
}
* URI string - if resource found
* NULL - resource not found
*/
-const char *OCGetResourceUri(OCResourceHandle handle) {
- OCResource *resource;
+const char *OCGetResourceUri(OCResourceHandle handle)
+{
+ OCResource *resource = NULL;
OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
resource = findResource((OCResource *) handle);
- if (resource) {
+ if (resource)
+ {
return resource->uri;
}
return (const char *) NULL;
*
* @param handle - handle of resource
* @return
- * property bitmap - if resource found
- * NULL - resource not found
+ * OCResourceProperty Bitmask
+ * -1 if resource is not found
*/
-uint8_t OCGetResourceProperties(OCResourceHandle handle) {
- OCResource *resource;
+OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
+{
+ OCResource *resource = NULL;
OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
resource = findResource((OCResource *) handle);
- if (resource) {
+ if (resource)
+ {
return resource->resourceProperties;
}
- return 0;
+ return (OCResourceProperty)-1;
}
/**
* OC_STACK_ERROR - stack process error
*/
OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
- uint8_t *numResourceTypes) {
- OCResource *resource;
- OCResourceType *pointer;
+ uint8_t *numResourceTypes)
+{
+ OCResource *resource = NULL;
+ OCResourceType *pointer = NULL;
OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
*numResourceTypes = 0;
resource = findResource((OCResource *) handle);
- if (resource) {
+ if (resource)
+ {
pointer = resource->rsrcType;
- while (pointer) {
+ while (pointer)
+ {
*numResourceTypes = *numResourceTypes + 1;
pointer = pointer->next;
}
* resource type name - if resource found
* NULL - resource not found
*/
-const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
- OCResourceType *resourceType;
+const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
+{
+ OCResourceType *resourceType = NULL;
OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
resourceType = findResourceTypeAtIndex(handle, index);
- if (resourceType) {
+ if (resourceType)
+ {
return resourceType->resourcetypename;
}
return (const char *) NULL;
* OC_STACK_ERROR - stack process error
*/
OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
- uint8_t *numResourceInterfaces) {
- OCResourceInterface *pointer;
- OCResource *resource;
+ uint8_t *numResourceInterfaces)
+{
+ OCResourceInterface *pointer = NULL;
+ OCResource *resource = NULL;
OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
*numResourceInterfaces = 0;
resource = findResource((OCResource *) handle);
- if (resource) {
+ if (resource)
+ {
pointer = resource->rsrcInterface;
- while (pointer) {
+ while (pointer)
+ {
*numResourceInterfaces = *numResourceInterfaces + 1;
pointer = pointer->next;
}
* resource interface name - if resource found
* NULL - resource not found
*/
-const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
- OCResourceInterface *resourceInterface;
+const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
+{
+ OCResourceInterface *resourceInterface = NULL;
OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
resourceInterface = findResourceInterfaceAtIndex(handle, index);
- if (resourceInterface) {
+ if (resourceInterface)
+ {
return resourceInterface->name;
}
return (const char *) NULL;
* NULL - resource not found
*/
OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
- uint8_t index) {
- OCResource *resource;
+ uint8_t index)
+{
+ OCResource *resource = NULL;
OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
- if (index >= MAX_CONTAINED_RESOURCES) {
+ if (index >= MAX_CONTAINED_RESOURCES)
+ {
return NULL;
}
resource = findResource((OCResource *) collectionHandle);
- if (!resource) {
+ if (!resource)
+ {
return NULL;
}
* OC_STACK_ERROR - stack process error
*/
OCStackResult OCBindResourceHandler(OCResourceHandle handle,
- OCEntityHandler entityHandler) {
- OCResource *resource;
+ OCEntityHandler entityHandler)
+{
+ OCResource *resource = NULL;
OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
// Validate parameters
VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
- //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
// Use the handle to find the resource in the resource linked list
resource = findResource((OCResource *)handle);
- if (!resource) {
+ if (!resource)
+ {
OC_LOG(ERROR, TAG, PCF("Resource not found"));
return OC_STACK_ERROR;
}
* entity handler - if resource found
* NULL - resource not found
*/
-OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
- OCResource *resource;
+OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
+{
+ OCResource *resource = NULL;
OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
// Use the handle to find the resource in the resource linked list
resource = findResource((OCResource *)handle);
- if (!resource) {
+ if (!resource)
+ {
OC_LOG(ERROR, TAG, PCF("Resource not found"));
return NULL;
}
* OC_STACK_NO_RESOURCE - invalid resource handle
* OC_STACK_NO_OBSERVERS - no more observers intrested in resource
*/
-OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
+OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
+{
OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
OCResource *resPtr = NULL;
- OCStackResult result;
+ OCStackResult result = OC_STACK_ERROR;
OCMethod method = OC_REST_NOMETHOD;
uint32_t maxAge = 0;
OCNotifyListOfObservers (OCResourceHandle handle,
OCObservationId *obsIdList,
uint8_t numberOfIds,
- unsigned char *notificationJSONPayload,
+ const char *notificationJSONPayload,
OCQualityOfService qos)
{
OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
OCResourceProperty resourceProperties, uint8_t enable)
{
if (resourceProperties
- > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
+ > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
+ {
OC_LOG(ERROR, TAG, PCF("Invalid property"));
return OC_STACK_INVALID_PARAM;
}
/**
* Initialize resource data structures, variables, etc.
*/
-OCStackResult initResources() {
+OCStackResult initResources()
+{
OCStackResult result = OC_STACK_OK;
// Init application resource vars
headResource = NULL;
*/
void insertResource(OCResource *resource)
{
- if (!headResource)
- {
- // First resource. Head and tail are the same.
+ OCResource *pointer = NULL;
+
+ if (!headResource) {
headResource = resource;
tailResource = resource;
}
void deleteAllResources()
{
OCResource *pointer = headResource;
- OCResource *temp;
+ OCResource *temp = NULL;
while (pointer)
{
*
* @param resource - resource to be deleted
* @return
- * 0 - error
- * 1 - success
+ * OC_STACK_ERROR - error
+ * OC_STACK_OK - success
*/
-int deleteResource(OCResource *resource)
+OCStackResult deleteResource(OCResource *resource)
{
OCResource *prev = NULL;
- OCResource *temp;
+ OCResource *temp = NULL;
temp = headResource;
while (temp)
}
}
#endif
-
// Only resource in list.
if (temp == headResource && temp == tailResource)
{
deleteResourceElements(temp);
OCFree(temp);
- return 1;
+ return OC_STACK_OK;
}
else
{
}
}
- return 0;
+ return OC_STACK_ERROR;
}
/**
*/
void deleteResourceElements(OCResource *resource)
{
- if (!resource) {
+ if (!resource)
+ {
return;
}
void deleteResourceType(OCResourceType *resourceType)
{
OCResourceType *pointer = resourceType;
- OCResourceType *next;
+ OCResourceType *next = NULL;
while (pointer)
{
*
* @param resourceInterface - specified resource interface
*/
-void deleteResourceInterface(OCResourceInterface *resourceInterface) {
+void deleteResourceInterface(OCResourceInterface *resourceInterface)
+{
OCResourceInterface *pointer = resourceInterface;
- OCResourceInterface *next;
+ OCResourceInterface *next = NULL;
while (pointer)
{
* @param resource - resource where resource type is to be inserted
* @param resourceType - resource type to be inserted
*/
-void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
- OCResourceType *pointer;
+void insertResourceType(OCResource *resource, OCResourceType *resourceType)
+{
+ OCResourceType *pointer = NULL;
if (resource && !resource->rsrcType)
{
{
pointer = resourceType;
}
- while (pointer->next) {
+ while (pointer->next)
+ {
pointer = pointer->next;
}
pointer->next = resourceType;
* resourcetype - if found
* NULL - not found
*/
-OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
- OCResource *resource;
- OCResourceType *pointer;
- uint8_t i;
+OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
+{
+ OCResource *resource = NULL;
+ OCResourceType *pointer = NULL;
// Find the specified resource
resource = findResource((OCResource *) handle);
// Iterate through the list
pointer = resource->rsrcType;
- i = 0;
- while ((i < index) && pointer)
+ for(uint8_t i = 0; i< index && pointer; ++i)
{
- i++;
pointer = pointer->next;
}
return pointer;
void insertResourceInterface(OCResource *resource,
OCResourceInterface *resourceInterface)
{
- OCResourceInterface *pointer;
-
+ OCResourceInterface *pointer = NULL;
if (!resource->rsrcInterface)
{
resource->rsrcInterface = resourceInterface;
* NULL - not found
*/
OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
- uint8_t index) {
- OCResource *resource;
- OCResourceInterface *pointer;
- uint8_t i = 0;
+ uint8_t index)
+{
+ OCResource *resource = NULL;
+ OCResourceInterface *pointer = NULL;
// Find the specified resource
resource = findResource((OCResource *) handle);
- if (!resource) {
+ if (!resource)
+ {
return NULL;
}
// Make sure a resource has a resourceinterface
- if (!resource->rsrcInterface) {
+ if (!resource->rsrcInterface)
+ {
return NULL;
}
// Iterate through the list
pointer = resource->rsrcInterface;
- while ((i < index) && pointer) {
- i++;
+ for (uint8_t i = 0; i < index && pointer; ++i)
+ {
pointer = pointer->next;
}
return pointer;
}
/**
- * Retrieves a resource type based upon a query ontains only just one
+ * Retrieves a resource type based upon a query contains only just one
* resource attribute (and that has to be of type "rt").
*
* @remark This API malloc's memory for the resource type. Do not malloc resourceType
* before passing in.
*
- * @param query - The quert part of the URI
+ * @param query - The query part of the URI
* @param resourceType - The resource type to be populated; pass by reference.
*
* @return
* OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
* OC_STACK_OK - Success
*/
-OCStackResult getResourceType(const char * query, unsigned char** resourceType)
+OCStackResult getResourceType(const char * query, char** resourceType)
{
if(!query)
{
if(strncmp(query, "rt=", 3) == 0)
{
- *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
+ *resourceType = (char *) OCMalloc(strlen(query)-3 + 1);
if(!*resourceType)
{
result = OC_STACK_NO_MEMORY;
return result;
}
-OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
+OCStackResult getQueryFromUri(const char * uri, char** query, char ** newURI)
{
if(!uri)
{
goto exit;
}
strcpy(tempURI, uri);
- char* strTokPtr;
- leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
+ char* strTokPtr = NULL;
+ leftToken = strtok_r(tempURI, "?", &strTokPtr);
//TODO-CA: This could be simplified. Clean up required.
while(leftToken != NULL)
{
if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
{
- *query = (unsigned char *) OCMalloc(strlen(leftToken) + 1);
+ *query = (char *) OCMalloc(strlen(leftToken) + 1);
if(!*query)
{
OCFree(tempURI);
goto exit;
}
- strcpy((char *)*query, ((const char *)&leftToken[0]));
+ strcpy(*query, &leftToken[0]);
break;
}
leftToken = strtok_r(NULL, "?", &strTokPtr);
{
static bool generated = false;
static ServerID sid;
-
if(generated)
{
return sid;
// This will change as the representation gets switched
// to another value
static char buffer[11];
- int n = sprintf(buffer, "%u", OCGetServerInstanceID());
- if (n < 0)
+
+ if (snprintf(buffer, sizeof(buffer),"%u", OCGetServerInstanceID()) < 0)
{
buffer[0]='\0';
}
int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
uint8_t *c, uint8_t *d )
{
- if ( !ipAddr || !a || !b || !c || !d ) {
- OC_LOG(FATAL, TAG, "Invalid argument");
+ if ( !ipAddr || !a || !b || !c || !d )
+ {
+ OC_LOG(FATAL, TAG, PCF("Invalid argument"));
return OC_STACK_INVALID_PARAM;
}
/// Retrieve the IPv4 address embedded inside OCDev address data structure
int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
{
- if ( !ipAddr || !port ) {
- OC_LOG(FATAL, TAG, "Invalid argument");
+ if ( !ipAddr || !port )
+ {
+ OC_LOG(FATAL, TAG, PCF("Invalid argument"));
return OC_STACK_INVALID_PARAM;
}
OCResource *collResource;
struct aggregatehandleinfo *next;
-} ClientRequstInfo;
+} ClientRequestInfo;
-// unsigned int nHandleIdx = 0;
-// ClientRequstInfo g_AggregateResponseHandle[10];
+static ClientRequestInfo *clientRequestList = NULL;
-ClientRequstInfo *clientRequstList = NULL;
-
-void AddClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* add)
+void AddClientRequestInfo(ClientRequestInfo **head, ClientRequestInfo* add)
{
- ClientRequstInfo *tmp = NULL;
+ ClientRequestInfo *tmp = NULL;
if (*head != NULL)
{
}
}
-ClientRequstInfo* GetClientRequestInfo(ClientRequstInfo *head, OCDoHandle handle)
+ClientRequestInfo* GetClientRequestInfo(ClientRequestInfo *head, OCDoHandle handle)
{
- ClientRequstInfo *tmp = NULL;
+ ClientRequestInfo *tmp = NULL;
tmp = head;
{
while (tmp)
{
-// printf("%p :: %p\n", tmp->required, handle);
if (tmp->required == handle)
{
break;
return NULL;
}
-void RemoveClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* del)
+void RemoveClientRequestInfo(ClientRequestInfo **head, ClientRequestInfo* del)
{
- ClientRequstInfo *tmp = NULL;
+ ClientRequestInfo *tmp = NULL;
if (*head == del)
{
void DeleteCapability(OCCapability *del)
{
- free(del->capability);
+ OCFree(del->capability);
del->capability = NULL;
- free(del->status);
+ OCFree(del->status);
del->status = NULL;
}
OCStackResult result = OC_STACK_OK;
size_t length = 0;
+ if(strlen(request) <= strlen(OIC_ACTION_PREFIX))
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
char* pRequest = (char *)request + strlen(OIC_ACTION_PREFIX);
- char* iterToken, *iterTokenPtr;
+ char* iterToken = NULL;
+ char* iterTokenPtr = NULL;
iterToken = (char *) strtok_r(pRequest, ":", &iterTokenPtr);
length = strlen(iterToken) + 1;
OCStackResult result = OC_STACK_OK;
char *iterToken = NULL, *iterTokenPtr = NULL;
- char *descIterToken = NULL, *descIterTokenPtr = NULL;
- char *attrIterToken = NULL, *attrIterTokenPtr = NULL;
- char *desc = NULL, *attr = NULL;
- char *key = NULL, *value = NULL;
+ char *descIterToken = NULL;
+ char *descIterTokenPtr = NULL;
+ char *attrIterToken = NULL;
+ char *attrIterTokenPtr = NULL;
+ char *desc = NULL;
+ char *attr = NULL;
+ char *key = NULL;
+ char *value = NULL;
OCAction *action = NULL;
OCCapability *capa = NULL;
VARIFY_PARAM_NULL(attrIterToken, result, exit)
strncpy(value, attrIterToken, strlen(attrIterToken) + 1);
- if(strcmp(key, "uri") == 0)
+ if(strncmp(key, "uri", sizeof("uri") - 1) == 0)
{
OC_LOG(INFO, TAG, PCF("Build OCAction Instance."));
OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
{
char temp[1024] = { 0 };
- int remaining = 1023;
+ uint16_t remaining = sizeof(temp) - 1;
- // OCActionSet *as = resource->actionsetHead;
- // while(as != NULL)
- // {
- // printf("\n\n\nAction Set Name :: %s\n", actionset->actionsetName);
OCAction *action = actionset->head;
if (remaining >= strlen(actionset->actionsetName) + 1)
{
- strcat(temp, actionset->actionsetName);
+ strncat(temp, actionset->actionsetName, sizeof(temp));
remaining -= strlen(actionset->actionsetName);
strcat(temp, "*");
remaining--;
while (action != NULL)
{
- printf("\tURI :: %s\n", action->resourceUri);
+ OC_LOG_V(INFO, TAG, "\tURI :: %s\n", action->resourceUri);
strcat(temp, "uri=");
remaining -= strlen("uri=");
strcat(temp, action->resourceUri);
OCCapability *capas = action->head;
while (capas != NULL)
{
- printf("\t\t%s = %s\n", capas->capability, capas->status);
+ OC_LOG_V(INFO, TAG, "\t\t%s = %s\n", capas->capability, capas->status);
strcat(temp, capas->capability);
remaining -= strlen(capas->capability);
strcat(temp, "=");
remaining--;
}
}
- // as = as->next;
- // }
*desc = (char *) OCMalloc(1024 - remaining);
+ if(!*desc)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
strcpy(*desc, temp);
- // printf("\t\tPlain Text = %s(%i)\n", *desc, 1024 - remaining);
return OC_STACK_OK;
}
OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
OCClientResponse* clientResponse)
{
- printf("\n\n\tcallback is called\n\n");
+ OC_LOG(INFO, TAG, PCF("\n\n\tcallback is called\n\n"));
- ClientRequstInfo *info = GetClientRequestInfo(clientRequstList, handle);
+ ClientRequestInfo *info = GetClientRequestInfo(clientRequestList, handle);
if (info)
{
- int idx;
+ uint32_t idx = 0;
- unsigned char *responseJson;
- responseJson = (unsigned char *) OCMalloc(
- (unsigned int) (strlen((char *) clientResponse->resJSONPayload) + 1));
+ char *responseJson = (char *) OCMalloc(
+ (unsigned int) (strlen( clientResponse->resJSONPayload) + 1));
// We need the body of response.
// Copy the body from the response
- strcpy((char *) responseJson, ((char *) clientResponse->resJSONPayload
- + OC_JSON_PREFIX_LEN));
+ strncpy((char *) responseJson, (clientResponse->resJSONPayload
+ + OC_JSON_PREFIX_LEN), strlen(clientResponse->resJSONPayload) + 1);
idx = strlen((char *) responseJson) - OC_JSON_SUFFIX_LEN;
// And insert NULL at the end of body.
(responseJson[idx]) = 0;
- OCEntityHandlerResponse response = { 0 };
+ OCEntityHandlerResponse response = { };
response.ehResult = OC_EH_OK;
response.payload = responseJson;
response.payloadSize = (unsigned int) strlen((char *) responseJson) + 1;
OCDoResponse(&response);
- RemoveClientRequestInfo(&clientRequstList, info);
+ RemoveClientRequestInfo(&clientRequestList, info);
OCFree(responseJson);
}
- // g_AggregateResponseHandle
-
return OC_STACK_KEEP_TRANSACTION;
}
void ActionSetCD(void *context)
{
- // printf("\n\t\tCD is called\n");
-
- // free( context );
}
-OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr, uint16_t *remaining)
+OCStackResult BuildActionJSON(OCAction* action, char* bufferPtr, uint16_t *remaining)
{
OCStackResult ret = OC_STACK_ERROR;
- cJSON *json;
- cJSON *body;
+ cJSON *json = NULL;
+ cJSON *body = NULL;
- char *jsonStr;
- uint16_t jsonLen;
+ char *jsonStr = NULL;
+ uint16_t jsonLen = 0;
OC_LOG(INFO, TAG, PCF("Entering BuildActionJSON"));
json = cJSON_CreateObject();
}
cJSON_Delete(json);
- free(jsonStr);
+ OCFree(jsonStr);
return ret;
}
-unsigned int GetNumOfTargetResource(OCAction *actionset)
+uint32_t GetNumOfTargetResource(OCAction *actionset)
{
- int numOfREsource = 0;
+ uint32_t numOfResource = 0;
OCAction *pointerAction = actionset;
while (pointerAction != NULL)
{
- numOfREsource++;
+ numOfResource++;
pointerAction = pointerAction->next;
}
- return numOfREsource;
+ return numOfResource;
}
-OCStackResult SendAction(OCDoHandle *handle, const char *targetUri, const unsigned char *action)
+OCStackResult SendAction(OCDoHandle *handle, const char *targetUri, const char *action)
{
- OCCallbackData cbdata = { 0 };
+ OCCallbackData cbdata = { };
cbdata.cb = &ActionSetCB;
cbdata.cd = &ActionSetCD;
cbdata.context = (void *) 0x99;
OCStackResult stackRet = OC_STACK_ERROR;
OC_LOG(INFO, TAG, PCF("Group Action is requested."));
- // if (stackRet == OC_STACK_OK)
- {
- char *doWhat = NULL;
- char *details = NULL;
-
- size_t bufferLength = 0;
- unsigned char buffer[MAX_RESPONSE_LENGTH] = { 0 };
- unsigned char *bufferPtr = NULL;
+ char *doWhat = NULL;
+ char *details = NULL;
- bufferPtr = buffer;
+ size_t bufferLength = 0;
+ char buffer[MAX_RESPONSE_LENGTH] = { 0 };
+ char *bufferPtr = NULL;
- OCResource * collResource = (OCResource *) ehRequest->resource;
+ bufferPtr = buffer;
- char *jsonResponse;
+ OCResource * collResource = (OCResource *) ehRequest->resource;
- ExtractKeyValueFromRequest((char *)ehRequest->reqJSONPayload, &doWhat, &details);
+ char *jsonResponse;
- cJSON *json;
- cJSON *format;
+ ExtractKeyValueFromRequest((char *)ehRequest->reqJSONPayload, &doWhat, &details);
+ cJSON *json;
+ cJSON *format;
- if (method == OC_REST_PUT)
- {
- json = cJSON_CreateObject();
- cJSON_AddStringToObject(json, "href", resource->uri);
- cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
- OC_LOG(INFO, TAG, PCF("Group Action[PUT]."));
+ if (method == OC_REST_PUT)
+ {
+ json = cJSON_CreateObject();
+ cJSON_AddStringToObject(json, "href", resource->uri);
+ cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
- if(strcmp(doWhat, "ActionSet") == 0)
- {
- OCActionSet *actionSet;
- BuildActionSetFromString(&actionSet, details);
+ OC_LOG(INFO, TAG, PCF("Group Action[PUT]."));
- if(actionSet != NULL)
- {
- AddActionSet(&resource->actionsetHead, actionSet);
- stackRet = OC_STACK_OK;
- }
- else
- {
- stackRet = OC_STACK_ERROR;
- }
+ if(strcmp(doWhat, "ActionSet") == 0)
+ {
+ OCActionSet *actionSet;
+ BuildActionSetFromString(&actionSet, details);
+ if(actionSet != NULL)
+ {
+ AddActionSet(&resource->actionsetHead, actionSet);
+ stackRet = OC_STACK_OK;
}
- else if (strcmp(doWhat, "DelActionSet") == 0)
+ else
{
- if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
- {
- stackRet = OC_STACK_OK;
- }
- else
- {
- stackRet = OC_STACK_ERROR;
- }
+ stackRet = OC_STACK_ERROR;
}
- jsonResponse = cJSON_Print(json);
- cJSON_Delete(json);
-
- strcat((char *) bufferPtr, jsonResponse);
-
- bufferLength = strlen((const char *) buffer);
- if (bufferLength > 0)
+ }
+ else if (strncmp(doWhat, "DelActionSet", sizeof("DelActionSet")) == 0)
+ {
+ if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
{
- OCEntityHandlerResponse response = { 0 };
- response.ehResult = OC_EH_OK;
- response.payload = buffer;
- response.payloadSize = bufferLength + 1;
- response.persistentBufferFlag = 0;
- response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
- response.resourceHandle = (OCResourceHandle) collResource;
- stackRet = OCDoResponse(&response);
+ stackRet = OC_STACK_OK;
+ }
+ else
+ {
+ stackRet = OC_STACK_ERROR;
}
-
- stackRet = OC_STACK_OK;
}
- if (method == OC_REST_POST)
+ jsonResponse = cJSON_Print(json);
+ cJSON_Delete(json);
+
+ strcat((char *) bufferPtr, jsonResponse);
+
+ bufferLength = strlen((const char *) buffer);
+ if (bufferLength > 0)
{
- OC_LOG(INFO, TAG, PCF("Group Action[POST]."));
+ OCEntityHandlerResponse response = { 0 };
+ response.ehResult = OC_EH_OK;
+ response.payload = buffer;
+ response.payloadSize = bufferLength + 1;
+ response.persistentBufferFlag = 0;
+ response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
+ response.resourceHandle = (OCResourceHandle) collResource;
+ stackRet = OCDoResponse(&response);
+ }
- OCActionSet *actionset = NULL;
+ stackRet = OC_STACK_OK;
+ }
- json = cJSON_CreateObject();
- cJSON_AddStringToObject(json, "href", resource->uri);
+ if (method == OC_REST_POST)
+ {
+ OC_LOG(INFO, TAG, PCF("Group Action[POST]."));
- if (strcmp(doWhat, "DoAction") == 0)
- {
- if (GetActionSet(details, resource->actionsetHead, &actionset) != OC_STACK_OK)
- {
- OC_LOG(INFO, TAG, PCF("ERROR"));
- stackRet = OC_STACK_ERROR;
- }
+ OCActionSet *actionset = NULL;
- if (actionset == NULL)
- {
- OC_LOG(INFO, TAG, PCF("ERROR"));
- stackRet = OC_STACK_ERROR;
- }
- else
- {
+ json = cJSON_CreateObject();
+ cJSON_AddStringToObject(json, "href", resource->uri);
- OCAction *pointerAction = actionset->head;
+ if (strcmp(doWhat, "DoAction") == 0)
+ {
+ if (GetActionSet(details, resource->actionsetHead, &actionset) != OC_STACK_OK)
+ {
+ OC_LOG(INFO, TAG, PCF("ERROR"));
+ stackRet = OC_STACK_ERROR;
+ }
- unsigned int num = GetNumOfTargetResource(pointerAction);
+ if (actionset == NULL)
+ {
+ OC_LOG(INFO, TAG, PCF("ERROR"));
+ stackRet = OC_STACK_ERROR;
+ }
+ else
+ {
- ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
- HandleAggregateResponse;
- ((OCServerRequest *) ehRequest->requestHandle)->numResponses = num + 1;
+ OCAction *pointerAction = actionset->head;
- while (pointerAction != NULL)
- {
- unsigned char actionDesc[MAX_RESPONSE_LENGTH] = { 0 };
- unsigned char* actionDescPtr = actionDesc;
- uint16_t remaining = MAX_RESPONSE_LENGTH;
+ uint32_t num = GetNumOfTargetResource(pointerAction);
- strncpy((char *) actionDescPtr, (const char *) OC_JSON_PREFIX,
- strlen((const char *) OC_JSON_PREFIX) + 1);
- BuildActionJSON(pointerAction, actionDescPtr, &remaining);
- strncat((char *) actionDescPtr, (const char *) OC_JSON_SUFFIX,
- strlen((const char *) OC_JSON_SUFFIX));
+ ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
+ HandleAggregateResponse;
+ ((OCServerRequest *) ehRequest->requestHandle)->numResponses = num + 1;
- ClientRequstInfo *info = (ClientRequstInfo *) OCMalloc(
- sizeof(ClientRequstInfo));
- memset(info, 0, sizeof(ClientRequstInfo));
+ while (pointerAction != NULL)
+ {
+ char actionDesc[MAX_RESPONSE_LENGTH] = { 0 };
+ char* actionDescPtr = actionDesc;
+ uint16_t remaining = MAX_RESPONSE_LENGTH;
- info->collResource = resource;
- info->ehRequest = (OCServerRequest *) ehRequest->requestHandle;
+ strncpy((char *) actionDescPtr, (const char *) OC_JSON_PREFIX,
+ strlen((const char *) OC_JSON_PREFIX) + 1);
+ BuildActionJSON(pointerAction, actionDescPtr, &remaining);
+ strncat((char *) actionDescPtr, (const char *) OC_JSON_SUFFIX,
+ strlen((const char *) OC_JSON_SUFFIX));
- SendAction(&info->required, pointerAction->resourceUri, actionDescPtr);
+ ClientRequestInfo *info = (ClientRequestInfo *) OCMalloc(
+ sizeof(ClientRequestInfo));
+ memset(info, 0, sizeof(ClientRequestInfo));
- AddClientRequestInfo(&clientRequstList, info);
+ info->collResource = resource;
+ info->ehRequest = (OCServerRequest *) ehRequest->requestHandle;
- pointerAction = pointerAction->next;
- }
+ SendAction(&info->required, pointerAction->resourceUri, actionDescPtr);
+ AddClientRequestInfo(&clientRequestList, info);
- stackRet = OC_STACK_OK;
+ pointerAction = pointerAction->next;
}
+
+
+ stackRet = OC_STACK_OK;
}
- else if (strcmp(doWhat, "GetActionSet") == 0)
+ }
+ else if (strcmp(doWhat, "GetActionSet") == 0)
+ {
+ char *plainText = NULL;
+ OCActionSet *actionset = NULL;
+
+ cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
+ GetActionSet(details, resource->actionsetHead, &actionset);
+ if (actionset != NULL)
{
- char *plainText = NULL;
- OCActionSet *actionset = NULL;
+ BuildStringFromActionSet(actionset, &plainText);
- cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
- GetActionSet(details, resource->actionsetHead, &actionset);
- if (actionset != NULL)
+ if (plainText != NULL)
{
- BuildStringFromActionSet(actionset, &plainText);
-
- if (plainText != NULL)
- {
- cJSON_AddStringToObject(format, "ActionSet", plainText);
- }
-
- stackRet = OC_STACK_OK;
+ cJSON_AddStringToObject(format, "ActionSet", plainText);
}
+
+ stackRet = OC_STACK_OK;
}
+ }
- jsonResponse = cJSON_Print(json);
- cJSON_Delete(json);
+ jsonResponse = cJSON_Print(json);
+ cJSON_Delete(json);
- strcat((char *) bufferPtr, jsonResponse);
+ strcat((char *) bufferPtr, jsonResponse);
- bufferLength = strlen((const char *) buffer);
- if (bufferLength > 0)
- {
- OCEntityHandlerResponse response =
- { 0 };
- response.ehResult = OC_EH_OK;
- response.payload = buffer;
- response.payloadSize = bufferLength + 1;
- response.persistentBufferFlag = 0;
- response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
- response.resourceHandle = (OCResourceHandle) collResource;
- stackRet = OCDoResponse(&response);
- }
+ bufferLength = strlen((const char *) buffer);
+ if (bufferLength > 0)
+ {
+ OCEntityHandlerResponse response = {};
+ response.ehResult = OC_EH_OK;
+ response.payload = buffer;
+ response.payloadSize = bufferLength + 1;
+ response.persistentBufferFlag = 0;
+ response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
+ response.resourceHandle = (OCResourceHandle) collResource;
+ stackRet = OCDoResponse(&response);
}
-
- OCFree(doWhat);
- OCFree(details);
}
+ OCFree(doWhat);
+ OCFree(details);
+
return stackRet;
}
+
Unit Test Requirements:
1. Install Google Test on a Linux build machine
-2. Create a file called "local.properties" in the
+2. Create a file called "local.properties" in the
root/csdk/stack/test. local.properties is used
by the makefile and specifies the path to the
Google Test directory on the build machine.
local.properties should contain GTEST_DIR.
For example:
-
+
GTEST_DIR := /home/johndoe/utils/gtest-1.7.0
If no interface is available, the unit tests will FAIL.
4. To run the unit test, first build the C OCStack.
At the time of this writing this was done by running
-
+
root/csdk/make deepclean
root/csdk/make BUILD=release *default
root/csdk/make BUILD=debug
root/csdk/stack/test/release/stacktests
root/csdk/stack/test/debug/stacktests
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
Import('env')
import os
import os.path
LOCAL_SRC_FILES += stacktests.cpp
+
"warning: only initialized variables can be placed into program memory area"
This appears to be a known gcc bug - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734
+
rm -fr $(BIN_DIR)
rm -fr $(OBJ_DIR)
+
}
void setup() {
- Serial.begin(115200);
-
+ Serial.begin(115200);
+
Serial.println ("Trying to get an IP addr using DHCP");
if (Ethernet.begin(ETHERNET_MAC) == 0) {
Serial.println("DHCP failed");
}
void loop() {
- Serial.println ("Processing CoAP messages!\n");
+ Serial.println ("Processing CoAP messages!\n");
OCProcess ();
- delay(1000);
+ delay(1000);
}
+
clean:
rm -rf debug
rm -rf release
+
}
int main() {
- OCDoHandle handle;
-
OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
/* Initialize OCStack*/
/* Start a discovery query*/
char szQueryUri[64] = { 0 };
strcpy(szQueryUri, OC_EXPLICIT_DEVICE_DISCOVERY_URI);
- if (OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS,
+ if (OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS,
0, 0, 0) != OC_STACK_OK) {
OC_LOG(ERROR, TAG, "OCStack resource error");
return 0;
return 0;
}
+
OC_DISCOVERABLE|OC_OBSERVABLE);
return res;
}
+
legacy_clean:
rm -f *.o $(PROGRAMS)
+
EXPECT_EQ(OC_STACK_OK, OCStop());
}
-#if 0
-TEST(StackTest, StackTestResourceDiscoverIfFilteringBad) {
- uint8_t addr[20];
- uint16_t port = USE_RANDOM_PORT;
- uint8_t ifname[] = "eth0";
- char uri[] = "/oc/core";
- char query[] = "if";
- char req[1024] = {};
- char rsp[1024] = {};
- //OCServerRequestResult res;
-
- //EXPECT_EQ(OC_STACK_INVALID_QUERY, OCHandleServerRequest(&res, uri, query, req, rsp));
-}
-
-TEST(StackTest, StackTestResourceDiscoverRtFilteringBad) {
- uint8_t addr[20];
- uint16_t port = USE_RANDOM_PORT;
- uint8_t ifname[] = "eth0";
- char uri[] = "/oc/core";
- char query[] = "rt";
- char req[1024] = {};
- char rsp[1024] = {};
- //OCServerRequestResult res;
-
- //EXPECT_EQ(OC_STACK_INVALID_QUERY, OCHandleServerRequest(&res, uri, query, req, rsp));
-}
-TEST(StackTest, StackTestResourceDiscoverIfFiltering) {
- uint8_t addr[20];
- uint16_t port = USE_RANDOM_PORT;
- uint8_t ifname[] = "eth0";
- char uri[] = "/oc/core";
- char query[] = "if=oc.mi.ll";
- char req[1024] = {};
- char rsp[1024] = {};
- //OCServerRequestResult res;
-
- //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp));
-}
-
-TEST(StackTest, StackTestResourceDiscoverRtFiltering) {
- uint8_t addr[20];
- uint16_t port = USE_RANDOM_PORT;
- uint8_t ifname[] = "eth0";
- char uri[] = "/oc/core";
- char query[] = "rt=core.brightled";
- char req[1024] = {};
- char rsp[1024] = {};
- //OCServerRequestResult res;
-
- //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp));
-}
-#endif
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# Examples build script
##
examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
examples_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap'])
-if env.get('SECURED') == '1':
+if env.get('SECURED') == '1':
examples_env.AppendUnique(LIBS = ['tinydtls'])
examples_env.ParseConfig('pkg-config --libs glib-2.0');
])
env.AppendTarget('examples')
+
int main(int argc, char* argv[]) {
- ostringstream requestURI;
+ std::ostringstream requestURI;
std::string deviceDiscoveryURI = "/oc/core/d";
OCConnectivityType connectivityType = OC_WIFI;
try
{
std::size_t inputValLen;
- int optionSelected = stoi(argv[1], &inputValLen);
+ int optionSelected = std::stoi(argv[1], &inputValLen);
if(inputValLen == strlen(argv[1]))
{
std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
}
}
- catch(exception& e)
+ catch(std::exception& e)
{
std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
}
return 0;
}
+
DuplicateString(&deviceInfo.platformVersion, platformVersion);
DuplicateString(&deviceInfo.supportUrl, supportUrl);
DuplicateString(&deviceInfo.version, version);
- }catch(exception &e)
+ }catch(std::exception &e)
{
std::cout<<"String Copy failed!!\n";
return OC_STACK_ERROR;
+
#include <stdexcept>
#include <condition_variable>
#include <mutex>
+#include <atomic>
#include "OCPlatform.h"
#include "OCApi.h"
const uint16_t API_VERSION = 2048;
const uint16_t TOKEN = 3000;
-static OCConnectivityType connectivityType = OC_WIFI;
-
class ClientFridge
{
public:
- ClientFridge()
+ ClientFridge(OCConnectivityType ct): m_callbackCount(0),
+ m_callsMade(0),m_connectivityType(ct)
{
- ostringstream requestURI;
+ std::ostringstream requestURI;
requestURI << OC_WELL_KNOWN_QUERY << "?rt=intel.fridge";
std::cout << "Fridge Client has started " <<std::endl;
FindCallback f (std::bind(&ClientFridge::foundDevice, this, PH::_1));
OCStackResult result = OCPlatform::findResource(
- "", requestURI.str(), connectivityType, f);
+ "", requestURI.str(), m_connectivityType, f);
if(OC_STACK_OK != result)
{
// its duties, so we block on the CV until we have completed
// what we are looking to do
std::unique_lock<std::mutex> lk(m_mutex);
- m_cv.wait(lk);
+ m_cv.wait(lk, [this]{ return m_callbackCount!=0 && m_callbackCount == m_callsMade;});
}
}
std::vector<std::string> lightTypes = {"intel.fridge.light"};
std::vector<std::string> ifaces = {DEFAULT_INTERFACE};
OCResource::Ptr light = constructResourceObject(resource->host(),
- "/light", connectivityType, false, lightTypes, ifaces);
+ "/light", m_connectivityType, false, lightTypes, ifaces);
if(!light)
{
std::vector<std::string> doorTypes = {"intel.fridge.door"};
OCResource::Ptr leftdoor = constructResourceObject(resource->host(),
- "/door/left", connectivityType, false, doorTypes, ifaces);
+ "/door/left", m_connectivityType, false, doorTypes, ifaces);
if(!leftdoor)
{
}
OCResource::Ptr rightdoor = constructResourceObject(resource->host(),
- "/door/right", connectivityType, false, doorTypes, ifaces);
+ "/door/right", m_connectivityType, false, doorTypes, ifaces);
if(!rightdoor)
{
}
OCResource::Ptr randomdoor = constructResourceObject(resource->host(),
- "/door/random", connectivityType, false, doorTypes, ifaces);
+ "/door/random", m_connectivityType, false, doorTypes, ifaces);
if(!randomdoor)
{
std::cout << "Error: Random Door Resource Object construction returned null\n";
// Below, header options are set only for device resource
resource->setHeaderOptions(headerOptions);
+ ++m_callsMade;
resource->get(QueryParamsMap(), GetCallback(
std::bind(&ClientFridge::getResponse, this, "Device", PH::_1,
PH::_2, PH::_3, resource, 0)
));
+ ++m_callsMade;
light->get(QueryParamsMap(), GetCallback(
std::bind(&ClientFridge::getResponse, this, "Fridge Light", PH::_1,
PH::_2, PH::_3, light, 1)
));
+ ++m_callsMade;
leftdoor->get(QueryParamsMap(), GetCallback(
std::bind(&ClientFridge::getResponse, this, "Left Door", PH::_1,
PH::_2, PH::_3, leftdoor, 2)
));
+ ++m_callsMade;
rightdoor->get(QueryParamsMap(), GetCallback(
std::bind(&ClientFridge::getResponse, this, "Right Door", PH::_1,
PH::_2, PH::_3, rightdoor, 3)
));
+ ++m_callsMade;
randomdoor->get(QueryParamsMap(), GetCallback(
std::bind(&ClientFridge::getResponse, this, "Random Door", PH::_1,
PH::_2, PH::_3, randomdoor, 4)
));
+ ++m_callsMade;
resource->deleteResource(DeleteCallback(
std::bind(&ClientFridge::deleteResponse, this, "Device", PH::_1,
PH::_2, resource, 0)
break;
}
}
+ ++m_callbackCount;
+
+ if(m_callbackCount == m_callsMade)
+ {
+ m_cv.notify_all();
+ }
}
//Callback function to handle response for deleteResource call.
std::cout << "Got a response from delete from the "<< resourceName << std::endl;
std::cout << "Delete ID is "<<deleteId<<" and resource URI is "<<resource->uri()<<std::endl;
printHeaderOptions(headerOptions);
+
+ ++m_callbackCount;
+
+ if(m_callbackCount == m_callsMade)
+ {
+ m_cv.notify_all();
+ }
}
//Function to print the headerOptions received from the server
std::mutex m_mutex;
std::condition_variable m_cv;
+ std::atomic<int> m_callbackCount;
+ std::atomic<int> m_callsMade;
+ OCConnectivityType m_connectivityType;
};
int main(int argc, char* argv[])
{
-
+ OCConnectivityType connectivityType = OC_WIFI;
if(argc == 2)
{
try
{
std::size_t inputValLen;
- int optionSelected = stoi(argv[1], &inputValLen);
+ int optionSelected = std::stoi(argv[1], &inputValLen);
if(inputValLen == strlen(argv[1]))
{
std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
}
}
- catch(exception& e)
+ catch(std::exception& e)
{
std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
}
};
OCPlatform::Configure(cfg);
- ClientFridge cf;
+ ClientFridge cf(connectivityType);
return 0;
}
+
std::this_thread::sleep_for(std::chrono::minutes(30));
return 0;
}
+
const int SUCCESS_RESPONSE = 0;
std::shared_ptr<OCResource> curResource;
+std::mutex resourceLock;
class Garage
{
// Callback to found resources
void foundResource(std::shared_ptr<OCResource> resource)
{
+ std::lock_guard<std::mutex> lock(resourceLock);
if(curResource)
{
std::cout << "Found another resource, ignoring"<<std::endl;
+ return;
}
std::string resourceURI;
int main(int argc, char* argv[]) {
-ostringstream requestURI;
+ std::ostringstream requestURI;
OCConnectivityType connectivityType = OC_WIFI;
try
{
std::size_t inputValLen;
- int optionSelected = stoi(argv[1], &inputValLen);
+ int optionSelected = std::stoi(argv[1], &inputValLen);
if(inputValLen == strlen(argv[1]))
{
std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
}
}
- catch(exception& e)
+ catch(std::exception& e)
{
std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
}
return 0;
}
+
// Forward declaring the entityHandler
OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request);
-/// This class represents a single resource named 'lightResource'. This resource has
-
+/// This class represents a single resource named 'GarageResource'.
class GarageResource
{
public:
}
catch(OCException e)
{
- //log(e.what());
+ oclog() << e.what();
}
// No explicit call to stop the OCPlatform
return 0;
}
+
cout << "\tresource Error!" << endl;
}
}
-
- // p_platform.bindResource(resourceHandle, foundResourceHandle);
-
}
}
catch (std::exception& e)
}
catch (OCException& e)
{
-
+ oclog() << "Exception in main: "<< e.what();
}
return 0;
}
+
// Forward declaring the entityHandler
/// This class represents a single resource named 'lightResource'. This resource has
-/// two simple properties named 'state' and 'power'
+/// one simple attribute, power
class LightResource
{
std::unique_lock<std::mutex> lock(blocker);
cv.wait(lock);
}
- catch(OCException e)
+ catch(OCException& e)
{
- //log(e.what());
+ oclog() << "Exception in main: "<< e.what();
}
// No explicit call to stop the platform.
return 0;
}
+
clean_apps:
rm -rf debug
rm -rf release
+
using namespace OC;
std::shared_ptr<OCResource> curResource;
+std::mutex resourceLock;
static int TEST_CASE = 0;
void printUsage()
{
- std::cout << "Usage : presenceclient -t <1|2> -c <0|1>" << std::endl;
+ std::cout << "Usage : presenceclient -t <1|2|3|4|5|6> -c <0|1>" << std::endl;
std::cout << "-t 1 : Discover Resources and Initiate Unicast Presence" << std::endl;
std::cout << "-t 2 : Discover Resources and Initiate Unicast Presence with Filter"
<< std::endl;
// Callback to found resources
void foundResource(std::shared_ptr<OCResource> resource)
{
+ std::lock_guard<std::mutex> lock(resourceLock);
if(curResource)
{
std::cout << "Found another resource, ignoring"<<std::endl;
+ return;
}
std::string resourceURI;
int main(int argc, char* argv[]) {
- ostringstream requestURI;
+ std::ostringstream requestURI;
int opt;
switch(opt)
{
case 't':
- TEST_CASE = stoi(optarg);
+ TEST_CASE = std::stoi(optarg);
break;
case 'c':
std::size_t inputValLen;
- optionSelected = stoi(optarg, &inputValLen);
+ optionSelected = std::stoi(optarg, &inputValLen);
if(inputValLen == strlen(optarg))
{
}
}
}
- catch(exception& e)
+ catch(std::exception& e)
{
std::cout << "Invalid input argument. Using WIFI as connectivity type"
<< std::endl;
std::unique_lock<std::mutex> lock(blocker);
cv.wait(lock);
- }catch(OCException& e)
+ }
+ catch(OCException& e)
{
- //log(e.what());
+ oclog() << "Exception in main: "<< e.what();
}
return 0;
}
+
std::unique_lock<std::mutex> lock(blocker);
cv.wait(lock);
}
- catch(OCException e)
+ catch(OCException& e)
{
- //log(e.what());
+ oclog() << "Exception in main: "<< e.what();
}
// No explicit call to stop the platform.
return 0;
}
+
const int SUCCESS_RESPONSE = 0;
std::shared_ptr<OCResource> curResource;
+std::mutex resourceLock;
int observe_count()
{
// Callback to found resources
void foundResource(std::shared_ptr<OCResource> resource)
{
+ std::lock_guard<std::mutex> lock(resourceLock);
if(curResource)
{
std::cout << "Found another resource, ignoring"<<std::endl;
int main(int argc, char* argv[]) {
- ostringstream requestURI;
+ std::ostringstream requestURI;
OCConnectivityType connectivityType = OC_WIFI;
if(argc == 2)
try
{
std::size_t inputValLen;
- int optionSelected = stoi(argv[1], &inputValLen);
+ int optionSelected = std::stoi(argv[1], &inputValLen);
if(inputValLen == strlen(argv[1]))
{
std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
}
}
- catch(exception& e)
+ catch(std::exception& e)
{
std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
}
}catch(OCException& e)
{
- //log(e.what());
+ oclog() << "Exception in main: "<< e.what();
}
return 0;
}
+
if(eCode == OC_STACK_OK)
{
std::cout << "OBSERVE RESULT:"<<std::endl;
- std::cout << "\tSequenceNumber: "<< sequenceNumber << endl;
+ std::cout << "\tSequenceNumber: "<< sequenceNumber << std::endl;
rep.getValue("state", mylight.m_state);
rep.getValue("power", mylight.m_power);
rep.getValue("name", mylight.m_name);
}
if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
- std::cout << endl << "Observe is used." << endl << endl;
+ std::cout << std::endl << "Observe is used." << std::endl << std::endl;
else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
- std::cout << endl << "ObserveAll is used." << endl << endl;
+ std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;
curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve);
// Callback to found resources
void foundResource(std::shared_ptr<OCResource> resource)
{
- cout << "In foundResource\n";
+ std::cout << "In foundResource\n";
std::string resourceURI;
std::string hostAddress;
try
int main(int argc, char* argv[]) {
- ostringstream requestURI;
+ std::ostringstream requestURI;
try
{
else if (argc == 2)
{
- checkObserverValue(stoi(argv[1]));
+ checkObserverValue(std::stoi(argv[1]));
std::cout << "<===No ConnectivtyType selected. "
<< "Setting ConnectivityType to WIFI===>\n\n";
}
else if(argc == 3)
{
- checkObserverValue(stoi(argv[1]));
- checkConnectivityValue(stoi(argv[2]));
+ checkObserverValue(std::stoi(argv[1]));
+ checkConnectivityValue(std::stoi(argv[2]));
}
else
{
return -1;
}
}
- catch(exception& e)
+ catch(std::exception& e)
{
std::cout << "<===Invalid input arguments===>\n\n";
return -1;
}catch(OCException& e)
{
- //log(e.what());
+ oclog() << "Exception in main: "<<e.what();
}
return 0;
}
+
DiscoveredResourceSet discoveredResources;
const int SUCCESS_RESPONSE = 0;
std::shared_ptr<OCResource> curResource;
+std::mutex resourceLock;
static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe;
//TODO-CA: Since CA CON message support is still in progress, this client uses
std::cout << "OBSERVE RESULT:"<<std::endl;
if(sequenceNumber == (int) ObserveAction::ObserveRegister)
{
- std::cout << "\tObserve Registration Confirmed: "<< endl;
+ std::cout << "\tObserve Registration Confirmed: "<< std::endl;
}
else if (sequenceNumber == (int) ObserveAction::ObserveUnregister)
{
- std::cout << "\tObserve Cancel Confirmed: "<< endl;
+ std::cout << "\tObserve Cancel Confirmed: "<< std::endl;
sleep(10);
std::cout << "DONE"<<std::endl;
std::exit(0);
}
else
{
- std::cout << "\tSequenceNumber: "<< sequenceNumber << endl;
+ std::cout << "\tSequenceNumber: "<< sequenceNumber << std::endl;
}
rep.getValue("state", mylight.m_state);
}
if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
- std::cout << endl << "Observe is used." << endl << endl;
+ std::cout << std::endl << "Observe is used." << std::endl << std::endl;
else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
- std::cout << endl << "ObserveAll is used." << endl << endl;
+ std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;
sleep(1);
curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve,
OC::QualityOfService::LowQos);
std::string hostAddress;
try
{
- if(discoveredResources.find(resource) == discoveredResources.end())
- {
- std::cout << "Found resource " << resource->uniqueIdentifier() <<
- " for the first time on server with ID: "<< resource->sid()<<std::endl;
- discoveredResources.insert(resource);
- }
- else
- {
- std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl;
- }
-
- if(curResource)
- {
- std::cout << "Found another resource, ignoring"<<std::endl;
- return;
- }
-
// Do some operations with resource object.
if(resource)
{
+ std::lock_guard<std::mutex> lk(resourceLock);
+
+ if(discoveredResources.find(resource) == discoveredResources.end())
+ {
+ std::cout << "Found resource " << resource->uniqueIdentifier() <<
+ " for the first time on server with ID: "<< resource->sid()<<std::endl;
+ discoveredResources.insert(resource);
+ }
+ else
+ {
+ std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl;
+ }
+
+ if(curResource)
+ {
+ std::cout << "Found another resource, ignoring"<<std::endl;
+ return;
+ }
+
std::cout<<"DISCOVERED Resource:"<<std::endl;
// Get the resource URI
resourceURI = resource->uri();
{
curResource = resource;
sleep(1);
- // Call a local function which will internally invoke get API on the resource pointer
+ // Call a local function which will internally invoke get
+ // API on the resource pointer
getLightRepresentation(resource);
}
}
int main(int argc, char* argv[]) {
- ostringstream requestURI;
+ std::ostringstream requestURI;
OCConnectivityType connectivityType = OC_WIFI;
try
{
OBSERVE_TYPE_TO_USE = ObserveType::Observe;
}
- else if (argc >= 2)
+ else if (argc ==2 || argc==3)
{
- int value = stoi(argv[1]);
+ int value = std::stoi(argv[1]);
if (value == 1)
OBSERVE_TYPE_TO_USE = ObserveType::Observe;
else if (value == 2)
if(argc == 3)
{
std::size_t inputValLen;
- int optionSelected = stoi(argv[2], &inputValLen);
+ int optionSelected = std::stoi(argv[2], &inputValLen);
if(inputValLen == strlen(argv[2]))
{
return -1;
}
}
- catch(exception& e)
+ catch(std::exception& e)
{
std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
}
std::unique_lock<std::mutex> lock(blocker);
cv.wait(lock);
- }catch(OCException& e)
+ }
+ catch(OCException& e)
{
- //log(e.what());
+ oclog() << "Exception in main: "<<e.what();
}
return 0;
}
+
#include "OCApi.h"
using namespace OC;
-OCConnectivityType connectivityType = OC_WIFI;
class ClientWorker
{
private:
- bool m_isFoo;
- int m_barCount;
void putResourceInfo(const HeaderOptions& headerOptions,
const OCRepresentation rep, const OCRepresentation rep2, const int eCode)
{
}
public:
+ ClientWorker(OCConnectivityType ct):m_connectivityType{ct}
+ {}
+
void start()
{
- ostringstream requestURI;
+ std::ostringstream requestURI;
requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.foo";
std::cout<<"Starting Client find:"<<std::endl;
FindCallback f (std::bind(&ClientWorker::foundResource, this, std::placeholders::_1));
std::cout<<"result:" <<
- OCPlatform::findResource("", requestURI.str(), connectivityType, f)
+ OCPlatform::findResource("", requestURI.str(), m_connectivityType, f)
<< std::endl;
std::cout<<"Finding Resource..."<<std::endl;
std::mutex m_resourceLock;
std::condition_variable m_cv;
std::shared_ptr<OCResource> m_resource;
+ OCConnectivityType m_connectivityType;
+ bool m_isFoo;
+ int m_barCount;
};
struct FooResource
int main(int argc, char* argv[])
{
+ OCConnectivityType connectivityType = OC_WIFI;
if(argc == 2)
{
try
{
std::size_t inputValLen;
- int optionSelected = stoi(argv[1], &inputValLen);
+ int optionSelected = std::stoi(argv[1], &inputValLen);
if(inputValLen == strlen(argv[1]))
{
std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
}
}
- catch(exception& e)
+ catch(std::exception& e)
{
std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
}
return -1;
}
- ClientWorker cw;
+ ClientWorker cw(connectivityType);
cw.start();
}
catch(OCException& e)
return 0;
}
+
std::mutex blocker;
std::condition_variable cv;
std::unique_lock<std::mutex> lock(blocker);
- cv.wait(lock);
+ cv.wait(lock, []{return false;});
}
catch(OCException &e)
{
return 0;
}
+
void createResource()
{
std::string resourceURI = m_lightUri; // URI of the resource
- std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light
+ // resource type name. In this case, it is light
+ std::string resourceTypeName = "core.light";
std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
// OCResourceProperty is defined ocstack.h
void PrintUsage()
{
std::cout << std::endl;
- std::cout << "Usage : simplserver <isListOfObservers>\n";
+ std::cout << "Usage : simpleserver <isListOfObservers>\n";
std::cout << " ObserveType : 0 - Observe All\n";
std::cout << " ObserveType : 1 - Observe List of observers\n\n";
}
try
{
- // Create the instance of the resource class (in this case instance of class 'LightResource').
+ // Create the instance of the resource class
+ // (in this case instance of class 'LightResource').
LightResource myLight(cfg);
// Invoke createResource function of class light.
std::mutex blocker;
std::condition_variable cv;
std::unique_lock<std::mutex> lock(blocker);
- cv.wait(lock);
+ cv.wait(lock, []{return false;});
}
- catch(OCException e)
+ catch(OCException& e)
{
- //log(e.what());
+ oclog() << "Exception in main: "<< e.what();
}
// No explicit call to stop the platform.
return 0;
}
+
try
{
std::size_t inputValLen;
- int optionSelected = stoi(argv[1], &inputValLen);
+ int optionSelected = std::stoi(argv[1], &inputValLen);
if(inputValLen == strlen(argv[1]))
{
std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
}
}
- catch(exception& e)
+ catch(std::exception& e)
{
std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
}
return 0;
}
+
#endif //__OCPLATFORM_H
+
namespace OC
{
- /**
- * @brief Both server and client must initialize the core platform by instantiating OCPlatform.
- * On successful initialization, an instance of the OCPlatform is returned.
- * APIs in OCPlatform provide mechanism to register a resource and host the resource
- * on the server, find resources on the network etc.
- */
class OCPlatform_impl
{
private:
static PlatformConfig& globalConfig();
public:
- /**
- * API for overwriting the default configuration of the OCPlatform object.
- * Note: Any calls made to this AFTER the first call to OCPlatform::Instance
- * will have no affect
- */
static void Configure(const PlatformConfig& config);
- /**
- * API for retrieving the current OCPlatform object. This will use the
- * default platform config, unless the default is over-written using the
- * Configure method before the first call to instance.
- */
static OCPlatform_impl& Instance();
public:
// typedef for handle to cancel presence info with
typedef OCDoHandle OCPresenceHandle;
- /**
- * Virtual destructor
- */
virtual ~OCPlatform_impl(void);
- /**
- * API for notifying base that resource's attributes have changed.
- *
- * @param OCResourceHandle resource handle of the resource
- * @param QualityOfService the quality of communication
- *
- * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
- * NOTE: This API is for server side only.
- * NOTE: OCResourceHandle is defined in ocstack.h.
- * NOTE: OCStackResult is defined in ocstack.h.
- */
OCStackResult notifyAllObservers(OCResourceHandle resourceHandle);
+
OCStackResult notifyAllObservers(OCResourceHandle resourceHandle, QualityOfService QoS);
- /**
- * API for notifying only specific clients that resource's attributes have changed.
- *
- * @param OCResourceHandle resource handle of the resource
- * @param observationIds std vector of observationIds. These set of ids are ones which
- * which will be notified upon resource change.
- * @param responsePtr OCResourceResponse pointer used by app to fill the response for this
- * resource change.
- * @param QualityOfService the quality of communication
- *
- * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
- *
- * NOTE: This API is for server side only.
- * NOTE: OCResourceHandle is defined in ocstack.h.
- * NOTE: OCStackResult is defined in ocstack.h.
- */
OCStackResult notifyListOfObservers(
OCResourceHandle resourceHandle,
ObservationIds& observationIds,
const std::shared_ptr<OCResourceResponse> responsePtr);
+
OCStackResult notifyListOfObservers(
OCResourceHandle resourceHandle,
ObservationIds& observationIds,
const std::shared_ptr<OCResourceResponse> responsePtr,
QualityOfService QoS);
- /**
- * API for Service and Resource Discovery.
- * NOTE: This API applies to client side only.
- *
- * @param host - Host IP Address of a service to direct resource discovery query. If null or
- * empty, performs multicast resource discovery query
- * @param resourceURI - name of the resource. If null or empty, performs search for all
- * resource names
- * @param handler - Handles callbacks, success states and failure states.
- *
- * Four modes of discovery defined as follows:
- * (NULL/Empty, NULL/Empty) - Performs ALL service discovery AND ALL resource
- * discovery.
- * (NULL/Empty, Not Empty) - Performs query for a filtered/scoped/particular
- * resource(s) from ALL services.
- * (Not Empty, NULL/Empty) - Performs ALL resource discovery on a particular service.
- * (Not Empty, Not Empty) - Performs query for a filtered/scoped/particular
- * resource(s) from a particular service.
- * @param QualityOfService the quality of communication
- *
- * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
- * NOTE: First parameter 'host' currently represents an IP address. This will change in
- * future and will refer to endpoint interface so that we can refer to other transports such
- * as BTH etc.
- * NOTE: OCStackResult is defined in ocstack.h.
- */
OCStackResult findResource(const std::string& host, const std::string& resourceURI,
OCConnectivityType connectivityType, FindCallback resourceHandler);
+
OCStackResult findResource(const std::string& host, const std::string& resourceURI,
OCConnectivityType connectivityType, FindCallback resourceHandler,
QualityOfService QoS);
- /**
- * API for Device Discovery
- *
- * @param host - Host IP Address. If null or empty, Multicast is performed.
- * @param resourceURI - Uri containing address to the virtual device in C Stack
- * ("/oc/core/d")
- *
- * @param QualityOfService the quality of communication
- *
- */
+
OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler);
+
OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler,
QualityOfService QoS);
EntityHandler entityHandler,
uint8_t resourceProperty);
- /**
- * This API registers a resource with the server
- * NOTE: This API applies to server & client side.
-
- * @param resourceHandle - Upon successful registration, resourceHandle will be filled
- * @param OCResource - The instance of OCResource that all data filled.
- *
- * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
- */
-
OCStackResult registerResource(OCResourceHandle& resourceHandle,
const std::shared_ptr<OCResource> resource);
- /**
- * This API registers all the device specific information
- *
- * @param OCDeviceInfo - Structure containing all the device related information
- *
- * @return OCStackResult return value of the API. Returns OC_STACK_OK if success
- *
- * Note: OCDeviceInfo is defined in OCStack.h
- */
OCStackResult registerDeviceInfo(const OCDeviceInfo deviceInfo);
- /**
- * Set default device entity handler
- *
- * @param entityHandler - entity handler to handle requests for
- * any undefined resources or default actions.
- * if NULL is passed it removes the device default entity handler.
- *
- * @return
- * OC_STACK_OK - no errors
- * OC_STACK_ERROR - stack process error
- */
OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler);
- /**
- * This API unregisters a resource with the server
- * NOTE: This API applies to server side only.
- *
- * @param resourceHandle - This is the resource handle which we which to unregister from the
- * server
- *
- * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
- * NOTE: OCStackResult is defined in ocstack.h.
- */
OCStackResult unregisterResource(const OCResourceHandle& resourceHandle) const;
- /**
- * Add a resource to a collection resource.
- *
- * @param collectionHandle - handle to the collection resource
- * @param addedResourceHandle - handle to resource to be added to the collection resource
- *
- * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.<br>
- * NOTE: OCStackResult is defined in ocstack.h. <br>
- * NOTE: bindResource must be used only after the both collection resource and
- * resource to add under a collections are created and respective handles obtained<br>
- * <b>Example:</b> <br>
- * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface,
- * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
- * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface,
- * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
- * Step 3: bindResource(homeResourceHandle, kitchenResourceHandle);<br>
- * At the end of Step 3, resource "a/home" will contain a reference to "a/kitchen".<br>
- */
OCStackResult bindResource(const OCResourceHandle collectionHandle,
const OCResourceHandle resourceHandle);
- /**
- * Add multiple resources to a collection resource.
- *
- * @param collectionHandle - handle to the collection resource
- * @param addedResourceHandleList reference to list of resource handles to be added to
- * the collection resource
- *
- * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
- * NOTE: OCStackResult is defined in ocstack.h. <br>
- * NOTE: bindResources must be used only after the both collection resource and
- * list of resources to add under a collection are created and respective handles
- * obtained<br>
- * <b> Example: </b> <br>
- * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface,
- * homeEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
- * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface,
- * kitchenEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
- * Step 3: registerResource(roomResourceHandle, "a/room", "room", Link_Interface,
- * roomEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
- * Step 4: std::vector<OCResourceHandle> rList; rList.push_back(kitchenResourceHandle);
- * rList.push_back(roomResourceHandle);<br>
- * Step 5: bindResource(homeResourceHandle, rList);<br>
- * At the end of Step 5, resource "a/home" will contain a references to "a/kitchen"
- * and "a/room" <br>
- */
OCStackResult bindResources(const OCResourceHandle collectionHandle,
const std::vector<OCResourceHandle>& addedResourceHandleList);
- /**
- * Unbind a resource from a collection resource.
- *
- * @param collectionHandle - handle to the collection resource
- * @param resourceHandle resource handle to be unbound from the collection resource
- *
- * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
- * NOTE: OCStackResult is defined in ocstack.h.<br>
- * NOTE: unbindResource must be used only after the both collection resource and
- * resource to unbind from a collection are created and respective handles obtained<br>
- * <b> Example </b> <br>
- * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface,
- * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
- * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface,
- * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
- * Step 3: bindResource(homeResourceHandle, kitchenResourceHandle);<br>
- * Step 4: unbindResource(homeResourceHandle, kitchenResourceHandle);<br>
- * At the end of Step 4, resource "a/home" will no longer reference "a/kitchen". <br>
- */
OCStackResult unbindResource(const OCResourceHandle collectionHandle,
const OCResourceHandle resourceHandle);
- /**
- * Unbind resources from a collection resource.
- *
- * @param collectionHandle - handle to the collection resource
- * @param resourceHandleList List of resource handles to be unbound from the collection
- * resource
- *
- * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
- *
- * NOTE: OCStackResult is defined in ocstack.h.<br>
- * NOTE: unbindResources must be used only after the both collection resource and
- * list of resources resource to unbind from a collection are created and respective handles
- * obtained. <br>
- * <b>Example</b> <br>
- * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface,
- * homeEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
- * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface,
- * kitchenEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
- * Step 3: registerResource(roomResourceHandle, "a/room", "room", Link_Interface,
- * roomEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
- * Step 4: std::vector<OCResourceHandle> rList; rList.push_back(kitchenResourceHandle);
- * rList.push_back(roomResourceHandle);<br>
- * Step 5: bindResource(homeResourceHandle, rList);<br>
- * Step 6: unbindResources(homeResourceHandle, rList);<br>
- * At the end of Step 6, resource "a/home" will no longer reference to "a/kitchen"
- * and "a/room"<br>
- */
OCStackResult unbindResources(const OCResourceHandle collectionHandle,
const std::vector<OCResourceHandle>& resourceHandleList);
- /**
- * Binds a type to a particular resource
- * @param resourceHandle - handle to the resource
- * @param resourceTypeName - new typename to bind to the resource
-
- * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success <br>
- */
OCStackResult bindTypeToResource(const OCResourceHandle& resourceHandle,
const std::string& resourceTypeName) const;
- /**
- * Binds an interface to a particular resource
- * @param resourceHandle - handle to the resource
- * @param resourceTypeName - new interface to bind to the resource
-
- * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success <br>
- */
OCStackResult bindInterfaceToResource(const OCResourceHandle& resourceHandle,
const std::string& resourceInterfaceName) const;
- /**
- * Start Presence announcements.
- *
- * @param ttl - time to live
- * @return OCStackResult - Returns OCSTACK_OK if success <br>
- *
- * Server can call this function when it comes online for the
- * first time, or when it comes back online from offline mode,
- * or when it re enters network.
- *
- */
OCStackResult startPresence(const unsigned int ttl);
- /**
- * Stop Presence announcements.
- *
- * @return OCStackResult - Returns OCSTACK_OK if success <br>
- *
- * Server can call this function when it is terminating,
- * going offline, or when going away from network.
- *
- */
OCStackResult stopPresence();
- /**
- * subscribes to a server's presence change events. By making this subscription,
- * every time a server adds/removes/alters a resource, starts or is intentionally
- * stopped (potentially more to be added later).
- *
- * @param presenceHandle - a handle object that can be used to identify this subscription
- * request. It can be used to unsubscribe from these events in the future.
- * It will be set upon successful return of this method.
- * @param host - The IP address/addressable name of the server to subscribe to.
- * @param resourceType - a resource type specified as a filter for subscription callbacks.
- * @param presenceHandler - callback function that will receive notifications/subscription
- * events
- *
- * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success <br>
- */
OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host,
OCConnectivityType connectivityType, SubscribeCallback presenceHandler);
+
OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host,
const std::string& resourceType, OCConnectivityType connectivityType,
SubscribeCallback presenceHandler);
- /**
- * unsubscribes from a previously subscribed server's presence events. Note that
- * you may for a short time still receive events from the server since it may take time
- * for the unsubscribe to take effect.
- *
- * @param presenceHandle - the handle object provided by the subscribePresence call that
- * identifies this subscription.
- *
- * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success <br>
- */
OCStackResult unsubscribePresence(OCPresenceHandle presenceHandle);
- /**
- * Creates a resource proxy object so that get/put/observe functionality
- * can be used without discovering the object in advance. Note that the
- * consumer of this method needs to provide all of the details required to
- * correctly contact and observe the object. If the consumer lacks any of
- * this information, they should discover the resource object normally.
- * Additionally, you can only create this object if OCPlatform was initialized
- * to be a Client or Client/Server. Otherwise, this will return an empty
- * shared ptr.
- *
- * @param host - a string containing a resolvable host address of the server
- * holding the resource. Currently this should be in the format
- * coap://address:port, though in the future, we expect this to
- * change to //address:port
- *
- * @param uri - the rest of the resource's URI that will permit messages to be
- * properly routed. Example: /a/light
- *
- * @param isObservable - a boolean containing whether the resource supports observation
- *
- * @param resourceTypes - a collection of resource types implemented by the resource
- *
- * @param interfaces - a collection of interfaces that the resource supports/implements
- * @return OCResource::Ptr - a shared pointer to the new resource object
- */
OCResource::Ptr constructResourceObject(const std::string& host, const std::string& uri,
OCConnectivityType connectivityType, bool isObservable,
const std::vector<std::string>& resourceTypes,
const std::vector<std::string>& interfaces);
- /**
- * Allows application entity handler to send response to an incoming request.
- *
- * @param pResponse - OCResourceResponse pointer that will permit to set values related
- * to resource response. <br>
- * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success <br>
- */
OCStackResult sendResponse(const std::shared_ptr<OCResourceResponse> pResponse);
private:
private:
/**
- * Constructor for OCPlatform. Constructs a new OCPlatform from a given PlatformConfig with
- * appropriate fields
+ * Constructor for OCPlatform_impl. Constructs a new OCPlatform_impl from a given
+ * PlatformConfig with appropriate fields
* @param config PlatformConfig struct which has details such as modeType
* (server/client/both), in-proc/out-of-proc etc.
*/
#endif //__OCPLATFORM_IMPL_H
+
public:
void setJSONRepresentation(const std::string& payload);
- void setJSONRepresentation(const unsigned char* payload);
+ void setJSONRepresentation(const char* payload);
std::string getJSONRepresentation(OCInfoFormat f) const;
#endif //__OCREPRESENTATION_H
+
{
class OCResource;
class OCResourceIdentifier;
- ostream& operator <<(ostream& os, const OCResourceIdentifier& ri);
+ std::ostream& operator <<(std::ostream& os, const OCResourceIdentifier& ri);
/**
* @brief OCResourceIdentifier represents the identity information for a server. This
* object combined with the OCResource's URI property uniquely identify an
class OCResourceIdentifier
{
friend class OCResource;
- friend ostream& operator <<(ostream& os, const OCResourceIdentifier& ri);
+ friend std::ostream& operator <<(std::ostream& os, const OCResourceIdentifier& ri);
public:
bool operator==(const OCResourceIdentifier &other) const;
} // namespace OC
#endif //__OCRESOURCE_H
+
#include <ocstack.h>
#include <OCRepresentation.h>
-using namespace std;
-
namespace OC
{
class InProcServerWrapper;
} // namespace OC
#endif //__OCRESOURCERESPONSE_H
+
std::string ConvertOCAddrToString(OCSecureType sec, int secureport)
{
uint16_t port;
- ostringstream os;
+ std::ostringstream os;
if(sec== OCSecureType::IPv4)
{
OCConnectivityType m_connectivityType;
};
}
+
namespace Utilities {
typedef std::map<std::string, std::string> QueryParamsKeyVal;
+
/*
- * @brief Helper function to get query parameter from a URI
- * @remarks Its okay to return a copy of the container.\
- * The size is not expected to be huge.
- * @remarks Temporary: The URI must strictly have\
- * coap as the protocol in the fully qualified URI\
- * e.g., coap://1.2.3.4:5657/foo?bar=0)
- * @remarks If a separate class for URI parser is needed,\
- * please talk to Erich Keane.
- * @todo If more URI elements need to be parsed,\
- * please move the common parsing logic to a
- * different function
+ * @brief helper function that parses the query parameters component
+ * of a URI into a key-value map. This function expects the uri
+ * parameter to contain the query parameters component of a URI
+ * (everything after the '?', excluding anything anchors).
+ *
+ * Note that output will not perform URL decoding
*/
QueryParamsKeyVal getQueryParams(const std::string& uri);
} // namespace OC
#endif
+
#include <string>
-using namespace std;
-
namespace OC
{
namespace InitException
}
#endif // _STRING_CONSTANTS_H_
+
-rm -f -v $(OBJ_DIR)/liboc.a $(OBJ_DIR)/*.o
cd csdk && $(MAKE) clean
cd csdk && $(MAKE) deepclean
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# liboc_logger (share library) build script
##
if target_os not in ['ios']:
SConscript('examples/SConscript')
+
#include <stdlib.h>
oc_log_ctx_t *oc_log_make_ctx(
- void* world,
- const oc_log_level level,
+ void* world,
+ const oc_log_level level,
oc_log_init_t init,
oc_log_destroy_t destroy,
oc_log_flush_t flush,
0 == set_level ||
0 == write_level ||
0 == set_module)
+ {
return 0;
+ }
if(OC_LOG_MIN_VAL__ >= level || OC_LOG_MAX_VAL__ <= level)
- return 0;
+ {
+ return 0;
+ }
log_ctx = (oc_log_ctx_t *)malloc(sizeof(oc_log_ctx_t));
- if(0 == log_ctx)
- return 0;
+ if(!log_ctx)
+ {
+ return 0;
+ }
log_ctx->ctx = 0; /* we'll get to this in a sec... */
log_ctx->log_level = level;
log_ctx->destroy = destroy;
log_ctx->flush = flush;
log_ctx->set_level = set_level;
- log_ctx->set_module = set_module;
+ log_ctx->set_module = set_module;
log_ctx->write_level = write_level;
- if(0 == log_ctx->init(log_ctx, world))
+ if(!log_ctx->init(log_ctx, world))
{
free(log_ctx);
return 0;
void oc_log_destroy(oc_log_ctx_t *ctx)
{
- if(0 == ctx)
- return;
+ if(!ctx)
+ {
+ return;
+ }
ctx->destroy(ctx);
if(0 != ctx->module_name)
- free(ctx->module_name);
+ {
+ free(ctx->module_name);
+ }
free(ctx);
}
int oc_log_init(oc_log_ctx_t *ctx, void *world)
{
- if(0 == ctx)
- return 0;
+ if(!ctx)
+ {
+ return 0;
+ }
return ctx->init(ctx, world);
}
void oc_log_flush(oc_log_ctx_t *ctx)
{
- if(0 == ctx)
+ if(!ctx)
{
return;
}
ctx->flush(ctx);
}
-void oc_log_set_level(oc_log_ctx_t *ctx, const oc_log_level ll)
+void oc_log_set_level(oc_log_ctx_t *ctx, const oc_log_level loglevel)
{
- if(0 == ctx)
+ if(!ctx)
{
return;
}
- ctx->set_level(ctx, ll);
+ ctx->set_level(ctx, loglevel);
}
size_t oc_log_write(oc_log_ctx_t *ctx, const char *msg)
{
- if(0 == ctx)
- return 0;
+ if(!ctx)
+ {
+ return 0;
+ }
return oc_log_write_level(ctx, ctx->log_level, msg);
}
-size_t oc_log_write_level(oc_log_ctx_t *ctx, const oc_log_level ll, const char *msg)
+size_t oc_log_write_level(oc_log_ctx_t *ctx, const oc_log_level loglevel, const char *msg)
{
- if(0 == ctx)
- return 0;
+ if(!ctx)
+ {
+ return 0;
+ }
- ctx->log_level = ll;
+ ctx->log_level = loglevel;
/* Notify: */
- return ctx->write_level(ctx, ll, msg);
+ return ctx->write_level(ctx, loglevel, msg);
}
int oc_log_set_module(oc_log_ctx_t *ctx, const char *module_name)
{
- char *mn;
- size_t l;
+ char *mn = NULL;
+ size_t len = 0;
- if(0 == ctx)
- return 0;
+ if(!ctx || !module_name)
+ {
+ return 0;
+ }
/* Swap pointers so that module data's not erased in the event of failure: */
- l = strlen(module_name);
+ len = strlen(module_name);
- mn = (char *)malloc(1 + l);
+ mn = (char *)malloc(1 + len);
- if(0 == mn)
- return 0;
+ if(!mn)
+ {
+ return 0;
+ }
- memcpy(mn, module_name, 1 + l);
+ memcpy(mn, module_name, 1 + len);
- if(0 != ctx->module_name)
- free(ctx->module_name);
+ if(!ctx->module_name)
+ {
+ free(ctx->module_name);
+ }
ctx->module_name = mn;
return ctx->set_module(ctx, ctx->module_name);
}
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# liboc_logger examples build script
##
Alias('liboc_logger_examples', [examples_c, examples_cpp])
examples_env.AppendTarget('liboc_logger_examples')
+
extern "C" {
#endif
- typedef enum {
+ typedef enum
+ {
OC_LOG_MIN_VAL__ = -1,
OC_LOG_ALL = 0,
OC_LOG_FATAL,
#endif
#endif
+
legacy_clean:
rm -f *.o $(PROGRAMS)
+
#include <OCResourceResponse.h>
#include <ocstack.h>
#include <OCApi.h>
+#include <ocmalloc.h>
#include <OCPlatform.h>
#include <OCUtilities.h>
{
if(entityHandlerRequest->query)
{
- std::string querystr(reinterpret_cast<char*>(entityHandlerRequest->query));
-
- OC::Utilities::QueryParamsKeyVal qp = OC::Utilities::getQueryParams(querystr);
+ OC::Utilities::QueryParamsKeyVal qp = OC::Utilities::getQueryParams(
+ entityHandlerRequest->query);
if(qp.size() > 0)
{
response.requestHandle = pResponse->getRequestHandle();
response.resourceHandle = pResponse->getResourceHandle();
response.ehResult = pResponse->getResponseResult();
- response.payload = (unsigned char*) payLoad.c_str();
+
+ response.payload = static_cast<char*>(OCMalloc(payLoad.length() + 1));
+ if(!response.payload)
+ {
+ result = OC_STACK_NO_MEMORY;
+ throw OCException(OC::Exception::NO_MEMORY, OC_STACK_NO_MEMORY);
+ }
+
+ strncpy(response.payload, payLoad.c_str(), payLoad.length()+1);
response.payloadSize = payLoad.length() + 1;
response.persistentBufferFlag = 0;
OCStop();
}
}
+
return OC::Exception::UNKNOWN_ERROR;
}
+
}
} // namespace OCPlatform
} //namespace OC
+
OCPlatform_impl::OCPlatform_impl(const PlatformConfig& config)
: m_cfg { config },
m_WrapperInstance { make_unique<WrapperFactory>() },
- m_csdkLock { make_shared<std::recursive_mutex>() }
+ m_csdkLock { std::make_shared<std::recursive_mutex>() }
{
init(m_cfg);
}
return result_guard(
OCNotifyListOfObservers(resourceHandle,
&observationIds[0], observationIds.size(),
- reinterpret_cast<unsigned char *>(const_cast<char *>(payload.c_str())),
+ payload.c_str(),
static_cast<OCQualityOfService>(QoS)));
}
uint8_t resourceProperty)
{
return checked_guard(m_server, &IServerWrapper::registerResource,
- ref(resourceHandle), resourceURI, resourceTypeName,
+ std::ref(resourceHandle), resourceURI, resourceTypeName,
resourceInterface, entityHandler, resourceProperty);
}
std::vector<std::string> resourceTypes = resource->getResourceTypes();
return checked_guard(m_server, &IServerWrapper::registerResourceWithHost,
- ref(resourceHandle), resource->host(), resource->uri(), resourceTypes[0]/*"core.remote"*/, "oc.mi.def",
+ std::ref(resourceHandle), resource->host(), resource->uri(),
+ resourceTypes[0]/*"core.remote"*/, "oc.mi.def",
(EntityHandler) nullptr, resourceProperty);
}
OCStackResult OCPlatform_impl::unbindResource(OCResourceHandle collectionHandle,
OCResourceHandle resourceHandle)
{
- return result_guard(OCUnBindResource(ref(collectionHandle), ref(resourceHandle)));
+ return result_guard(OCUnBindResource(std::ref(collectionHandle), std::ref(resourceHandle)));
}
OCStackResult OCPlatform_impl::unbindResources(const OCResourceHandle collectionHandle,
OCStackResult OCPlatform_impl::unsubscribePresence(OCPresenceHandle presenceHandle)
{
return checked_guard(m_client, &IClientWrapper::UnsubscribePresence,
- ref(presenceHandle));
+ std::ref(presenceHandle));
}
OCStackResult OCPlatform_impl::sendResponse(const std::shared_ptr<OCResourceResponse> pResponse)
pResponse);
}
} //namespace OC
+
}
}
- void MessageContainer::setJSONRepresentation(const unsigned char* payload)
+ void MessageContainer::setJSONRepresentation(const char* payload)
{
- setJSONRepresentation(std::string(reinterpret_cast<const char*>(payload)));
+ setJSONRepresentation(std::string(payload));
}
std::string MessageContainer::getJSONRepresentation(OCInfoFormat f) const
return os;
}
}
+
}
}
-ostream& operator <<(ostream& os, const OCResourceIdentifier& ri)
+std::ostream& operator <<(std::ostream& os, const OCResourceIdentifier& ri)
{
os << ri.m_representation<<ri.m_resourceUri;
}
} // namespace OC
+
#include <OCApi.h>
-#include "OCUtilities.h"
+#include <OCUtilities.h>
#include <boost/algorithm/string.hpp>
#include <iterator>
#include <algorithm>
-extern "C" {
-#include <uri.h> // libcoap
-#include <option.h> // libcoap
-}
-
-namespace OC {
-
- // Helper function to escape special character.
- std::string escapeString(const std::string& value)
- {
- std::ostringstream stringStream;
- for (const char& c : value)
- {
- switch (c)
- {
- case '\\': stringStream << "\\\\";
- break;
- case '"': stringStream << "\\\"";
- break;
- case '/': stringStream << "\\/";
- break;
- case '\b': stringStream << "\\b";
- break;
- case '\f': stringStream << "\\f";
- break;
- case '\n': stringStream << "\\n";
- break;
- case '\r': stringStream << "\\r";
- break;
- case '\t': stringStream << "\\t";
- break;
- default: stringStream << c;
- break;
- }
- }
- return stringStream.str();
- }
-}
-// [TODO] remove this function
-// it seems that the C stack is parsing and giving out the query separately.
-// the entire URI need not be parsed
-static OC::Utilities::QueryParamsKeyVal tempPatch(const std::string& _uri)
+OC::Utilities::QueryParamsKeyVal OC::Utilities::getQueryParams(const std::string& uri)
{
OC::Utilities::QueryParamsKeyVal qp;
- if(_uri.empty())
+ if(uri.empty())
{
return qp;
}
std::vector<std::string> queryparams;
- boost::split(queryparams, _uri, boost::is_any_of("&"));
+ boost::split(queryparams, uri, [](const char c){return c=='&';},
+ boost::token_compress_on);
for(std::string& it: queryparams)
{
- std::vector<std::string> keyval;
- boost::split(keyval, it, boost::is_any_of("="));
- if(2 == keyval.size())
- {
- qp[keyval.at(0)] = keyval.at(1);
- }
- }
-
- return qp;
-}
-
-// implementation can be split into two functions if needed
-// uses do{}while(0) to avoid returning from multiple locations
-OC::Utilities::QueryParamsKeyVal OC::Utilities::getQueryParams(const std::string& _uri)
-{
-
- // this is a temporary fix. [TODO] remove this after permanent fix
- return tempPatch(_uri);
-
- OC::Utilities::QueryParamsKeyVal qp;
- unsigned char *bufptr = nullptr; // don't delete via bufptr
- unsigned char *bufptrToDelete = nullptr; // bufptr may be incremented. need this one to keep track.
- do // while(0)
- {
- if(_uri.empty())
- {
- break;
- }
-
- coap_uri_t coapuri = {{0}};
- unsigned char* uristr = reinterpret_cast<unsigned char*>(const_cast<char*>(_uri.c_str()));
+ auto index = it.find('=');
- if(coap_split_uri(uristr, _uri.length(), &coapuri) < 0)
+ if(index == std::string::npos)
{
- break;
+ qp[it] = "";
}
-
- size_t buflen = 2048; // this is big enough buffer. [TODO] may want to downsize it. I have seen that the size may have to be greater than coap.query.length, which is counterintuitve but there may be a bug in coap uri parser.
- bufptrToDelete = bufptr = new (std::nothrow) unsigned char[buflen](); // why heap? will need it for incrementing the pointer in the logic below
-
- if(!bufptr)
+ else
{
- break;
- }
-
- int segments = -1;
- if((segments = coap_split_query(coapuri.query.s, coapuri.query.length, bufptr, &buflen)) < 0)
- {
- break;
- }
-
- // coap uri parser has weird api. its not straighforward to understand what the coap function calls below do.
- // coap uri parser lacks ability to split the key value pair in query params. that will be done in getQueryParams() function
- std::vector<std::string> queryparams;
- while(segments--)
- {
- queryparams.push_back(std::string (reinterpret_cast<char*>(coap_opt_value(bufptr)), coap_opt_length(bufptr)));
- bufptr += coap_opt_size(bufptr);
- }
-
- if(queryparams.empty())
- {
- break;
- }
-
- //[TODO] use foreach
- for(std::string& it : queryparams)
- {
- std::vector<std::string> keyval;
- boost::split(keyval, it, boost::is_any_of("="));
- if(2 == keyval.size())
- {
- qp[keyval.at(0)] = keyval.at(1);
- }
+ qp[it.substr(0, index)] = it.substr(index + 1);
}
}
- while(0);
-
- if(bufptrToDelete)
- {
- delete [] bufptrToDelete;
+ return qp;
}
- return qp;
-}
namespace OC {
}
} // namespace OC
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# OCLib (share library) build script
##
'../include/',
'../csdk/stack/include',
'../csdk/ocrandom/include',
+ '../csdk/ocmalloc/include',
'../csdk/logger/include',
'../oc_logger/include',
'../csdk/connectivity/lib/libcoap-4.1.1'
if target_os == 'android':
oclib_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
- oclib_env.AppendUnique(LIBS = ['octbstack', 'oc_logger', 'boost_thread-gcc-mt-1_49', 'gnustl_static', 'log'])
+ oclib_env.AppendUnique(LIBS = ['octbstack', 'oc_logger', 'boost_thread', 'gnustl_static', 'log'])
if target_os in ['darwin', 'ios']:
oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
oclib_env.AppendUnique(CPPPATH = [oclib_env.get('SRC_DIR') + '/extlibs/cereal/include'])
oclib = oclib_env.SharedLibrary('oc', oclib_src)
oclib_env.InstallTarget(oclib, 'liboc')
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
######################################################################
# This script manages third party libraries
#
if not target_arch == platform.machine():
print '''
*********************************** Warning ***********************************
-* You are trying cross build, please make sure (%s) version libraries are
-* installed! *
+* You are trying cross build, please make sure (%s) version libraries are *
+* installed! *
*******************************************************************************
''' % target_arch
elif target_os == 'darwin':
lib_env.AppendUnique(CPPPATH = ['/usr/local/include'])
lib_env.AppendUnique(LIBPATH = ['/usr/local/lib'])
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# 'unit_test' script for building unit tests and libs
#
##
-import os
-
Import('env')
target_os = env.get('TARGET_OS')
SConscript('unittests/SConscript')
+
2. Run the unit test by issuing the following command from <oic-resource>:
./unittests/unittests
+
+#******************************************************************
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Import('env')
import os
unittests_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
ut = unittests_env.Command ('ut', None,
[out_dir + '/resource/unittests/unittests'])
- AlwaysBuild ('ut')
\ No newline at end of file
+ AlwaysBuild ('ut')
clean:
-rm -rf release
-rm -rf debug
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# 'service' sub-project main build script
#
# SConscript('notification-manager/SConscript')
#else:
# SConscript('notification-manager/SampleApp/arduino/SConscript')
+
clean:
rm -f $(OBJS) SampleConsumer.o SampleProvider.o NotificationManager SampleProvider SampleConsumer
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# NotificationManager build script
##
# Go to build sample apps
SConscript('SampleApp/SConscript')
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# NotificationManager build script
##
# Source files and Targets
######################################################################
sampleprovider = notimgr_env.Program('sampleprovider', 'sampleProvider/SampleProvider.cpp')
-sampleconsumer = notimgr_env.Program('sampleconsumer', 'sampleConsumer/SampleConsumer.cpp')
\ No newline at end of file
+sampleconsumer = notimgr_env.Program('sampleconsumer', 'sampleConsumer/SampleConsumer.cpp')
+
ADD_EXECUTABLE(${EX_NOTICONSUMER} ${NOTI_BASE_DIR}/SampleApp/linux/sampleConsumer/SampleConsumer.cpp)
TARGET_LINK_LIBRARIES(${EX_NOTICONSUMER} ${OCLIB} ${OCTBSTACK} pthread)
INSTALL(TARGETS ${EX_NOTICONSUMER} DESTINATION ${BIN_INSTALL_DIR})
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# plugin-manager project build script
##
pmimpl = pmimpl_env.SharedLibrary('pmimpl', pmimpl_src)
plugin_manager_env.InstallTarget([ppm, pmimpl], 'libppm')
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
##
# Plugins build script
##
if target_os not in ['windows', 'winrt']:
plugins_env.AppendUnique(CXXFLAGS = ['-g3', '-Wall', '-pthread', '-std=c++0x'])
- plugins_env.PrependUnique(CCFLAGS = ['-fPIC'])
+ plugins_env.PrependUnique(CCFLAGS = ['-fPIC'])
plugins_env.AppendUnique(LINKFLAGS = ['-fPIC'])
if target_os not in ['arduino', 'android']:
lightserver = plugins_env.SharedLibrary('mqtt-light/lightserver_mqtt_plugin', mqtt_light_src)
SConscript('mqtt-fan/lib/SConscript')
+
cd ../../lib && $(MAKE) clean
rm -rf ./release/obj
cd ./release && rm -f *.so
+
cd ../../lib && $(MAKE) clean
rm -rf ./release/obj
cd ./release && rm -f *.so
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
##
#sample-app build script
##
'connectivity_abstraction', 'coap',
'ppm', 'pmimpl', 'dl'])
-if env.get('SECURED') == '1':
+if env.get('SECURED') == '1':
sample_env.AppendUnique(LIBS = ['tinydtls'])
sample_env.ParseConfig('pkg-config --libs glib-2.0')
Alias('mqttclient', mqttclient)
env.AppendTarget('mqttclient')
+
rm -f *.o
rm -f *.so
rm -f mqttclient
+
if (eCode == OC_STACK_OK)
{
std::cout << "OBSERVE RESULT:" << std::endl;
- std::cout << "\tSequenceNumber: " << sequenceNumber << endl;
+ std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl;
rep.getValue("state", myfan.m_state);
rep.getValue("power", myfan.m_power);
}
if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
- std::cout << endl << "Observe is used." << endl << endl;
+ std::cout << std::endl << "Observe is used." << std::endl << std::endl;
else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
- std::cout << endl << "ObserveAll is used." << endl << endl;
+ std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;
//curFanResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve);
}
catch (std::exception &e)
{
- //log(e.what());
+ std::cout<<"Exception in foundResourceFan: "<<e.what()<<std::endl;
}
}
}
catch (std::exception &e)
{
- //log(e.what());
+ std::cout<<"Exception in foundResourceLight:" <<e.what() << std::endl;
}
}
}
catch (OCException &e)
{
- //log(e.what());
+ std::cout<<"Exception in main: "<<e.what() << std::endl;
}
return 0;
}
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# soft-sensor-manager project build script
##
libssmsdk = sdk_env.StaticLibrary(
target = 'libSSMSDK',
source = [ssm_sdk_cpp_src]
- )
+ )
sdk_env.InstallTarget(libssmsdk, 'libSSMCORE')
######################################################################
Command("THSensorApp","SampleApp/linux/THSensorApp/THSensorApp", Copy("$TARGET", "$SOURCE"))
Command("THSensorApp1","SampleApp/linux/THSensorApp1/THSensorApp1", Copy("$TARGET", "$SOURCE"))
+
rm -f -v *.o ${TARGET}
rm -rf ./${RST_NAME}
+
#endif // __cplusplus
#endif
+
if (reportReceiver != NULL)
g_objReportReceiver = env->NewGlobalRef(reportReceiver);
}
+
}
#endif
-#endif
\ No newline at end of file
+#endif
+
if (requestFlag & RequestHandlerFlag::RequestFlag)
{
- cout << "\t\trequestFlag : Request\n";
+ std::cout << "\t\trequestFlag : Request\n";
// If the request type is GET
if (requestType == "GET")
legacy_clean:
@rm -rf bin
@rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
+
return 0;
}
#endif //ARDUINOWIFI
+
legacy_clean:
@rm -rf bin
@rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
+
legacy_clean:
@rm -rf bin
@rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
+
legacy_clean:
@rm -rf bin
@rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
+
float calculateDistance(float avgRSSI, float txPower);
#endif /* PROXIMITY_H_ */
+
#endif /* TRACKEE_H_ */
+
return 0;
}
#endif //ARDUINOWIFI
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# linux sample app build script
##
linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
linux_sample_env.AppendUnique(LIBS = ['libSSMSDK'])
-#linux_sample_env.AppendUnique(LIBS = ['libSSMCORE'])
linux_sample_env.AppendUnique(LIBS = ['libSSMCore'])
linux_sample_env.AppendUnique(LIBS = ['pthread'])
linux_sample_env.AppendUnique(LIBS = ['oc'])
ssmtesterapp = linux_sample_env.Program('SSMTesterApp', 'src/SSMTestApp.cpp')
Alias("ssmtesterapp_sample", ssmtesterapp)
env.AppendTarget('SSMTesterApp')
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# linux sample app build script
##
thsensorapp = linux_sample_env.Program('THSensorApp', 'src/ThingResourceServer.cpp')
Alias("thsensorapp_sample", thsensorapp)
env.AppendTarget('thsensorapp_sample')
+
rm -f -v *.o ${TARGET}
rm -rf ./${RST_NAME}
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# linux sample app build script
##
linux_sample_env.AppendUnique(LIBS = ['pthread'])
linux_sample_env.AppendUnique(LIBS = ['connectivity_abstraction'])
linux_sample_env.AppendUnique(LIBS = ['coap'])
-if lib_env.get('SECURED') == '1':
+if lib_env.get('SECURED') == '1':
linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
linux_sample_env.ParseConfig('pkg-config --libs glib-2.0')
thsensorapp1 = linux_sample_env.Program('THSensorApp1', 'src/ThingResourceServer1.cpp')
Alias("thsensorapp1_sample", thsensorapp1)
env.AppendTarget('thsensorapp1_sample')
+
rm -f -v *.o ${TARGET}
rm -rf ./${RST_NAME}
+
│  └── OCServer.cpp :: TODO :: Unused remove??
└── README - You are reading this.
+
5. To run simpleServer do \91./simpleServer\92 and to run simpleClient do \91./simpleClient\92.
+
cd csdk && $(MAKE) deepclean
clean_legacy:
-rm -f -v OCLib.a *.o simpleserver simpleclient simpleclientserver
+
#INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${PKGNAME}.png DESTINATION "/usr/share/icons/default/small")
INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${PKGNAME}.xml DESTINATION "/usr/share/packages")
INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${PKGNAME}.rule DESTINATION /etc/smack/accesses2.d)
+
com.samsung.ssmtester system::use_internet r
system::use_internet com.samsung.ssmtester r
+
<label>SSM test</label>
</ui-application>
</manifest>
+
#endif //__OICAPP_LOG_H__
+
return appcore_efl_main(PACKAGE, &argc, &argv, &ops);
}
+
#endif //__OICAPP_TEST_H__
+
#endif //__OICAPP_UTILS_H__
+
<domain name="_"/>
</request>
</manifest>
+
/usr/share/*
/etc/smack/accesses2.d/com.samsung.ssmtester.rule
#%%license LICENSE.APLv2
+
;
#endif /* DISCOMFORTINDEXSENSOR_H_ */
+
;
#endif /* INDOORTRAJECTORYSENSOR_H_ */
+
printf("Conversion_DataFormat() is Successful.\n");
}
+
ADD_SUBDIRECTORY(ClientApp)
ADD_SUBDIRECTORY(THSensorApp)
ADD_SUBDIRECTORY(THSensorApp1)
+
TARGET_LINK_LIBRARIES(${SS_SAMPLE_THSEN} ${SS_SDK} ${OCLIB} ${OCTBSTACK} pthread)
INSTALL(TARGETS ${SS_SAMPLE_THSEN} DESTINATION ${BIN_INSTALL_DIR})
+
TARGET_LINK_LIBRARIES(${SS_SAMPLE_THSEN1} ${SS_SDK} ${OCLIB} ${OCTBSTACK} pthread)
INSTALL(TARGETS ${SS_SAMPLE_THSEN1} DESTINATION ${BIN_INSTALL_DIR})
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# things_manager project build script
##
#Go to build sample apps
SConscript('sampleapp/SConscript')
+
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# sampleapp build script
##
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# linux sample app build script
##
linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
linux_sample_env.AppendUnique(LIBS = ['libTGMSDKLibrary', 'oc', 'octbstack',
- 'connectivity_abstraction',
- 'libcoap', 'liboc_logger', 'dl', 'pthread'])
-if env.get('SECURED') == '1':
+ 'connectivity_abstraction',
+ 'libcoap', 'liboc_logger', 'dl', 'pthread'])
+if env.get('SECURED') == '1':
linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
linux_sample_env.ParseConfig('pkg-config --libs glib-2.0')
env.AppendTarget('ConServerApp')
env.AppendTarget('ConClientApp')
env.AppendTarget('BootstrapServerApp')
+
// When OCPlatform destructor is invoked, internally we do platform cleanup
}
+
#dep:
# gccmakedep $(SRCS)
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# linux sample app build script
##
'connectivity_abstraction',
'libcoap', 'liboc_logger', 'dl', 'pthread'])
-if env.get('SECURED') == '1':
- linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
+if env.get('SECURED') == '1':
+ linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
linux_sample_env.ParseConfig('pkg-config --libs glib-2.0')
env.AppendTarget('GroupServerApp')
env.AppendTarget('LightServerApp')
env.AppendTarget('BookmarkApp')
+
rm -f groupclient
rm -f lightserver
rm -f bookmark
+
+#******************************************************************
+#
+# Copyright 2014 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
##
# linux sample app build script
##
'connectivity_abstraction',
'libcoap', 'liboc_logger', 'dl', 'pthread'])
-if env.get('SECURED') == '1':
- linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
+if env.get('SECURED') == '1':
+ linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
linux_sample_env.ParseConfig('pkg-config --libs glib-2.0')
env.AppendTarget('MusicplayerApp')
env.AppendTarget('PhoneApp')
env.AppendTarget('SpeakerApp')
+
rm -f -v *.o ${TARGET2}
rm -f -v *.o ${TARGET3}
rm -f -v *.o ${TARGET4}
+
clean:
rm -f -v *.o ${TARGET}
+
namespace OIC
{
+ using std::cout;
+ using std::endl;
GroupSynchronization* GroupSynchronization::groupSyncnstance = NULL;
GroupSynchronization* GroupSynchronization::getInstance()
} catch(OCException &e) {
return OC_STACK_INVALID_PARAM;
-
+
}
cout << "GroupSynchronization::joinGroup : "
<< "To bind collectionResHandle and resourceHandle" << endl;
<< endl;
return result;
}
- } catch(OCException &e)
+ } catch(OCException &e)
{
cout << "ERROR : " << e.reason() << endl;
return OC_STACK_NO_RESOURCE;
}
}
}
+
};
}
#endif // __OC_GROUPSYNCHRONIZATION__
+
return g_groupmanager->findCandidateResources(type, &onFoundBootstrapServer);
}
}
+
+#******************************************************************
+#
+# Copyright 2014 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 script manages third party libraries
#
Import('env')
lib_env.AppendUnique(LIBPATH = env.get('BUILD_DIR'))
+