--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
+