{\r
switch (type) {\r
case 0:\r
- return OCConnectivityType::OC_IPV4;\r
+ return OCConnectivityType::CT_DEFAULT;\r
case 1:\r
- return OCConnectivityType::OC_IPV6;\r
+ return OCConnectivityType::CT_ADAPTER_IP;\r
case 2:\r
- return OCConnectivityType::OC_EDR;\r
+ return OCConnectivityType::CT_ADAPTER_RFCOMM_BTEDR;\r
case 3:\r
- return OCConnectivityType::OC_LE;\r
- case 4:\r
- return OCConnectivityType::OC_ALL;\r
+ return OCConnectivityType::CT_ADAPTER_GATT_BTLE;\r
default:\r
ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected connectivity type");\r
- return OCConnectivityType::OC_ALL;\r
+ return OCConnectivityType::CT_DEFAULT;\r
};\r
}\r
\r
{
m_resourceMap.clear();
- OC::OCPlatform::findResource("", OC_WELL_KNOWN_QUERY, OC_ALL, m_findCB);
+ OC::OCPlatform::findResource("", OC_WELL_KNOWN_QUERY, CT_DEFAULT, m_findCB);
}
void MiddleClient::foundOCResource(shared_ptr<OCResource> resource)
print 'Unzipping android lib...'
env.UnpackAll(androidlib_dir, androidlib_zip)
print 'Unzipping android lib complete'
-
+
# Remove downloaded file
# os.remove(androidlib_zip_file)
else:
if build_sample == 'ON':
if target_os in ['linux', 'arduino', 'android']:
env.SConscript('./samples/' + target_os + '/SConscript')
-
+
*/
typedef char *CAToken_t;
-/**
- * @enum CATransportType_t
- * @brief Different connectivities that are handled in Connectivity Abstraction
- */
+// The following flags are the same as the equivalent OIC values in
+// octypes.h, allowing direct copying with slight fixup.
+// The CA layer should used the OC types when build allows that.
+#define MAX_ADDR_STR_SIZE_CA (40)
+
+typedef enum
+{
+ CA_DEFAULT_ADAPTER = 0,
+
+ // value zero indicates discovery
+ CA_ADAPTER_IP = (1 << 0), // IPv4 and IPv6, including 6LoWPAN
+ CA_ADAPTER_GATT_BTLE = (1 << 1), // GATT over Bluetooth LE
+ CA_ADAPTER_RFCOMM_BTEDR = (1 << 2), // RFCOMM over Bluetooth EDR
+} CATransportAdapter_t;
+
typedef enum
{
- CA_IPV4 = (1 << 0), /**< IPV4 Transport Type */
- CA_IPV6 = (1 << 1), /**< IPV6 Transport Type */
- CA_EDR = (1 << 2), /**< EDR Transport Type */
- CA_LE = (1 << 3) /**< LE Transport Type */
-} CATransportType_t;
+ CA_DEFAULT_FLAGS = 0,
+
+ // Insecure transport is the default (subject to change)
+ CA_SECURE = (1 << 4), // secure the transport path
+ // IPv4 & IPv6 autoselection is the default
+ CA_IPV6 = (1 << 5), // IP adapter only
+ CA_IPV4 = (1 << 6), // IP adapter only
+ // Link-Local multicast is the default multicast scope for IPv6.
+ // These correspond in both value and position to the IPv6 address bits.
+ CA_SCOPE_INTERFACE = 0x1, // IPv6 Interface-Local scope
+ CA_SCOPE_LINK = 0x2, // IPv6 Link-Local scope (default)
+ CA_SCOPE_REALM = 0x3, // IPv6 Realm-Local scope
+ CA_SCOPE_ADMIN = 0x4, // IPv6 Admin-Local scope
+ CA_SCOPE_SITE = 0x5, // IPv6 Site-Local scope
+ CA_SCOPE_ORG = 0x8, // IPv6 Organization-Local scope
+ CA_SCOPE_GLOBAL = 0xE, // IPv6 Global scope
+} CATransportFlags_t;
/**
* @enum CANetworkStatus_t
CA_INTERFACE_UP /**< Connection is Available */
} CANetworkStatus_t;
-/**
- * @brief Address of the local or remote endpoint
- */
-typedef union
-{
- /**
- * @brief BT Mac Information
- */
- struct
- {
- char btMacAddress[CA_MACADDR_SIZE]; /**< BT mac address **/
- } BT;
-
- /**
- * @brief LE MAC Information
- */
- struct
- {
- char leMacAddress[CA_MACADDR_SIZE]; /**< BLE mac address **/
- } LE;
-
- /**
- * @brief IP Information
- */
- struct
- {
- char ipAddress[CA_IPADDR_SIZE]; /**< Ip address of the interface**/
- uint16_t port; /**< port information**/
- } IP;
-} CAAddress_t;
-
/*
* @brief remoteEndpoint identity
*/
{
uint16_t id_length;
unsigned char id[CA_MAX_ENDPOINT_IDENTITY_LEN];
-}CARemoteId_t;
+} CARemoteId_t;
/**
* @enum CAMessageType_t
} CAMethod_t;
/**
- * @brief Remote endpoint information for connectivities
+ * @brief Endpoint information for connectivities
+ * Must be identical to OCDevAddr.
*/
typedef struct
{
-
- CAURI_t resourceUri; /**< Resource URI information **/
- CAAddress_t addressInfo; /**< Remote Endpoint address **/
- CATransportType_t transportType; /**< Connectivity of the endpoint**/
- bool isSecured; /**< Secure connection**/
- CARemoteId_t identity; /**< Endpoint identity **/
-} CARemoteEndpoint_t;
-
-
-/**
- * @brief Group endpoint information for connectivities
- */
-typedef struct
-{
- CAURI_t resourceUri; /**< Resource URI information **/
- CATransportType_t transportType; /**< Transport type of the endpoint**/
-} CAGroupEndpoint_t;
-
-/**
- @brief Local Connectivity information
- */
-typedef struct
-{
- CAAddress_t addressInfo; /**< Address of the interface **/
- CATransportType_t type; /**< Transport type of local device **/
- bool isSecured; /**< Secure connection**/
-} CALocalConnectivity_t;
+ CATransportAdapter_t adapter; // adapter type
+ CATransportFlags_t flags; // transport modifiers
+ char addr[MAX_ADDR_STR_SIZE_CA]; // address for all
+ uint32_t interface; // usually zero for default interface
+ uint16_t port; // for IP
+ CARemoteId_t identity; // endpoint identity
+} CAEndpoint_t;
/**
* @enum CAResult_t
uint16_t optionID; /**< The header option ID which will be
added to communication packets */
uint16_t optionLength; /**< Option Length **/
- uint8_t optionData[CA_MAX_HEADER_OPTION_DATA_LENGTH]; /**< Optional data values**/
+ char optionData[CA_MAX_HEADER_OPTION_DATA_LENGTH]; /**< Optional data values**/
} CAHeaderOption_t;
/**
CAHeaderOption_t *options; /** Header Options for the request */
uint8_t numOptions; /**< Number of Header options */
CAPayload_t payload; /**< payload of the request */
+ CAURI_t resourceUri; /**< Resource URI information **/
} CAInfo_t;
/**
{
CAMethod_t method; /**< Name of the Method Allowed */
CAInfo_t info; /**< Information of the request. */
+ bool isMulticast; /**< is multicast request */
} CARequestInfo_t;
/**
helpful to identify the error */
} CAErrorInfo_t;
+/**
+ * @brief Hold global variables for CA layer (also used by RI layer)
+ */
+typedef struct
+{
+ CATransportFlags_t serverFlags;
+ CATransportFlags_t clientFlags;
+} CAGlobals_t;
+
+extern CAGlobals_t caglobals;
+
#ifdef __cplusplus
} /* extern "C" */
#endif
-#endif /* CA_COMMON_H_ */
+#endif //#ifndef CA_COMMON_H_
* @param requestInfo [OUT] Info for resource model to understand about the request.
* @return NONE
*/
-typedef void (*CARequestCallback)(const CARemoteEndpoint_t *object,
+typedef void (*CARequestCallback)(const CAEndpoint_t *object,
const CARequestInfo_t *requestInfo);
/**
* @param responseInfo [OUT] Identifier which needs to be mapped with response.
* @return NONE
*/
-typedef void (*CAResponseCallback)(const CARemoteEndpoint_t *object,
+typedef void (*CAResponseCallback)(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo);
/**
* @brief Callback function type for error
* @param errorInfo [OUT] CA Error information
* @return NONE
*/
-typedef void (*CAErrorCallback)(const CARemoteEndpoint_t *object,
+typedef void (*CAErrorCallback)(const CAEndpoint_t *object,
const CAErrorInfo_t *errorInfo);
#ifdef __WITH_DTLS__
#endif //__WITH_DTLS__
/**
- * @brief Create a Remote endpoint if the URI is available already.
- * This is a Helper function which can be used before calling
- * CASendRequest / CASendNotification.
- * @param uri [IN] Absolute URI of the resource to be used to generate the
- * Remote endpoint
- * \n For ex : coap://10.11.12.13:4545/resource_uri ( for IP)
- * \n coap://10:11:12:13:45:45/resource_uri ( for BT)
- * @param transportType [IN] Transport type of the endpoint
- * @param object [OUT] Endpoint object which contains the above parsed data
+ * @brief Create an endpoint description
+ * @param flags [IN] how the adapter should be used
+ * @param adapter [IN] which adapter to use
+ * @param addr [IN] string representation of address
+ * @param port [IN] port (for IP_ADAPTER)
+ * @param endpoint [OUT] Endpoint which contains the above
* @return #CA_STATUS_OK or #CA_STATUS_FAILED
- * @remark The created Remote endpoint can be freed using CADestroyRemoteEndpoint() API.
- * @see CADestroyRemoteEndpoint
+ * @remark The created Remote endpoint can be freed using CADestroyEndpoint().
+ * @see CADestroyEndpoint
*/
-CAResult_t CACreateRemoteEndpoint(const CAURI_t uri,
- const CATransportType_t transportType,
- CARemoteEndpoint_t **object);
+CAResult_t CACreateEndpoint(CATransportFlags_t flags,
+ CATransportAdapter_t adapter,
+ const char *addr,
+ uint16_t port,
+ CAEndpoint_t **object);
/**
* @brief Destroy the remote endpoint created
- * @param object [IN] Remote Endpoint object created with CACreateRemoteEndpoint
+ * @param object [IN] Remote Endpoint object created with CACreateEndpoint
* @return NONE
*/
-void CADestroyRemoteEndpoint(CARemoteEndpoint_t *object);
+void CADestroyEndpoint(CAEndpoint_t *object);
/**
* @brief Generating the token for matching the request and response.
void CADestroyToken(CAToken_t token);
/**
- * @brief Find the resource in the network. This API internally sends multicast messages on all
- * selected connectivity adapters. Responses are delivered via response callbacks.
- *
- * @param resourceUri [IN] Uri to send multicast search request. Must contain only relative
- * path of Uri to be search.
- * @param token [IN] Token for the request
- * @param tokenLength [IN] length of the token
- * @return #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_STATUS_NOT_INITIALIZED
- */
-CAResult_t CAFindResource(const CAURI_t resourceUri, const CAToken_t token, uint8_t tokenLength);
-
-/**
* @brief Send control Request on a resource
- * @param object [IN] Remote Endpoint where the payload need to be sent.
- * This Remote endpoint is delivered with Request or response callback.
+ * @param object [IN] Endpoint where the payload need to be sent.
+ * This endpoint is delivered with Request or response callback.
* @param requestInfo [IN] Information for the request.
* @return #CA_STATUS_OK #CA_STATUS_FAILED #CA_MEMORY_ALLOC_FAILED
*/
-CAResult_t CASendRequest(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
-
-/**
- * @brief Send control Request on a resource to multicast group
- * @param object [IN] Group Endpoint where the payload need to be sent.
- * This Remote endpoint is delivered with Request or response callback.
- * @param requestInfo [IN] Information for the request.
- * @return #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
- */
-CAResult_t CASendRequestToAll(const CAGroupEndpoint_t *object,
- const CARequestInfo_t *requestInfo);
+CAResult_t CASendRequest(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
/**
* @brief Send the response
- * @param object [IN] Remote Endpoint where the payload need to be sent.
- * This Remote endpoint is delivered with Request or response callback
+ * @param object [IN] Endpoint where the payload need to be sent.
+ * This endpoint is delivered with Request or response callback
* @param responseInfo [IN] Information for the response
* @return #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
*/
-CAResult_t CASendResponse(const CARemoteEndpoint_t *object,
- const CAResponseInfo_t *responseInfo);
+CAResult_t CASendResponse(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
/**
* @brief Send notification to the remote object
- * @param object [IN] Remote Endpoint where the payload need to be sent.
- * This Remote endpoint is delivered with Request or response callback.
+ * @param object [IN] Endpoint where the payload need to be sent.
+ * This endpoint is delivered with Request or response callback.
* @param responseInfo [IN] Information for the response.
* @return #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
*/
-CAResult_t CASendNotification(const CARemoteEndpoint_t *object,
+CAResult_t CASendNotification(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo);
/**
- * @brief To advertise the resource
- * @param resourceUri [IN] URI to be advertised
- * @param token [IN] Token for the request
- * @param tokenLength [IN] length of the token
- * @param options [IN] Header options information
- * @param numOptions [IN] Number of options
- * @return #CA_STATUS_OK or #CA_STATUS_FAILED or
- * #CA_MEMORY_ALLOC_FAILED or #CA_STATUS_NOT_INITIALIZED
- */
-CAResult_t CAAdvertiseResource(const CAURI_t resourceUri,const CAToken_t token,
- uint8_t tokenLength, const CAHeaderOption_t *options,
- const uint8_t numOptions);
-
-/**
* @brief Select network to use
* @param interestedNetwork [IN] Connectivity Type enum
* @return #CA_STATUS_OK or #CA_NOT_SUPPORTED or #CA_STATUS_FAILED or #CA_NOT_SUPPORTED
* @return #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_STATUS_INVALID_PARAM or
* #CA_MEMORY_ALLOC_FAILED
*/
-CAResult_t CAGetNetworkInformation(CALocalConnectivity_t **info, uint32_t *size);
+CAResult_t CAGetNetworkInformation(CAEndpoint_t **info, uint32_t *size);
/**
* @brief To Handle the Request or Response
* 'ID of new device(Resource Server)',
* 'ID of owner smart-phone(Provisioning Server)')
*
- * @param[IN] addrInfo information of network address
- * @param[IN] transportType transport type
+ * @param[IN] endpoint information of network address
* @param[IN] label Ownership transfer method e.g)"oic.sec.doxm.jw"
* @param[IN] labelLen Byte length of label
* @param[IN] rsrcServerDeviceID ID of new device(Resource Server)
* @retval CA_STATUS_OK Successful
* @retval CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAGenerateOwnerPSK(const CAAddress_t* addrInfo,
- const CATransportType_t transportType,
+CAResult_t CAGenerateOwnerPSK(const CAEndpoint_t *endpoint,
const uint8_t* label, const size_t labelLen,
const uint8_t* rsrcServerDeviceID,
const size_t rsrcServerDeviceIDLen,
/**
* Initiate DTLS handshake with selected cipher suite
*
- * @param[IN] addrInfo information of network address
- * @param[IN] transportType transport type
+ * @param[IN] endpoint information of network address
*
* @retval CA_STATUS_OK Successful
* @retval CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAInitiateHandshake(const CAAddress_t* addrInfo,
- const CATransportType_t transportType);
+CAResult_t CAInitiateHandshake(const CAEndpoint_t *endpoint);
/**
* Close the DTLS session
*
- * @param[IN] addrInfo information of network address
- * @param[IN] transportType transport type
+ * @param[IN] endpoint information of network address
*
* @retval CA_STATUS_OK Successful
* @retval CA_STATUS_FAILED Operation failed
*/
-CAResult_t CACloseDtlsSession(const CAAddress_t* addrInfo,
- const CATransportType_t transportType);
-
+CAResult_t CACloseDtlsSession(const CAEndpoint_t *endpoint);
#endif /* __WITH_DTLS__ */
* @param dataLen [IN] Size of data to be sent.
* @return The number of bytes sent on the network. Return value equal to -1 indicates error.
*/
-typedef int32_t (*CAAdapterSendUnicastData)(const CARemoteEndpoint_t *endpoint,
- const void *data, uint32_t dataLen);
+typedef int32_t (*CAAdapterSendUnicastData)(const CAEndpoint_t *endpoint,
+ const void *data, uint32_t dataLen);
/**
* @brief Sends Multicast data to the endpoint using the adapter connectivity.
* Note: length must be > 0.
+ * @param endpoint [IN] Remote Endpoint information (like ipaddress , port,
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
* @return The number of bytes sent on the network. Return value equal to -1 indicates error.
*/
-typedef int32_t (*CAAdapterSendMulticastData)(const void *data, uint32_t dataLen);
+typedef int32_t (*CAAdapterSendMulticastData)(const CAEndpoint_t *endpoint,
+ const void *data, uint32_t dataLen);
/**
* @brief Get Network Information
* @param size [OUT] Number of local connectivity structures.
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-typedef CAResult_t (*CAAdapterGetNetworkInfo)(CALocalConnectivity_t **info, uint32_t *size);
+typedef CAResult_t (*CAAdapterGetNetworkInfo)(CAEndpoint_t **info, uint32_t *size);
/**
* @brief Read Synchronous API callback.
/**
* @brief This will be used during the registration of adapters call backs to the common logic
- * @see CAConnectivityHandler_t , CATransportType_t
+ * @see CAConnectivityHandler_t , CATransportAdapter_t
*/
typedef void (*CARegisterConnectivityCallback)(CAConnectivityHandler_t handler,
- CATransportType_t cType);
+ CATransportAdapter_t cType);
/**
* @brief This will be used during the recive of network requests and response.
* @see SendUnicastData(), SendMulticastData()
*/
-typedef void (*CANetworkPacketReceivedCallback)(CARemoteEndpoint_t *endPoint, void *data,
+typedef void (*CANetworkPacketReceivedCallback)(const CAEndpoint_t *endPoint, void *data,
uint32_t dataLen);
/**
* @brief This will be used to notify network changes to the connectivity common logic layer
* @see SendUnicastData(), SendMulticastData()
*/
-typedef void (*CANetworkChangeCallback)(CALocalConnectivity_t *info, CANetworkStatus_t status);
+typedef void (*CANetworkChangeCallback)(const CAEndpoint_t *info, CANetworkStatus_t status);
/**
* @brief This will be used to notify error result to the connectivity common logic layer
*/
-typedef void (*CAErrorHandleCallback)(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
- uint32_t dataLen, CAResult_t result);
+typedef void (*CAErrorHandleCallback)(const CAEndpoint_t *endpoint,
+ const void *data, uint32_t dataLen,
+ CAResult_t result);
#ifdef __cplusplus
} /* extern "C" */
*/
extern void OCGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo);
-typedef void (*CAPacketReceivedCallback)(const char *ipAddress, const uint16_t port,
- const void *data, const uint32_t dataLength,
- const bool isSecured, const CARemoteId_t *identity);
+typedef void (*CAPacketReceivedCallback)(const CAEndpoint_t *endpoint,
+ const void *data, uint32_t dataLength);
-typedef uint32_t (*CAPacketSendCallback)(const char *ipAddress, const uint16_t port,
- const void *data, const uint32_t dataLength);
+typedef uint32_t (*CAPacketSendCallback)(const CAEndpoint_t *endpoint,
+ const void *data, uint32_t dataLength);
/**
* @struct stCAAdapterCallbacks_t
/**
- * @struct stCADtlsPeerInfo_t
- * @brief structure associates the peer psk id with peer n/w address
- */
-typedef struct stCADtlsPeerInfo
-{
- CAAddress_t address;
- CARemoteId_t identity;
-}stCADtlsPeerInfo_t;
-
-
-/**
* @fn CADTLSSetAdapterCallbacks
* @brief Used set send and recv callbacks for different adapters(WIFI,EtherNet)
*
*
*/
void CADTLSSetAdapterCallbacks(CAPacketReceivedCallback recvCallback,
- CAPacketSendCallback sendCallback, CATransportType_t type);
+ CAPacketSendCallback sendCallback,
+ CATransportAdapter_t type);
/**
* @brief Register callback to get DTLS PSK credentials.
/**
* Initiate DTLS handshake with selected cipher suite
*
- * @param[in] addrInfo information of network address
- * @param[in] transportType transport type
+ * @param[in] endpoint information of network address
*
* @retval CA_STATUS_OK for success, otherwise some error value
*/
-CAResult_t CADtlsInitiateHandshake(const CAAddress_t* addrInfo,
- const CATransportType_t transportType);
+CAResult_t CADtlsInitiateHandshake(const CAEndpoint_t *endpoint);
/**
* Close the DTLS session
*
- * @param[in] addrInfo information of network address
- * @param[in] transportType transport type
+ * @param[in] endpoint information of network address
*
* @retval CA_STATUS_OK for success, otherwise some error value
*/
-CAResult_t CADtlsClose(const CAAddress_t* addrInfo,
- const CATransportType_t transportType);
+CAResult_t CADtlsClose(const CAEndpoint_t *endpoint);
/**
* Generate ownerPSK using PRF
* 'ID of new device(Resource Server)',
* 'ID of owner smart-phone(Provisioning Server)')
*
- * @param[in] addrInfo information of network address
- * @param[in] transportType transport type
+ * @param[in] endpoint information of network address
* @param[in] label Ownership transfer method e.g)"oic.sec.doxm.jw"
* @param[in] labelLen Byte length of label
* @param[in] rsrcServerDeviceID ID of new device(Resource Server)
*
* @retval CA_STATUS_OK for success, otherwise some error value
*/
-CAResult_t CADtlsGenerateOwnerPSK(const CAAddress_t* addrInfo,
- const CATransportType_t transportType,
+CAResult_t CADtlsGenerateOwnerPSK(const CAEndpoint_t *endpoint,
const uint8_t* label, const size_t labelLen,
const uint8_t* rsrcServerDeviceID, const size_t rsrcServerDeviceIDLen,
const uint8_t* provServerDeviceID, const size_t provServerDeviceIDLen,
* a new DTLS handshake is started, pdu info is
* cached to be send when session setup is finished.
*
- * @param[in] remoteAddress address to which data will be sent.
+ * @param[in] endpoint address to which data will be sent.
* @param[in] port port to which data will be sent.
* @param[in] data length of data.
* @param[in] dataLen length of given data
- * @param[in] type transport at which packet needs to be send
*
* @return 0 on success otherwise a positive error value.
* @retval CA_STATUS_OK Successful
*
*/
-CAResult_t CAAdapterNetDtlsEncrypt(const char *remoteAddress,
- const uint16_t port,
+CAResult_t CAAdapterNetDtlsEncrypt(const CAEndpoint_t *endpoint,
void *data,
- uint32_t dataLen,
- CATransportType_t type);
+ uint32_t dataLen);
/**
* @fn CAAdapterNetDtlsDecrypt
* @retval CA_STATUS_FAILED Operation failed
*
*/
-CAResult_t CAAdapterNetDtlsDecrypt(const char *remoteAddress,
- const uint16_t port,
+CAResult_t CAAdapterNetDtlsDecrypt(const CAEndpoint_t *endpoint,
uint8_t *data,
- uint32_t dataLen,
- CATransportType_t type);
+ uint32_t dataLen);
#endif /* CA_ADAPTER_NET_DTLS_H_ */
#include <jni.h>
#endif
+#ifndef WITH_ARDUINO
+#include <sys/socket.h>
+#endif
+
#include "cacommon.h"
#include "logger.h"
#include "pdu.h"
typedef struct
{
int socketFd; /**< Socket decriptor **/
- char ipAddress[CA_IPADDR_SIZE]; /**< Address of the ip **/
- uint16_t port; /**< Server port number **/
- bool isSecured; /**< Indicates secured server **/
+ CAEndpoint_t endpoint; /**< endpoint description **/
bool isServerStarted; /**< Indicates server started **/
bool isMulticastServer; /**< Indicates multicast server **/
char ifAddr[CA_IPADDR_SIZE]; /**< Address of the multicast interface **/
void CALogPDUData(coap_pdu_t *pdu);
/**
- * @fn CAAdapterCreateLocalEndpoint
- * @brief Create CALocalConnectivity_t instance.
- */
-CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CATransportType_t type, const char *address);
-
-/**
- * @fn CAAdapterCopyLocalEndpoint
- * @brief Create CALocalConnectivity_t duplicate instance.
- */
-CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(const CALocalConnectivity_t *connectivity);
-
-/**
- * @fn CAAdapterFreeLocalEndpoint
- * @brief Deallocate CALocalConnectivity_t instance.
- */
-void CAAdapterFreeLocalEndpoint(CALocalConnectivity_t *localEndPoint);
-
-/**
- * @fn CAAdapterCreateRemoteEndpoint
- * @brief Allocate CARemoteEndpoint_t instance.
+ * @fn CAAdapterCloneEndpoint
+ * @brief Create CAEndpoint_t duplicate instance.
*/
-CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CATransportType_t type, const char *address,
- const char *resourceUri);
+CAEndpoint_t *CAAdapterCloneEndpoint(const CAEndpoint_t *endpoint);
/**
- * @fn CAAdapterCopyRemoteEndpoint
- * @brief Create CARemoteEndpoint_t duplicate instance.
+ * @fn CAAdapterFreeEndpoint
+ * @brief Deallocate CAEndpoint_t instance.
*/
-CARemoteEndpoint_t *CAAdapterCopyRemoteEndpoint(
- const CARemoteEndpoint_t *remoteEndpoint);
+void CAAdapterFreeEndpoint(CAEndpoint_t *localEndPoint);
/**
- * @fn CAAdapterFreeRemoteEndpoint
- * @brief Deallocate CARemoteEndpoint_t instance.
+ * @fn CAAdapterCreateEndpoint
+ * @brief Allocate CAEndpoint_t instance.
*/
-void CAAdapterFreeRemoteEndpoint(CARemoteEndpoint_t *remoteEndPoint);
+CAEndpoint_t *CAAdapterCreateEndpoint(CATransportFlags_t flags,
+ CATransportAdapter_t adapter, const char *address, uint16_t port);
/**
* @fn CAParseIPv4AddressInternal
* @brief Used to get the socket fd for given server information.
*
* @param serverInfoList [IN] Server information list.
- * @param ipAddress [IN] Ip address of the server.
- * @param isSecured [IN] To check whether it is secured server or not.
* @param isMulticast [IN] To check whether it is multicast server or not.
- * @param type [IN] CA_IPV4, CA_IPV6 etc.
+ * @param endpoint [IN] network address
* @return positive value on success and -1 on error.
*/
-int CAGetSocketFdForUnicastServer(const u_arraylist_t *serverInfoList, const char *ipAddress,
- bool isSecured, bool isMulticast, CATransportType_t type);
+int CAGetSocketFdForUnicastServer(const u_arraylist_t *serverInfoList,
+ bool isMulticast, const CAEndpoint_t *endpoint);
/**
* @brief Used to add the server information into serverinfo list
*/
void CAClearServerInfoList(u_arraylist_t *serverInfoList);
+/**
+ * @brief Convert address from binary to string
+ * @param ipaddr [IN] IP address info
+ * @param host [OUT] address string (must be CA_IPADDR_SIZE)
+ * @param port [OUT] host order port number
+ */
+void CAConvertAddrToName(const struct sockaddr_storage *sockaddr, char *host, uint16_t *port);
+
+/**
+ * @brief Convert address from string to binary
+ * @param host [IN] address string
+ * @param port [IN] host order port number
+ * @param ipaddr [OUT] IP address info
+ */
+void CAConvertNameToAddr(const char *host, uint16_t port, struct sockaddr_storage *sockaddr);
+
#ifdef __ANDROID__
/**
* @fn CANativeJNISetContext
/**
* @brief Sends data to the peer bluetooth OIC device using the adapter connectivity.
- * @param remoteEndpoint [IN] Remote Endpoint information (like ipaddress, port, reference uri and
+ * @param endpoint [IN] Remote Endpoint information (like ipaddress, port, and
* connectivity type) to which the unicast data has to be sent.
* @param data [IN] Data to be sent.
* @param dataLength [IN] Size of data to be sent.
* @return The number of bytes sent on the network. Returns -1 on error.
*
*/
-int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+int32_t CASendEDRUnicastData(const CAEndpoint_t *endpoint, const void *data,
uint32_t dataLength);
/**
* @brief Sends multicast data to all discovered bluetooth OIC devices using the adapter
- * connectivity.
- * @param data [IN] Data which needs to be sent to all discovered bluetooth OIC device.
- * @param dataLength [IN] Length of data in bytes.
+ * @param endpoint [IN] Remote Endpoint information (like ipaddress, port, and connectivity.
+ * @param data [IN] Data which needs to be sent to all discovered bluetooth OIC device.
+ * @param dataLength [IN] Length of data in bytes.
* @return Number of bytes sent on the network. Returns -1 on error.
*/
-int32_t CASendEDRMulticastData(const void *data, uint32_t dataLength);
+int32_t CASendEDRMulticastData(const CAEndpoint_t *endpoint, const void *data,
+ uint32_t dataLength);
/**
* @brief Get EDR Connectivity network information.
*
* @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+CAResult_t CAGetEDRInterfaceInformation(CAEndpoint_t **info, uint32_t *size);
/**
* @brief Read Synchronous API callback.
/**
* @brief Sends data to the peer bluetooth OIC device using the adapter connectivity.
- * @param remoteEndpoint [IN] Remote Endpoint information (like ipaddress, port, reference uri and
+ * @param endpoint [IN] Remote Endpoint information (like ipaddress, port, reference uri and
* connectivity type) to which the unicast data has to be sent.
* @param data [IN] Data to be sent.
* @param dataLength [IN] Size of data to be sent.
* @return Number of bytes sent on the network. Returns -1 on error.
*/
-int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+int32_t CASendEDRUnicastData(const CAEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
/**
* @retval #CA_STATUS_FAILED Operation failed
* @remarks info is allocated in this API and should be freed by the caller.
*/
-CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+CAResult_t CAGetEDRInterfaceInformation(CAEndpoint_t **info, uint32_t *size);
/**
* @brief Read Synchronous API callback.
*/
typedef struct
{
- CARemoteEndpoint_t *remoteEndpoint; /**< Remote Endpoint */
+ CAEndpoint_t *remoteEndpoint; /**< Remote Endpoint */
void *data; /**< Data to be sent */
uint32_t dataLen; /**< Length of the data to be sent */
} CAEDRData;
*/
typedef struct
{
- CALocalConnectivity_t *info; /**< Local Connectivity Information */
+ CAEndpoint_t *info; /**< Local Connectivity Information */
CANetworkStatus_t status; /**< Network Status */
} CAEDRNetworkEvent;
* @see #CALocalConnectivity_t
*
*/
-CAResult_t CAEDRGetInterfaceInformation(CALocalConnectivity_t **info);
+CAResult_t CAEDRGetInterfaceInformation(CAEndpoint_t **info);
/**
* @brief Start RFCOMM server for given service UUID
* @param transportType [IN] interested network for starting
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAStartAdapter(CATransportType_t transportType);
+CAResult_t CAStartAdapter(CATransportAdapter_t transportType);
/**
* @brief Stopping different connectivity adapters based on the network un-selection.
* @param transportType [IN] network type that want to stop
* @return none
*/
-void CAStopAdapter(CATransportType_t transportType);
+void CAStopAdapter(CATransportAdapter_t transportType);
/**
* @brief Get network information such as ipaddress and mac information
* @param size [OUT] number of connectivity information structures
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size);
+CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, uint32_t *size);
/**
* @brief Sends unicast data to the remote endpoint
* @param length [IN] length of the data that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length);
+CAResult_t CASendUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length);
/**
* @brief Sends multicast data to all endpoints in the network.
+ * @param endpoint [IN] endpoint information where the data has to be sent
* @param data [IN] data that needs to be sent
* @param length [IN] length of the data that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CASendMulticastData(const void *data, uint32_t length);
+CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length);
/**
* @brief Start listening servers to receive search requests from clients
#include "caadapterinterface.h"
-
#ifdef __cplusplus
extern "C"
{
/**
* @brief Starting different connectivity adapters based on the network selection.
- * @param transportType [IN] network type that want to stop
+ * @param transportAdapter [IN] network type that want to stop
* @return none
*/
-CAResult_t CAStartAdapter(CATransportType_t transportType);
+CAResult_t CAStartAdapter(CATransportAdapter_t transportType);
/**
* @brief Stopping different connectivity adapters based on the network un-selection.
- * @param transportType [IN] un selected network for stopping the packets transfer
+ * @param transportAdapter [IN] un selected network for stopping the packets transfer
* @return none
*/
-void CAStopAdapter(CATransportType_t transportType);
+void CAStopAdapter(CATransportAdapter_t transportType);
/**
* @brief Get network information such as ipaddress and mac information. Gets the network
* @param size [OUT] number of connectivity information structures
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size);
+CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, uint32_t *size);
/**
* @brief Sends unicast data to the remote endpoint
* @param length [IN] length of the data that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length);
+CAResult_t CASendUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length);
/**
* @brief Sends multicast data to all endpoints in the network.
+ * @param endpoint [IN] endpoint information where the data has to be sent
* @param data [IN] data that needs to be sent
* @param length [IN] length of the data that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CASendMulticastData(const void *data, uint32_t length);
+CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length);
/**
* @brief Start listening servers to receive search requests from clients
* @return The number of bytes sent on the network. Return value equal to -1 indicates error.
* @remarks dataLen must be > 0.
*/
-int32_t CASendIPUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+int32_t CASendIPUnicastData(const CAEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
* @brief Sends Multicast data to the endpoint using the IP connectivity.
+ * @param endpoint [IN] Remote Endpoint information (like ipaddress , port)
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
* @return The number of bytes sent on the network. Return value equal to -1 indicates error.
* @remarks dataLen must be > 0.
*/
-int32_t CASendIPMulticastData(const void *data, uint32_t dataLen);
+int32_t CASendIPMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen);
/**
* @brief Get IP Connectivity network information
* @return #CA_STATUS_OK or Appropriate error code
* @remarks info is allocated in this API and should be freed by the caller.
*/
-CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size);
/**
* @brief Read Synchronous API callback.
* @return The number of bytes sent on the network. Return value equal to -1 indicates error.
* @remark dataLen must be > 0.
*/
-int32_t CASendIPUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+int32_t CASendIPUnicastData(const CAEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
* @return The number of bytes sent on the network. Return value equal to -1 indicates error.
* @remark dataLen must be > 0.
*/
-int32_t CASendIPMulticastData(const void *data, uint32_t dataLen);
+int32_t CASendIPMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen);
/**
* @brief Get IP Connectivity network information
* @return #CA_STATUS_OK or Appropriate error code
* @remarks info is allocated in this API and should be freed by the caller.
*/
-CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size);
/**
* @brief Read Synchronous API callback.
/**
* @brief Callback to be notified on reception of any data from remote OIC devices.
*
- * @param ipAddress [IN] IP address of remote OIC device.
- * @param port [IN] Port number on which data is received.
+ * @param endpoint [IN] network endpoint description
* @param data [IN] Data received from remote OIC device.
* @param dataLength [IN] Length of data in bytes.
- * @param isSecured [IN] Indicates the data is secure or not.
- * @param identity [IN] Identity of the remote OIC device.
*
* @return NONE
* @pre Callback must be registered using CAIPSetPacketReceiveCallback()
*/
-typedef void (*CAIPPacketReceivedCallback)(const char *ipAddress, uint16_t port,
- const void *data, uint32_t dataLength,
- bool isSecured, const CARemoteId_t *identity);
+typedef void (*CAIPPacketReceivedCallback)(const CAEndpoint_t *endpoint,
+ const void *data,
+ uint32_t dataLength);
/**
* @brief Callback to be notified when exception occures on multicast/unicast server.
/**
* @brief API to send unicast UDP data
*
- * @param remoteAddress [IN] IP address to which data needs to be sent.
- * @param port [IN] Port to which data needs to be send.
+ * @param endpoint [IN] complete network address to send to
* @param data [IN] Data to be send.
* @param dataLength [IN] Length of data in bytes
* @param isMulticast [IN] Whether data needs to be sent to multicast ip
- * @param isSecured [IN] Whether data to be sent on secured channel.
*
* @return The number of bytes sent on the network. Returns 0 on error.
* @remarks isSecure will be ignored when isMulticast is true.
*/
-uint32_t CAIPSendData(const char *remoteAddress, uint16_t port, const void *data,
- uint32_t dataLength, bool isMulticast, bool isSecure);
+uint32_t CAIPSendData(const CAEndpoint_t *endpoint,
+ const void *data,
+ uint32_t dataLength,
+ bool isMulticast);
/**
* @brief Callback to be notified when IP adapter connection state changes.
*/
typedef struct
{
- CARemoteEndpoint_t
+ CAEndpoint_t
*remoteEndpoint; /**< Remote endpoint contains the inforamtion of remote device */
void *data; /**< Data to be transmitted over LE tranport */
uint32_t dataLen; /**< Length of the data being transmitted */
* @return The number of bytes sent on the network. Returns -1 on error.
* @remarks dataLen must be > 0.
*/
-int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
* @brief Sends Multicast data to the endpoint using the LE connectivity.
- * @param data [IN] Data which required to be sent.
- * @param dataLen [IN] Size of data to be sent.
+ * @param endpoint [IN] Remote Endpoint information to which the unicast data has to be sent.
+ * @param data [IN] Data which required to be sent.
+ * @param dataLen [IN] Size of data to be sent.
* @return The number of bytes sent on the network. Returns -1 on error.
* @remarks dataLen must be > 0.
*/
-int32_t CASendLEMulticastData(const void *data, uint32_t dataLen);
+int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen);
/**
* @brief Starts notification server on EDR adapters.
* @return The number of bytes sent on the network. Returns 0 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *data,
+uint32_t CASendLENotification(const CAEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
* @param size [OUT] Number of local connectivity structures.
* @return #CA_STATUS_OK or Appropriate error code
*/
-CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size);
/**
* @brief Read Synchronous API callback.
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CABLEServerSendData(const CARemoteEndpoint_t *remoteEndpoint,
+CAResult_t CABLEServerSendData(const CAEndpoint_t *remoteEndpoint,
const void *data, uint32_t dataLen);
/**
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
+CAResult_t CABLEClientSendData(const CAEndpoint_t *remoteEndpoint,
const void *data, uint32_t dataLen);
/**
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+CALEData_t *CACreateBLEData(const CAEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
/**
*/
typedef struct
{
- CARemoteEndpoint_t
- *remoteEndpoint; /**< Remote endpoint contains the inforamtion of remote device */
+ CAEndpoint_t *remoteEndpoint; /**< Remote endpoint contains the inforamtion of remote device */
void *data; /**< Data to be transmitted over LE tranport */
uint32_t dataLen; /**< Length of the data being transmitted */
} CALEData_t;
* @return The number of bytes sent on the network. Returns -1 on error.
* @remarks dataLen must be > 0.
*/
-int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
* @return The number of bytes sent on the network. Returns 0 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *data,
+uint32_t CASendLENotification(const CAEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
* @param size [OUT] Number of local connectivity structures.
* @return #CA_STATUS_OK or Appropriate error code
*/
-CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size);
/**
* @brief Read Synchronous API callback.
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CABLEServerSendData(const CARemoteEndpoint_t *remoteEndpoint,
+CAResult_t CABLEServerSendData(const CAEndpoint_t *remoteEndpoint,
const void *data, uint32_t dataLen);
/**
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
+CAResult_t CABLEClientSendData(const CAEndpoint_t *remoteEndpoint,
const void *data, uint32_t dataLen);
/**
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+CALEData_t *CACreateBLEData(const CAEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
/**
* @param request [IN] request that needs to be sent
* @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
*/
-CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *endpoint,
+CAResult_t CADetachRequestMessage(const CAEndpoint_t *endpoint,
const CARequestInfo_t *request);
/**
* @param request [IN] request that needs to be sent
* @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
*/
-CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
+CAResult_t CADetachRequestToAllMessage(const CAEndpoint_t *object,
const CARequestInfo_t *request);
/**
* @param response [IN] response that needs to be sent
* @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
*/
-CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *endpoint,
+CAResult_t CADetachResponseMessage(const CAEndpoint_t *endpoint,
const CAResponseInfo_t *response);
/**
* @param request [IN] request that needs to be sent
* @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
*/
-CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *endpoint,
+CAResult_t CADetachRequestMessage(const CAEndpoint_t *endpoint,
const CARequestInfo_t *request);
/**
* @param request [IN] request that needs to be sent
* @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
*/
-CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
+CAResult_t CADetachRequestToAllMessage(const CAEndpoint_t *object,
const CARequestInfo_t *request);
/**
* @param response [IN] response that needs to be sent
* @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
*/
-CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *endpoint,
+CAResult_t CADetachResponseMessage(const CAEndpoint_t *endpoint,
const CAResponseInfo_t *response);
/**
/**
* @brief Add network type to the selected networks for network packets reception
- * @param transportType [IN] Transport type that needs to be added
+ * @param transportAdapter [IN] Adapter that needs to be added
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAAddNetworkType(CATransportType_t transportType);
+CAResult_t CAAddNetworkType(CATransportAdapter_t transportAdapter);
/**
* @brief Remove network type from the selected configuration
- * @param transportType [IN] Transport type that needs to be removed
+ * @param transportAdapter [IN] Adapter that needs to be removed
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CARemoveNetworkType(CATransportType_t transportType);
+CAResult_t CARemoveNetworkType(CATransportAdapter_t transportAdapter);
/**
* @brief Get selected network information
* @param size [OUT] No Of Array objects
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_t *size);
+CAResult_t CAGetNetworkInformationInternal(CAEndpoint_t **info, uint32_t *size);
/**
* @brief Terminate network type from selected configuration
/**
* @brief generates pdu structure from the given information.
- * @param uri [IN] uri information of the pdu
* @param code [IN] code of the pdu packet
* @param info [IN] pdu information
* @return generated pdu
*/
-coap_pdu_t *CAGeneratePDU(const char *uri, uint32_t code, const CAInfo_t info);
+coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info);
/**
* function for generating
* @brief extracts request information from received pdu.
* @param pdu [IN] received pdu
* @param outReqInfo [OUT] request info structure made from received pdu
- * @param outUri [OUT] uri received in the received pdu
- * @param buflen [IN] Buffer Length for outUri parameter
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo, char *outUri,
- uint32_t buflen);
+CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo);
/**
* @brief extracts response information from received pdu.
* @param pdu [IN] received pdu
* @param outResInfo [OUT] response info structure made from received pdu
- * @param outUri [OUT] uri received in the received pdu
- * @param buflen [IN] Buffer Length for outUri parameter
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
- char *outUri, uint32_t buflen);
+CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo);
/**
* @brief extracts error information from received pdu.
* @param pdu [IN] received pdu
* @param errorInfo [OUT] error info structure made from received pdu
- * @param outUri [OUT] uri received in the received pdu
- * @param buflen [IN] length of outUri
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, CAErrorInfo_t *errorInfo,
- char *outUri, uint32_t buflen);
+CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, CAErrorInfo_t *errorInfo);
+
/**
* @brief creates pdu from the request information
* @param code [IN] request or response code
* @param payload [IN] payload for the request or response consumed
* @return generated pdu
*/
-coap_pdu_t *CAGeneratePDUImpl(code_t code, coap_list_t *options, const CAInfo_t info,
+coap_pdu_t *CAGeneratePDUImpl(code_t code, coap_list_t *options, const CAInfo_t *info,
const char *payload, size_t payloadSize);
/**
* @param optlist [OUT] options information
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t info, coap_list_t **optlist);
+CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **optlist);
/**
* @brief creates option node from key length and data
* @param data [IN] data that needs to be sent
* @return created list
*/
-coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const uint8_t *data);
+coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const char *data);
/**
* @brief order the inserted options
* @param pdu [IN] received pdu
* @param outCode [OUT] code of the received pdu
* @param outInfo [OUT] request info structure made from received pdu
- * @param outUri [OUT] uri received in the received pdu
- * @param buflen [IN] Buffer Length for outUri parameter
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo,
- char *outUri, uint32_t buflen);
+CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo);
/**
* @brief create pdu from received data
* @param endpoint [IN] endpoint information where the data has to be sent
* @return remote endpoint created
*/
-CARemoteEndpoint_t *CACloneRemoteEndpoint(const CARemoteEndpoint_t *endpoint);
-
-/**
- * @brief Creates a new remote endpoint from the input uri
- * @param uri [IN] absolute uri information to create remote endpoint
- * @param transportType [IN] transport type of the endpoint
- * @return remote endpoint created
- */
-CARemoteEndpoint_t *CACreateRemoteEndpointUriInternal(const CAURI_t uri,
- const CATransportType_t transportType);
-
-/**
- * @brief Creates a new remote endpoint from the input and other information
- * @param resourceUri [IN] absolute uri information to create remote endpoint
- * @param addr [IN] address of the endpoint
- * @param type [IN] transport type of the endpoint
- * @return remote endpoint created
- */
-CARemoteEndpoint_t *CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
- const CAAddress_t addr,
- const CATransportType_t type);
+CAEndpoint_t *CACloneEndpoint(const CAEndpoint_t *endpoint);
/**
* @brief Destroy remote endpoint
* @param endpoint [IN] endpoint information where the data has to be sent
* @return none
*/
-void CADestroyRemoteEndpointInternal(CARemoteEndpoint_t *rep);
+void CADestroyEndpointInternal(CAEndpoint_t *rep);
/**
* @brief Creates a new request information
#include "uarraylist.h"
#include "cacommon.h"
-/** CA_IPV4, CA_EDR, CA_LE **/
-#define DEFAULT_RETRANSMISSION_TYPE (CA_IPV4 | CA_EDR | CA_LE)
+/** IP, EDR, LE **/
+#define DEFAULT_RETRANSMISSION_TYPE (CA_ADAPTER_IP | \
+ CA_ADAPTER_RFCOMM_BTEDR | \
+ CA_ADAPTER_GATT_BTLE)
/** default ACK time is 2 sec.(CoAP) **/
#define DEFAULT_ACK_TIMEOUT_SEC 2
#define RETRANSMISSION_CHECK_PERIOD_SEC 1
/** retransmission data send method type**/
-typedef CAResult_t (*CADataSendMethod_t)(const CARemoteEndpoint_t *endpoint, const void *pdu,
+typedef CAResult_t (*CADataSendMethod_t)(const CAEndpoint_t *endpoint,
+ const void *pdu,
uint32_t size);
/** retransmission timeout callback type**/
-typedef void (*CATimeoutCallback_t)(const CARemoteEndpoint_t *endpoint, const void *pdu,
+typedef void (*CATimeoutCallback_t)(const CAEndpoint_t *endpoint,
+ const void *pdu,
uint32_t size);
typedef struct
{
/** retransmission support transport type **/
- CATransportType_t supportType;
+ CATransportAdapter_t supportType;
/** retransmission trying count **/
uint8_t tryingCount;
* @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionSentData(CARetransmission_t* context,
- const CARemoteEndpoint_t* endpoint, const void* pdu,
- uint32_t size);
+ const CAEndpoint_t* endpoint,
+ const void* pdu, uint32_t size);
/**
* @brief Pass the received pdu data. if received pdu is ACK data for the retransmission CON data,
* @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
- const CARemoteEndpoint_t *endpoint, const void *pdu,
+ const CAEndpoint_t *endpoint, const void *pdu,
uint32_t size, void **retransmissionPdu);
/**
#include "cacommon.h"
/** CA_IPV4, CA_LE **/
-#define DEFAULT_RETRANSMISSION_TYPE (CA_IPV4 | CA_LE)
+#define DEFAULT_RETRANSMISSION_TYPE (CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE)
/** default retransmission trying count is 4. **/
#define DEFAULT_RETRANSMISSION_COUNT 4
#define RETRANSMISSION_CHECK_PERIOD_SEC 1
/** retransmission data send method type**/
-typedef CAResult_t (*CADataSendMethod_t)(const CARemoteEndpoint_t *endpoint, const void *pdu,
+typedef CAResult_t (*CADataSendMethod_t)(const CAEndpoint_t *endpoint, const void *pdu,
uint32_t size);
/** retransmission timeout callback type**/
-typedef void (*CATimeoutCallback_t)(const CARemoteEndpoint_t *endpoint, const void *pdu,
+typedef void (*CATimeoutCallback_t)(const CAEndpoint_t *endpoint, const void *pdu,
uint32_t size);
typedef struct
{
/** retransmission support transport type **/
- CATransportType_t supportType;
+ CATransportAdapter_t supportType;
/** retransmission trying count **/
uint8_t tryingCount;
* @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionSentData(CARetransmission_t *context,
- const CARemoteEndpoint_t *endpoint,
+ const CAEndpoint_t *endpoint,
const void *pdu, uint32_t size);
/**
* @return CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
- const CARemoteEndpoint_t *endpoint, const void *pdu,
+ const CAEndpoint_t *endpoint, const void *pdu,
uint32_t size, void **retransmissionPdu);
/**
uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
-void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo);
-void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo);
-void error_handler(const CARemoteEndpoint_t *object, const CAErrorInfo_t* errorInfo);
-
+void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo);
+void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo);
+void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
void get_resource_uri(const char *URI, char *resourceURI, uint32_t length);
uint32_t get_secure_information(CAPayload_t payLoad);
CAResult_t get_network_type(uint32_t selectedNetwork);
void callback(char *subject, char *receivedData);
-CAResult_t get_remote_address(CATransportType_t transportType, CAAddress_t addressInfo);
+CAResult_t get_remote_address(CATransportAdapter_t transportType, const char *address);
-CATransportType_t g_selectedNwType = CA_IPV4;
+CATransportAdapter_t g_selectedNwType = CA_ADAPTER_IP;
static CAToken_t g_lastRequestToken = NULL;
static uint8_t g_lastRequestTokenLength;
= "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
"\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
-
static jobject g_responseListenerObject = NULL;
static JavaVM *g_jvm;
-static CARemoteEndpoint_t *g_clientEndpoint = NULL;
+static CAEndpoint_t *g_clientEndpoint = NULL;
+static char *g_resourceUri;
static CAToken_t g_clientToken;
static uint8_t g_clientTokenLength = NULL;
JNIEXPORT void JNICALL
Java_org_iotivity_ca_service_RMInterface_RMFindResource(JNIEnv *env, jobject obj, jstring uri)
{
- // create token
- CAToken_t token = NULL;
- uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
- CAResult_t res = CAGenerateToken(&token, tokenLength);
- if ((CA_STATUS_OK != res) || (!token))
- {
- LOGE("token generate error!!");
- return;
- }
-
- printf("Generated token %s\n", token);
-
- const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
- LOGI("RMFindResource - %s", strUri);
-
- res = CAFindResource((const CAURI_t) strUri, token, tokenLength);
-
- //ReleseStringUTFCharss for strUri
- (*env)->ReleaseStringUTFChars(env, uri, strUri);
-
- if (CA_STATUS_OK != res)
- {
- LOGE("Could not find resource");
- //destroy token
- CADestroyToken(token);
- }
- else
- {
- LOGI("find resource to %s URI", strUri);
- CADestroyToken(g_lastRequestToken);
- g_lastRequestToken = token;
- g_lastRequestTokenLength = tokenLength;
- }
+ LOGE("Java_org_iotivity_service_RMInterface_RMFindResource not implemented");
}
JNIEXPORT void JNICALL
LOGI("RMSendRequest - %s", strUri);
//create remote endpoint
- CARemoteEndpoint_t* endpoint = NULL;
- res = CACreateRemoteEndpoint((const CAURI_t) strUri, g_selectedNwType, &endpoint);
-
+ CAEndpoint_t* endpoint = NULL;
+ res = CACreateEndpoint(CA_DEFAULT_FLAGS, g_selectedNwType, strUri, 0, &endpoint);
//ReleaseStringUTFChars for strUri
(*env)->ReleaseStringUTFChars(env, uri, strUri);
{
LOGE("token generate error!!");
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
// destroy token
CADestroyToken(token);
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
// destroy token
CADestroyToken(token);
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
+ requestInfo.isMulticast = false;
requestInfo.info = requestData;
// send request
CADestroyToken(token);
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
free(requestData.payload);
}
LOGI("RMSendReqestToAll - %s", strUri);
// create remote endpoint
- CARemoteEndpoint_t *endpoint = NULL;
- res = CACreateRemoteEndpoint((const CAURI_t) strUri, g_selectedNwType, &endpoint);
+ CAEndpoint_t *endpoint = NULL;
+ res = CACreateEndpoint(CA_DEFAULT_FLAGS, g_selectedNwType, strUri, 0, &endpoint);
//ReleaseStringUTFChars for strUri
(*env)->ReleaseStringUTFChars(env, uri, strUri);
return;
}
- CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
- if (NULL == group)
- {
- LOGE("Memory allocation failed!");
- CADestroyRemoteEndpoint(endpoint);
- return;
- }
- group->transportType = endpoint->transportType;
- group->resourceUri = endpoint->resourceUri;
-
// create token
CAToken_t token = NULL;
uint8_t tokenLength = CA_MAX_TOKEN_LEN;
{
LOGE("token generate error!!");
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
- free(group);
+ CADestroyEndpoint(endpoint);
return;
}
CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
+ requestInfo.isMulticast = true;
requestInfo.info = requestData;
// send request to all
- res = CASendRequestToAll(group, &requestInfo);
+ res = CASendRequest(endpoint, &requestInfo);
if (CA_STATUS_OK != res)
{
LOGE("Could not send request to all");
}
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
- free(group);
-
+ CADestroyEndpoint(endpoint);
}
JNIEXPORT void JNICALL
if (1 == isSecured)
{
- uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_clientEndpoint->resourceUri) + 1;
+ uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
responseData.payload = (CAPayload_t) malloc(length);
- sprintf(responseData.payload, SECURE_INFO_DATA, g_clientEndpoint->resourceUri,
+ sprintf(responseData.payload, SECURE_INFO_DATA, g_resourceUri,
g_localSecurePort);
}
else
{
- uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_clientEndpoint->resourceUri) + 1;
+ uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
responseData.payload = (CAPayload_t) malloc(length);
- sprintf(responseData.payload, NORMAL_INFO_DATA, g_clientEndpoint->resourceUri);
+ sprintf(responseData.payload, NORMAL_INFO_DATA, g_resourceUri);
}
}
//msgType is RESET
g_clientTokenLength = 0;
// destroy remote endpoint
- CADestroyRemoteEndpoint(g_clientEndpoint);
+ CADestroyEndpoint(g_clientEndpoint);
g_clientEndpoint = NULL;
}
JNIEXPORT void JNICALL
-Java_org_iotivity_ca_service_RMInterface_RMAdvertiseResource(JNIEnv *env, jobject obj, jstring uri)
-{
- LOGI("RMAdvertiseResource");
-
- uint32_t optionNum = 2;
-
- CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
- sizeof(CAHeaderOption_t) * optionNum);
- if (NULL == headerOpt)
- {
- LOGE("Memory allocation failed!");
- return;
- }
-
- char* tmpOptionData1 = "Hello";
- headerOpt[0].optionID = 3000;
- memcpy(headerOpt[0].optionData, tmpOptionData1, strlen(tmpOptionData1));
- headerOpt[0].optionLength = (uint16_t) strlen(tmpOptionData1);
-
- char* tmpOptionData2 = "World";
- headerOpt[1].optionID = 3001;
- memcpy(headerOpt[1].optionData, tmpOptionData2, strlen(tmpOptionData2));
- headerOpt[1].optionLength = (uint16_t) strlen(tmpOptionData2);
-
- // create token
- CAToken_t token = NULL;
- uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
- CAResult_t res = CAGenerateToken(&token, tokenLength);
- if ((CA_STATUS_OK != res) || (!token))
- {
- LOGE("token generate error!");
- free(headerOpt);
- return;
- }
-
- const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
-
- res = CAAdvertiseResource((const CAURI_t) strUri, token, tokenLength,
- headerOpt, (uint8_t) optionNum);
- if (CA_STATUS_OK != res)
- {
- LOGE("Could not start advertise resource");
- CADestroyToken(token);
- }
- else
- {
- CADestroyToken(g_lastRequestToken);
- g_lastRequestToken = token;
- g_lastRequestTokenLength = tokenLength;
- }
-
- free(headerOpt);
-
- //ReleaseStringUTFChars for strUri
- (*env)->ReleaseStringUTFChars(env, uri, strUri);
-}
-
-JNIEXPORT void JNICALL
Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
jstring payload, jint selectedNetwork,
jint isSecured, jint msgType,
LOGI("RMSendNotification - %s", strUri);
//create remote endpoint
- CARemoteEndpoint_t* endpoint = NULL;
- if (CA_STATUS_OK != CACreateRemoteEndpoint((const CAURI_t) strUri,
- g_selectedNwType, &endpoint))
+ CAEndpoint_t* endpoint = NULL;
+ if (CA_STATUS_OK != CACreateEndpoint(CA_DEFAULT_FLAGS, g_selectedNwType, strUri, 0, &endpoint))
{
//ReleaseStringUTFChars for strUri
(*env)->ReleaseStringUTFChars(env, uri, strUri);
}
char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
- get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
+ get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
//ReleaseStringUTFChars for strUri
(*env)->ReleaseStringUTFChars(env, uri, strUri);
if ((CA_STATUS_OK != res) || (!token))
{
LOGE("token generate error!");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
// destroy token
CADestroyToken(token);
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
snprintf(responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
// destroy token
CADestroyToken(token);
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
snprintf(responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
CADestroyToken(token);
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
free(responseData.payload);
}
{
LOGI("RMGetNetworkInfomation");
- CALocalConnectivity_t *tempInfo = NULL;
+ CAEndpoint_t *tempInfo = NULL;
uint32_t tempSize = 0;
CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
if (CA_STATUS_OK != res)
{
LOGE("Could not start get network information");
- OICFree(tempInfo);
+ free(tempInfo);
return;
}
uint32_t index;
for (index = 0; index < tempSize; index++)
{
- res = get_remote_address(tempInfo[index].type, tempInfo[index].addressInfo);
+ res = get_remote_address(tempInfo[index].adapter, tempInfo[index].addr);
if (CA_STATUS_OK != res)
{
- OICFree(tempInfo);
+ free(tempInfo);
return;
}
if (NULL != g_responseListenerObject)
{
char networkInfo[NETWORK_INFO_LENGTH];
- LOGI("Type: %d", tempInfo[index].type);
- sprintf(networkInfo, "%d",tempInfo[index].type);
+ LOGI("Type: %d", tempInfo[index].adapter);
+ sprintf(networkInfo, "%d",tempInfo[index].adapter);
callback("Type :", networkInfo);
- if (CA_IPV4 == tempInfo[index].type)
+ if (CA_ADAPTER_IP == tempInfo[index].adapter)
{
- LOGI("Port: %d", tempInfo[index].addressInfo.IP.port);
- sprintf(networkInfo, "%d",tempInfo[index].addressInfo.IP.port);
+ LOGI("Port: %d", tempInfo[index].port);
+ sprintf(networkInfo, "%d",tempInfo[index].port);
callback("Port: ", networkInfo);
}
- LOGI("Secured: %d", tempInfo[index].isSecured);
+ LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
LOGI("Address: %s", g_remoteAddress);
callback("Address: ", g_remoteAddress);
free(g_remoteAddress);
}
- if (true == tempInfo[index].isSecured)
+ if (tempInfo[index].flags & CA_SECURE)
{
- g_localSecurePort = tempInfo[index].addressInfo.IP.port;
+ g_localSecurePort = tempInfo[index].port;
}
}
// free
- OICFree(tempInfo);
+ free(tempInfo);
LOGI("##############################################################");
}
}
}
-void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo)
+void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
{
if (!object)
return;
}
- CAResult_t res = get_remote_address(object->transportType, object->addressInfo);
+ CAResult_t res = get_remote_address(object->adapter, object->addr);
if (CA_STATUS_OK != res)
{
return;
}
LOGI("##########received request from remote device #############");
- if (object->resourceUri)
- {
- LOGI("Uri: %s", object->resourceUri);
- }
LOGI("Remote Address: %s", g_remoteAddress);
+ LOGI("Uri: %s", requestInfo->info.resourceUri);
LOGI("Data: %s", requestInfo->info.payload);
LOGI("Token: %s", requestInfo->info.token);
LOGI("Code: %d", requestInfo->method);
char *cloneUri = NULL;
uint32_t len = 0;
- if (NULL != object->resourceUri)
+ if (NULL != requestInfo->info.resourceUri)
{
- len = strlen(object->resourceUri);
- cloneUri = (char *) malloc(sizeof(char) * (len + 1));
+ len = strlen(requestInfo->info.resourceUri);
+ cloneUri = (char *)malloc(sizeof(char) * (len + 1));
if (NULL == cloneUri)
{
return;
}
- memcpy(cloneUri, object->resourceUri, len + 1);
+ memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
callback("Uri: ", cloneUri);
}
free(g_remoteAddress);
//clone g_clientEndpoint
- g_clientEndpoint = (CARemoteEndpoint_t *) malloc(sizeof(CARemoteEndpoint_t));
+ g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
if (NULL == g_clientEndpoint)
{
LOGE("g_clientEndpoint Out of memory");
free(cloneUri);
return;
}
- memcpy(g_clientEndpoint, object, sizeof(CARemoteEndpoint_t));
+ memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
if (NULL != cloneUri)
{
len = strlen(cloneUri);
- g_clientEndpoint->resourceUri = (char *) malloc(sizeof(char) * (len + 1));
- if (NULL == g_clientEndpoint)
+ g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
+ if (NULL == g_resourceUri)
{
LOGE("g_clientEndpoint->resourceUri Out of memory");
free(g_clientEndpoint);
free(cloneUri);
return;
}
- memcpy(g_clientEndpoint->resourceUri, cloneUri, len + 1);
+ memcpy(g_resourceUri, cloneUri, len + 1);
free(cloneUri);
}
//clone g_clientToken
if (NULL == g_clientToken)
{
LOGE("g_clientToken Out of memory");
- free(g_clientEndpoint->resourceUri);
free(g_clientEndpoint);
return;
}
if (NULL == clonePayload)
{
LOGE("clonePayload Out of memory");
- free(g_clientEndpoint->resourceUri);
free(g_clientEndpoint);
return;
}
callback("Option info: ", optionInfo);
- uint32_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
+ size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
if (NULL == cloneOptionData)
{
LOGE("cloneOptionData Out of memory");
- free(g_clientEndpoint->resourceUri);
free(g_clientEndpoint);
return;
}
LOGI("############################################################");
//Check if this has secure communication information
- if (requestInfo->info.payload && CA_IPV4 == object->transportType)
+ if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
{
uint32_t securePort = get_secure_information(requestInfo->info.payload);
if (0 < securePort) //Set the remote endpoint secure details and send response
length = sizeof(SECURE_COAPS_PREFIX) - 1; //length of "coaps://"
// length of "ipaddress:port"
- length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
- length += strlen(object->resourceUri) + 1;
+ length += strlen(object->addr) + PORT_LENGTH;
+ length += strlen(requestInfo->info.resourceUri) + 1;
uri = calloc(1, sizeof(char) * length);
if (!uri)
free(uri);
return;
}
- sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
- securePort, object->resourceUri);
+ sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addr,
+ securePort, requestInfo->info.resourceUri);
- CARemoteEndpoint_t *endpoint = NULL;
- if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
+ CAEndpoint_t *endpoint = NULL;
+ if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
+ object->adapter, uri, securePort, &endpoint))
{
LOGE("Failed to create duplicate of remote endpoint!");
free(uri);
return;
}
- endpoint->isSecured = true;
object = endpoint;
free(uri);
}
}
-void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo)
+void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
{
- CAResult_t res = get_remote_address(object->transportType, object->addressInfo);
+ CAResult_t res = get_remote_address(object->adapter, object->addr);
if (CA_STATUS_OK != res)
{
return;
}
LOGI("##########Received response from remote device #############");
- LOGI("Uri: %s", object->resourceUri);
+ LOGI("Uri: %s", responseInfo->info.resourceUri);
LOGI("Remote Address: %s", g_remoteAddress);
LOGI("response result: %d", responseInfo->result);
LOGI("Data: %s", responseInfo->info.payload);
{
uint32_t len = 0;
- if (NULL != object->resourceUri)
+ if (NULL != responseInfo->info.resourceUri)
{
- len = strlen(object->resourceUri);
+ len = strlen(responseInfo->info.resourceUri);
char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
if (NULL == cloneUri)
return;
}
- memcpy(cloneUri, object->resourceUri, len + 1);
+ memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
callback("Uri: ", cloneUri);
free(cloneUri);
callback("Option info: ", optionInfo);
- uint32_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
+ size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
if (NULL == cloneOptionData)
{
LOGI("############################################################");
//Check if this has secure communication information
- if (responseInfo->info.payload && CA_IPV4 == object->transportType)
+ if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
{
uint32_t securePort = get_secure_information(responseInfo->info.payload);
if (0 < securePort) //Set the remote endpoint secure details and send response
}
}
-void error_handler(const CARemoteEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
+void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
{
printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
- if(rep && rep->resourceUri )
- {
- LOGI("Error Handler, RemoteEndpoint Info resourceUri : %s", rep->resourceUri);
- }
- else
- {
- LOGI("Error Handler, RemoteEndpoint is NULL");
- }
-
if(errorInfo)
{
const CAInfo_t *info = &errorInfo->info;
LOGI("Error Handler result : %d", errorInfo->result);
LOGI("Error Handler token : %s", info->token);
LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
+ LOGI("Error Handler resourceUri : %s", info->resourceUri);
LOGI("Error Handler type : %d", info->type);
LOGI("Error Handler payload : %s", info->payload);
void get_resource_uri(const char *URI, char *resourceURI, uint32_t length)
{
const char *startPos = URI;
- const char *temp = NULL;
- if (NULL != (temp = strstr(URI, "://")))
+ const char *temp = strstr(URI, "://");
+ if (NULL != temp)
{
startPos = strchr(temp + 3, '/');
if (!startPos)
{
return CA_NOT_SUPPORTED;
}
- if (number & CA_IPV4)
+ if (number & CA_ADAPTER_IP)
{
- g_selectedNwType = CA_IPV4;
+ g_selectedNwType = CA_ADAPTER_IP;
return CA_STATUS_OK;
}
- if (number & CA_EDR)
+ if (number & CA_ADAPTER_RFCOMM_BTEDR)
{
- g_selectedNwType = CA_EDR;
+ g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
return CA_STATUS_OK;
}
- if (number & CA_LE)
+ if (number & CA_ADAPTER_GATT_BTLE)
{
- g_selectedNwType = CA_LE;
+ g_selectedNwType = CA_ADAPTER_GATT_BTLE;
return CA_STATUS_OK;
}
}
-CAResult_t get_remote_address(CATransportType_t transportType, CAAddress_t addressInfo)
+CAResult_t get_remote_address(CATransportAdapter_t transportType, const char *address)
{
+ uint32_t len = strlen(address);
- uint32_t len = 0;
- if (CA_IPV4 == transportType)
+ g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
+ if (NULL == g_remoteAddress)
{
- len = strlen(addressInfo.IP.ipAddress);
- g_remoteAddress = (char *) malloc(sizeof(char) * (len + 1));
-
- if (NULL == g_remoteAddress)
- {
- LOGE("g_remoteAddress Out of memory");
- return CA_MEMORY_ALLOC_FAILED;
- }
-
- memcpy(g_remoteAddress, addressInfo.IP.ipAddress, len + 1);
- }
-
- else if (CA_EDR == transportType)
- {
- len = strlen(addressInfo.BT.btMacAddress);
- g_remoteAddress = (char *) malloc(sizeof(char) * (len + 1));
-
- if (NULL == g_remoteAddress)
- {
- LOGE("g_remoteAddress Out of memory");
- return CA_MEMORY_ALLOC_FAILED;
- }
-
- memcpy(g_remoteAddress, addressInfo.BT.btMacAddress, len + 1);
+ LOGE("g_remoteAddress Out of memory");
+ return CA_MEMORY_ALLOC_FAILED;
}
- else if (CA_LE == transportType)
- {
- len = strlen(addressInfo.LE.leMacAddress);
- g_remoteAddress = (char *) malloc(sizeof(char) * (len + 1));
-
- if (NULL == g_remoteAddress)
- {
- LOGE("g_remoteAddress Out of memory");
- return CA_MEMORY_ALLOC_FAILED;
- }
-
- memcpy(g_remoteAddress, addressInfo.LE.leMacAddress, len + 1);
- }
+ memcpy(g_remoteAddress, address, len + 1);
return CA_STATUS_OK;
}
static void Initialize();
static void StartListeningServer();
static void StartDiscoveryServer();
-static void FindResource();
static void SendRequest();
static void SendRequestAll();
-static void SendResponse(CARemoteEndpoint_t *endpoint, const CAInfo_t* info);
-static void AdvertiseResource();
+static void SendResponse(CAEndpoint_t *endpoint, const CAInfo_t* info);
static void SendNotification();
static void SelectNetwork();
static void UnselectNetwork();
static void HandleRequestResponse();
-static void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
-static void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
-static void ErrorHandler(const CARemoteEndpoint_t *object, const CAErrorInfo_t* errorInfo);
+static void RequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
+static void ResponseHandler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
+static void ErrorHandler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
static void Terminate();
void GetData(char *readInput, size_t bufferLength, size_t *dataLength)
(*dataLength) = len;
}
-CATransportType_t GetConnectivityType()
+bool ParseData(char *buf, char *url, char *resourceUri)
+{
+ char *slash = strchr(buf, '/');
+ if (!slash)
+ {
+ return false;
+ }
+
+ strcpy(resourceUri, slash);
+
+ char *dot = strchr(buf, '.');
+ if (dot && dot < slash)
+ {
+ char *colon = strchr(buf, ':');
+ if (colon && colon < slash)
+ {
+ strncpy(url, buf, colon - buf);
+ return true;
+ }
+ }
+
+ strncpy(url, buf, slash - buf);
+ return true;
+}
+
+CATransportAdapter_t GetConnectivityType()
{
char type[2] = {0};
Serial.println("Select network");
- Serial.println("IPv4: 0");
- Serial.println("EDR: 2");
- Serial.println("LE: 3");
+ Serial.println("IP: 0");
+ Serial.println("RFCOMM (EDR): 1");
+ Serial.println("GATT (BLE): 2");
size_t typeLen = 0;
GetData(type, sizeof(type), &typeLen);
if (0 >= typeLen)
{
Serial.println("i/p err,default ethernet");
- return CA_IPV4;
+ return CA_ADAPTER_IP;
}
switch (type[0])
{
case '0':
- return CA_IPV4;
+ return CA_ADAPTER_IP;
+ case '1':
+ return CA_ADAPTER_RFCOMM_BTEDR;
case '2':
- return CA_EDR;
- case '3':
- return CA_LE;
+ return CA_ADAPTER_GATT_BTLE;
}
- return CA_IPV4;
+ return CA_ADAPTER_IP;
}
void setup()
break;
case 'F': // find resource
- FindResource();
+ SendRequestAll();
break;
case 'R': // send request
case 'E': //send request to all
SendRequestAll();
break;
- case 'A': // advertise resource
- AdvertiseResource();
- break;
-
case 'B': // send notification
SendNotification();
break;
}
}
-void FindResource()
-{
- char buf[MAX_BUF_LEN] = {0};
- Serial.println("============");
- Serial.println("ex) /a/light");
- Serial.println("uri: ");
- size_t len = 0;
- GetData(buf, sizeof(buf), &len);
- if (0 >= len)
- {
- Serial.println("i/p err");
- return;
- }
- // create token
- CAToken_t token = NULL;
- uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
- CAResult_t res = CAGenerateToken(&token, tokenLength);
- if (res != CA_STATUS_OK || (!token))
- {
- Serial.println("token error");
- return;
- }
-
- Serial.print("token:");
- Serial.println(token);
-
- res = CAFindResource(buf, token, tokenLength);
- if (res != CA_STATUS_OK)
- {
- Serial.print("find error: ");
- Serial.println(res);
- }
- else
- {
- Serial.println("success: ");
- Serial.println(buf);
- }
- CADestroyToken(token);
-}
-
void SendRequest()
{
char buf[MAX_BUF_LEN] = {0};
- CATransportType_t selectedNetwork;
+ char address[MAX_BUF_LEN] = {0};
+ char resourceUri[MAX_BUF_LEN] = {0};
+ CATransportAdapter_t selectedNetwork;
selectedNetwork = GetConnectivityType();
Serial.println("============");
return;
}
+ if (!ParseData(buf, address, resourceUri))
+ {
+ Serial.println("bad uri");
+ return;
+ }
+
// create remote endpoint
- CARemoteEndpoint_t *endpoint = NULL;
- CAResult_t res = CACreateRemoteEndpoint(buf,selectedNetwork,&endpoint);
+ CAEndpoint_t *endpoint = NULL;
+ CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, 0, &endpoint);
if (res != CA_STATUS_OK)
{
Serial.println("Out of memory");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
requestData.payload = (CAPayload_t)"Json Payload";
requestData.type = msgType;
+ requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
+ strcpy(requestData.resourceUri, resourceUri);
CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
requestInfo.method = CA_GET;
+ requestInfo.isMulticast = false;
requestInfo.info = requestData;
// send request
// destroy remote endpoint
if (endpoint != NULL)
{
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
}
Serial.println("============");
void SendRequestAll()
{
char buf[MAX_BUF_LEN] = {0};
+ char address[MAX_BUF_LEN] = {0};
+ char resourceUri[MAX_BUF_LEN] = {0};
- CATransportType_t selectedNetwork;
+ CATransportAdapter_t selectedNetwork;
selectedNetwork = GetConnectivityType();
Serial.println("=========");
Serial.println("10.11.12.13:4545/resource_uri ( for IP )");
Serial.println("10:11:12:13:45:45/resource_uri ( for BT )");
+ Serial.println("/resource_uri (any adapter)");
Serial.println("uri : ");
size_t len = 0;
return;
}
+ if (!ParseData(buf, address, resourceUri))
+ {
+ Serial.println("bad uri");
+ return;
+ }
+
// create remote endpoint
- CARemoteEndpoint_t *endpoint = NULL;
- CAResult_t res = CACreateRemoteEndpoint(buf, selectedNetwork, &endpoint);
+ CAEndpoint_t *endpoint = NULL;
+ CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, 0, &endpoint);
if (res != CA_STATUS_OK)
{
Serial.println("create remote endpoint error");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
- CAGroupEndpoint_t *group = NULL;
- group = (CAGroupEndpoint_t *)OICMalloc(sizeof(CAGroupEndpoint_t));
- group->transportType = endpoint->transportType;
- group->resourceUri = endpoint->resourceUri;
-
// create token
CAToken_t token = NULL;
uint8_t tokenLength = CA_MAX_TOKEN_LEN;
requestData.tokenLength = tokenLength;
requestData.payload = "Temp Json Payload";
requestData.type = CA_MSG_NONCONFIRM;
+ requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
+ strcpy(requestData.resourceUri, resourceUri);
CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
requestInfo.method = CA_GET;
+ requestInfo.isMulticast = true;
requestInfo.info = requestData;
// send request
// CASendRequest(endpoint, &requestInfo);
- CASendRequestToAll(group, &requestInfo);
+ CASendRequest(endpoint, &requestInfo);
if (NULL != token)
{
// destroy remote endpoint
if (endpoint != NULL)
{
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
}
- OICFree(group);
Serial.println("==========");
}
-void AdvertiseResource()
-{
- char buf[MAX_BUF_LEN] = {0};
-
- Serial.println("============");
- Serial.println("uri: ");
-
- size_t len = 0;
- GetData(buf, sizeof(buf), &len);
- if (0 >= len)
- {
- Serial.println("no i/p");
- return;
- }
-
- int16_t optionNum = 0;
- char optionData[MAX_OPT_LEN] = {0};
- char optionNumBuf[2] = {0};
-
- Serial.println("Option Num: ");
- GetData(optionNumBuf, sizeof(optionNumBuf), &len);
- if (0 >= len)
- {
- Serial.println("no i/p,0 option");
- }
- else
- {
- optionNum = atoi(optionNumBuf);
- Serial.println(optionNum);
- }
-
- CAHeaderOption_t *headerOpt = NULL;
- if (optionNum > 0)
- {
- headerOpt = (CAHeaderOption_t *) OICCalloc(optionNum, sizeof(CAHeaderOption_t));
- if (NULL == headerOpt)
- {
- Serial.println("Out of memory");
- return;
- }
- }
-
- int i;
- for (i = 0 ; i < optionNum ; i++)
- {
- int optionID = 0;
- char getOptionID[4];
- Serial.println("Opt ID:");
- GetData(getOptionID, sizeof(getOptionID), &len);
- if (0 >= len)
- {
- Serial.println("no i/p");
- continue;
- }
- else
- {
- optionID = atoi(getOptionID);
- }
-
- memset(optionData, 0, sizeof(optionData));
- Serial.println("Opt Data:");
- GetData(optionData, sizeof(optionData), &len);
- if (0 >= len)
- {
- Serial.println("no i/p");
- continue;
- }
-
- headerOpt[i].optionID = optionID;
- memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
- Serial.println("ID:");
- Serial.println(optionID);
- Serial.println("Data:");
- Serial.println(optionData);
-
- headerOpt[i].optionLength = (uint16_t)strlen(optionData);
- }
-
- Serial.println("============");
- // create token
- CAToken_t token = NULL;
- uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
- CAResult_t res = CAGenerateToken(&token, tokenLength);
- if (res != CA_STATUS_OK || (!token))
- {
- Serial.println("token error");
- return;
- }
-
- Serial.println("token");
- Serial.println(token);
-
- CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t)optionNum);
- OICFree(headerOpt);
- CADestroyToken(token);
-}
-
void SendNotification()
{
char buf[MAX_BUF_LEN] = {0};
- CATransportType_t selectedNetwork;
+ char address[MAX_BUF_LEN] = {0};
+ char resourceUri[MAX_BUF_LEN] = {0};
+ CATransportAdapter_t selectedNetwork;
selectedNetwork = GetConnectivityType();
Serial.println("============");
return;
}
+ if (!ParseData(buf, address, resourceUri))
+ {
+ Serial.println("bad uri");
+ return;
+ }
+
// create remote endpoint
- CARemoteEndpoint_t *endpoint = NULL;
- CAResult_t res = CACreateRemoteEndpoint(buf,selectedNetwork,&endpoint);
+ CAEndpoint_t *endpoint = NULL;
+ CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, 0, &endpoint);
if (CA_STATUS_OK != res)
{
Serial.println("Out of memory");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
respondData.token = token;
respondData.tokenLength = tokenLength;
respondData.payload = (CAPayload_t)"Notification Data";
+ respondData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
+ strcpy(respondData.resourceUri, resourceUri);
CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
responseInfo.result = CA_SUCCESS;
// destroy remote endpoint
if (NULL != endpoint)
{
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
}
CADestroyToken(token);
Serial.println("============");
Serial.println("Select network");
- Serial.println("IPv4: 0");
- Serial.println("EDR: 2");
- Serial.println("LE: 3\n");
+ Serial.println("IP: 0");
+ Serial.println("EDR: 1");
+ Serial.println("LE: 2\n");
size_t len = 0;
GetData(buf, sizeof(buf), &len);
break;
}
- CASelectNetwork(CATransportType_t(1<<number));
+ CASelectNetwork(CATransportAdapter_t(1<<number));
Serial.println("============");
}
CAHandleRequestResponse();
}
-void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+void RequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
{
if (!object)
{
- Serial.println("Remote endpoint is NULL!");
+ Serial.println("endpoint is NULL!");
return;
}
return;
}
- Serial.println("uri: ");
- Serial.println(object->resourceUri);
Serial.println("RAddr: ");
- Serial.println(object->addressInfo.IP.ipAddress);
+ Serial.println(object->addr);
Serial.println("Port: ");
- Serial.println(object->addressInfo.IP.port);
+ Serial.println(object->port);
+ Serial.println("uri: ");
+ Serial.println(requestInfo->info.resourceUri);
Serial.println("data: ");
Serial.println(requestInfo->info.payload);
Serial.println("Type: ");
}
}
Serial.println("send response");
- SendResponse((CARemoteEndpoint_t *)object, (requestInfo != NULL) ? &requestInfo->info : NULL);
+ SendResponse((CAEndpoint_t *)object, (requestInfo != NULL) ? &requestInfo->info : NULL);
}
-void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+void ResponseHandler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
{
- if (object && object->resourceUri)
+ if (object)
{
Serial.print("uri: ");
- Serial.println(object->resourceUri);
+ Serial.println(object->addr);
}
if (responseInfo)
{
+ Serial.print("uri: ");
+ Serial.println(responseInfo->info.resourceUri);
Serial.print("data: ");
Serial.println(responseInfo->info.payload);
Serial.print("Type: ");
}
}
-void ErrorHandler(const CARemoteEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
+void ErrorHandler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
{
printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
- if(rep && rep->resourceUri )
- {
- printf("Error Handler, RemoteEndpoint Info resourceUri : %s\n", rep->resourceUri);
- }
- else
- {
- printf("Error Handler, RemoteEndpoint is NULL");
- }
-
if(errorInfo)
{
const CAInfo_t *info = &errorInfo->info;
printf("Error Handler token : %s\n", info->token);
printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
printf("Error Handler type : %d\n", info->type);
+ printf("Error Handler resourceUri : %s\n", info->resourceUri);
printf("Error Handler payload : %s\n", info->payload);
if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
return;
}
-void SendResponse(CARemoteEndpoint_t *endpoint, const CAInfo_t* info)
+void SendResponse(CAEndpoint_t *endpoint, const CAInfo_t* info)
{
char buf[MAX_BUF_LEN] = {0};
int g_received;
uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
-CATransportType_t g_selected_nw_type = CA_IPV4;
+CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
char get_menu();
void start_listening_server();
void start_discovery_server();
-void find_resource();
void send_request();
void send_request_all();
-void advertise_resource();
void send_notification();
void select_network();
void unselect_network();
void handle_request_response();
-void find_fixed_resource();
void get_network_info();
void send_secure_request();
-void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
-void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
-void error_handler(const CARemoteEndpoint_t *object, const CAErrorInfo_t* errorInfo);
-
-void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info);
+void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
+void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
+void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
+void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
void get_resource_uri(char *URI, char *resourceURI, int length);
int get_secure_information(CAPayload_t payLoad);
start_discovery_server();
break;
- case 'f': // find resource
- case 'F':
- find_resource();
- break;
-
case 'r': // send request
case 'R':
send_request();
break;
- case 'a': // advertise resource
- case 'A':
- advertise_resource();
- break;
-
case 'b': // send notification
case 'B':
send_notification();
handle_request_response();
break;
- case 'y':
- case 'Y':
- while (1)
- {
- g_received = 0;
- find_fixed_resource();
- while (g_received == 0)
- {
- sleep(1);
- handle_request_response();
-
- }
- }
- break;
-
case 'w':
case 'W':
g_received = 0;
}
}
-void find_fixed_resource()
-{
- // create token
- CAToken_t token = NULL;
- uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
- CAResult_t res = CAGenerateToken(&token, tokenLength);
- if ((CA_STATUS_OK != res) || (!token))
- {
- printf("Token generate error!!");
- return;
- }
- printf("Generated token %s\n", token);
-
- char buf[MAX_BUF_LEN] = { 0 };
- strcpy(buf, "/a/light");
-
- res = CAFindResource(buf, token, tokenLength);
- if (CA_STATUS_OK != res)
- {
- printf("Find resource error : %d\n", res);
- }
- else
- {
- printf("Find resource to %s URI\n", buf);
- }
-
- // delete token
- CADestroyToken(token);
-
- printf("=============================================\n");
-}
-
-void find_resource()
-{
- printf("\n=============================================\n");
- printf("ex) /a/light\n");
- printf("reference uri : ");
-
- char buf[MAX_BUF_LEN] = { 0 };
- if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
- {
- return;
- }
-
- // create token
- CAToken_t token = NULL;
- uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
- CAResult_t res = CAGenerateToken(&token, tokenLength);
- if ((CA_STATUS_OK != res) || (!token))
- {
- printf("Token generate error!!\n");
- return;
- }
-
- printf("Generated token %s\n", token);
-
- res = CAFindResource(buf, token, tokenLength);
- if (CA_STATUS_OK != res)
- {
- printf("Find resource error : %d\n", res);
- CADestroyToken(token);
- }
- else
- {
- printf("Find resource to %s URI\n", buf);
- CADestroyToken(g_last_request_token);
- g_last_request_token = token;
- }
-
- printf("=============================================\n");
-}
-
void send_request()
{
CAResult_t res = get_network_type();
}
// create remote endpoint
- CARemoteEndpoint_t *endpoint = NULL;
- res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint);
+ CAEndpoint_t *endpoint = NULL;
+ res = CACreateEndpoint(CA_DEFAULT_FLAGS, g_selected_nw_type, uri, 0, &endpoint);
if (CA_STATUS_OK != res || !endpoint)
{
printf("Failed to create remote endpoint, error code : %d\n", res);
char buf[MAX_BUF_LEN] = { 0 };
if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
{
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
if ((CA_STATUS_OK != res) || (!token))
{
printf("Token generate error, error code : %d\n", res);
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
if (NULL == requestData.payload)
{
printf("Memory allocation fail\n");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
CADestroyToken(token);
return;
}
if (NULL == requestData.payload)
{
printf("Memory allocation fail\n");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
CADestroyToken(token);
return;
}
//destroy token
CADestroyToken(token);
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
free(requestData.payload);
snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", SECURE_COAPS_PREFIX, ipv4addr);
// create remote endpoint
- CARemoteEndpoint_t *endpoint = NULL;
- CAResult_t res = CACreateRemoteEndpoint(uri, CA_IPV4, &endpoint);
+ CAEndpoint_t *endpoint = NULL;
+ CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, uri, 0, &endpoint);
if (CA_STATUS_OK != res)
{
printf("Failed to create remote endpoint, error code: %d\n", res);
exit:
// cleanup
CADestroyToken(token);
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
printf("=============================================\n");
}
}
// create remote endpoint
- CARemoteEndpoint_t *endpoint = NULL;
- res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+ CAEndpoint_t *endpoint = NULL;
+ res = CACreateEndpoint(0, g_selected_nw_type, buf, 0, &endpoint);
if (CA_STATUS_OK != res)
{
printf("Create remote endpoint error, error code: %d\n", res);
return;
}
- CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
+ CAEndpoint_t *group = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
if (NULL == group)
{
printf("Memory allocation failed!\n");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
- group->transportType = endpoint->transportType;
- group->resourceUri = endpoint->resourceUri;
+ group->adapter = endpoint->adapter;
// create token
CAToken_t token = NULL;
if ((CA_STATUS_OK != res) || (!token))
{
printf("Token generate error!!\n");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
free(group);
return;
}
CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
requestInfo.info = requestData;
+ requestInfo.isMulticast = true;
// send request
- res = CASendRequestToAll(group, &requestInfo);
+ res = CASendRequest(group, &requestInfo);
if (CA_STATUS_OK != res)
{
printf("Could not send request to all\n");
}
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
free(group);
printf("=============================================\n");
}
-void advertise_resource()
-{
- printf("\n=============================================\n");
- printf("uri : ");
-
- char buf[MAX_BUF_LEN] = { 0 };
- if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
- {
- return;
- }
-
- char optionNumBuf[MAX_BUF_LEN] = { 0 };
- char optionData[MAX_OPT_LEN] = { 0 } ;
-
- printf("Option Num : ");
- if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
- {
- return;
- }
- int optionNum = atoi(optionNumBuf);
-
- CAHeaderOption_t * headerOpt = (CAHeaderOption_t *)
- calloc(1, optionNum * sizeof(CAHeaderOption_t));
- if (NULL == headerOpt)
- {
- printf("Memory allocation failed!\n");
- return;
- }
-
- int i;
- for (i = 0; i < optionNum; i++)
- {
- char getOptionID[MAX_BUF_LEN] = { 0 } ;
-
- printf("[%d] Option ID : ", i + 1);
- if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
- {
- free(headerOpt);
- return;
- }
- int optionID = atoi(getOptionID);
-
- headerOpt[i].optionID = optionID;
-
- printf("[%d] Option Data : ", i + 1);
- if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
- {
- free(headerOpt);
- return;
- }
-
- memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
- printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData);
-
- headerOpt[i].optionLength = (uint16_t) strlen(optionData);
- }
- printf("\n=============================================\n");
-
- // create token
- CAToken_t token = NULL;
- uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
- CAResult_t res = CAGenerateToken(&token, tokenLength);
- if ((CA_STATUS_OK != res) || (!token))
- {
- printf("Token generate error!!\n");
- free(headerOpt);
- return;
- }
-
- printf("Generated token %s\n", token);
-
- res = CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t) optionNum);
- if (CA_STATUS_OK != res)
- {
- printf("Could not start advertise resource\n");
- CADestroyToken(token);
- }
- else
- {
- CADestroyToken(g_last_request_token);
- g_last_request_token = token;
- }
-
- free(headerOpt);
-}
-
void send_notification()
{
CAResult_t res = get_network_type();
int messageType = messageTypeBuf[0] - '0';
// create remote endpoint
- CARemoteEndpoint_t *endpoint = NULL;
- res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
+ CAEndpoint_t *endpoint = NULL;
+ res = CACreateEndpoint(0, g_selected_nw_type, buf, 0, &endpoint);
if (CA_STATUS_OK != res)
{
printf("Create remote endpoint error, error code: %d\n", res);
if ((CA_STATUS_OK != res) || (!token))
{
printf("Token generate error!!\n");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return;
}
// destroy token
CADestroyToken(token);
// destroy remote endpoint
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
printf("\n=============================================\n");
}
void get_network_info()
{
- CALocalConnectivity_t *tempInfo = NULL;
+ CAEndpoint_t *tempInfo = NULL;
uint32_t tempSize = 0;
CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
int index;
for (index = 0; index < tempSize; index++)
{
- printf("Type: %d\n", tempInfo[index].type);
- if (CA_IPV4 == tempInfo[index].type)
+ printf("Type: %d\n", tempInfo[index].adapter);
+ if (CA_ADAPTER_IP == tempInfo[index].adapter)
{
- printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
- printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
+ printf("Address: %s\n", tempInfo[index].addr);
+ printf("Port: %d\n", tempInfo[index].port);
}
- else if (CA_EDR == tempInfo[index].type)
+ else if (CA_ADAPTER_RFCOMM_BTEDR == tempInfo[index].adapter)
{
- printf("Address: %s\n", tempInfo[index].addressInfo.BT.btMacAddress);
+ printf("Address: %s\n", tempInfo[index].addr);
}
- else if (CA_LE == tempInfo[index].type)
+ else if (CA_ADAPTER_GATT_BTLE == tempInfo[index].adapter)
{
- printf("Address: %s\n", tempInfo[index].addressInfo.LE.leMacAddress);
+ printf("Address: %s\n", tempInfo[index].addr);
}
- printf("Secured: %s\n\n", tempInfo[index].isSecured ? "true" : "false");
+ printf("Secured: %s\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" : "false");
- if (tempInfo[index].isSecured)
+ if (tempInfo[index].flags & CA_SECURE)
{
- g_local_secure_port = tempInfo[index].addressInfo.IP.port;
+ g_local_secure_port = tempInfo[index].port;
printf("Secured: in global %d\n\n", g_local_secure_port);
}
}
printf("##############################################################");
}
-void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
{
if (NULL == object || NULL == requestInfo)
{
}
printf("##########received request from remote device #############\n");
- printf("Uri: %s\n", object->resourceUri);
- if (CA_IPV4 == object->transportType)
+ if (CA_ADAPTER_IP == object->adapter)
{
- printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
- object->addressInfo.IP.port, object->isSecured);
+ printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
+ object->port, object->flags & CA_SECURE);
}
- else if (CA_EDR == object->transportType)
+ else if (CA_ADAPTER_RFCOMM_BTEDR == object->adapter)
{
- printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
+ printf("Remote Address: %s \n", object->addr);
}
- else if (CA_LE == object->transportType)
+ else if (CA_ADAPTER_GATT_BTLE == object->adapter)
{
- printf("Remote Address: %s \n", object->addressInfo.LE.leMacAddress);
+ printf("Remote Address: %s \n", object->addr);
}
printf("Data: %s\n", requestInfo->info.payload);
printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
//Check if this has secure communication information
if (requestInfo->info.payload &&
- (CA_IPV4 == object->transportType))
+ (CA_ADAPTER_IP == object->adapter))
{
int securePort = get_secure_information(requestInfo->info.payload);
if (0 < securePort) //Set the remote endpoint secure details and send response
size_t length = sizeof(SECURE_COAPS_PREFIX) - 1;
// length of "ipaddress:port"
- length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
- length += strlen(object->resourceUri) + 1;
+ length += strlen(object->addr) + PORT_LENGTH;
+ length += 1;
char *uri = calloc(1, sizeof(char) * length);
if (!uri)
printf("Failed to create new uri\n");
return;
}
- sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
- object->addressInfo.IP.port, object->resourceUri);
+ sprintf(uri, "%s%s:%d/", SECURE_COAPS_PREFIX, object->addr,
+ object->port);
- CARemoteEndpoint_t *endpoint = NULL;
- if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
+ CAEndpoint_t *endpoint = NULL;
+ if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, uri, 0, &endpoint))
{
printf("Failed to create duplicate of remote endpoint!\n");
return;
}
- endpoint->isSecured = true;
+ endpoint->flags = CA_SECURE;
object = endpoint;
free(uri);
g_received = 1;
}
-void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
{
printf("##########Received response from remote device #############\n");
- printf("Uri: %s\n", object->resourceUri);
- if (CA_IPV4 == object->transportType)
+ if (CA_ADAPTER_IP == object->adapter)
{
- printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
- object->addressInfo.IP.port, object->isSecured);
+ printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
+ object->port, object->flags & CA_SECURE);
}
- else if (CA_EDR == object->transportType)
+ else if (CA_ADAPTER_RFCOMM_BTEDR == object->adapter)
{
- printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
+ printf("Remote Address: %s \n", object->addr);
}
- else if (CA_LE == object->transportType)
+ else if (CA_ADAPTER_GATT_BTLE == object->adapter)
{
- printf("Remote Address: %s \n", object->addressInfo.LE.leMacAddress);
+ printf("Remote Address: %s \n", object->addr);
}
printf("response result : %d\n", responseInfo->result);
printf("Data: %s\n", responseInfo->info.payload);
}
}
-void error_handler(const CARemoteEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
+void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
{
printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
- if(rep && rep->resourceUri )
- {
- printf("Error Handler, RemoteEndpoint Info resourceUri : %s\n", rep->resourceUri);
- }
- else
- {
- printf("Error Handler, RemoteEndpoint is NULL");
- }
-
if(errorInfo)
{
const CAInfo_t *info = &errorInfo->info;
printf("Error Handler token : %s\n", info->token);
printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
printf("Error Handler type : %d\n", info->type);
+ printf("Error Handler resourceUri : %s\n", info->resourceUri);
printf("Error Handler payload : %s\n", info->payload);
if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
return;
}
-void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info)
+void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
{
printf("entering send_response\n");
responseData.token = (info != NULL) ? info->token : NULL;
responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
- if (endpoint->isSecured)
+ if (endpoint->flags & CA_SECURE)
{
printf("Sending response on secure communication\n");
- uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(endpoint->resourceUri);
+ uint32_t length = sizeof(SECURE_INFO_DATA);
responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
if (NULL == responseData.payload)
{
printf("Memory allocation fail\n");
return;
}
- snprintf(responseData.payload, length, SECURE_INFO_DATA, endpoint->resourceUri,
- g_local_secure_port);
+ snprintf(responseData.payload, length, SECURE_INFO_DATA, info->resourceUri, g_local_secure_port);
+ return;
}
else
{
printf("Sending response on non-secure communication\n");
- uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(endpoint->resourceUri);
+ uint32_t length = sizeof(NORMAL_INFO_DATA);
responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
if (NULL == responseData.payload)
{
printf("Memory allocation fail\n");
return;
}
- snprintf(responseData.payload, length, NORMAL_INFO_DATA, endpoint->resourceUri);
+ snprintf(responseData.payload, length, NORMAL_INFO_DATA, info->resourceUri);
+ return;
}
}
printf("\n=============================================\n");
printf("\tselect network type\n");
- printf("IPv4 : 0\n");
- printf("BT : 2\n");
- printf("LE : 3\n");
+ printf("IP : 1\n");
+ printf("GATT : 2\n");
+ printf("RFCOMM : 3\n");
printf("select : ");
if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
number = (number < 0 || number > 3) ? 0 : 1 << number;
- if (!(number & 0xf))
+ if (number == 1)
{
- return CA_NOT_SUPPORTED;
- }
- if (number & CA_IPV4)
- {
- g_selected_nw_type = CA_IPV4;
+ g_selected_nw_type = CA_ADAPTER_IP;
return CA_STATUS_OK;
}
- if (number & CA_EDR)
+ if (number == 2)
{
- g_selected_nw_type = CA_EDR;
+ g_selected_nw_type = CA_ADAPTER_GATT_BTLE;
return CA_STATUS_OK;
}
- if (number & CA_LE)
+ if (number == 3)
{
- g_selected_nw_type = CA_LE;
+ g_selected_nw_type = CA_ADAPTER_RFCOMM_BTEDR;
return CA_STATUS_OK;
}
- printf("\n=============================================\n");
-
- return CA_STATUS_FAILED;
+ return CA_NOT_SUPPORTED;
}
CAResult_t get_input_data(char *buf, int32_t length)
void find_resource();
void send_request();
void send_request_all();
-void advertise_resource();
void send_notification();
void select_network();
void unselect_network();
send_request();
break;
- case 'a': // advertise resource
- case 'A':
- advertise_resource();
- break;
-
case 'b': // send notification
case 'B':
send_notification();
printf("=============================================\n");
}
-void advertise_resource()
-{
- printf("\n=============================================\n");
- printf("uri : ");
-
- char buf[MAX_BUF_LEN] = { 0 };
- if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
- {
- return;
- }
-
- char optionNumBuf[MAX_BUF_LEN] = { 0 };
- char optionData[MAX_OPT_LEN] = { 0 } ;
-
- printf("Option Num : ");
- if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
- {
- return;
- }
- int optionNum = atoi(optionNumBuf);
-
- CAHeaderOption_t * headerOpt = (CAHeaderOption_t *)
- calloc(1, optionNum * sizeof(CAHeaderOption_t));
- if (NULL == headerOpt)
- {
- printf("Memory allocation failed!\n");
- return;
- }
-
- int i;
- for (i = 0; i < optionNum; i++)
- {
- char getOptionID[MAX_BUF_LEN] = { 0 } ;
-
- printf("[%d] Option ID : ", i + 1);
- if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
- {
- free(headerOpt);
- return;
- }
- int optionID = atoi(getOptionID);
-
- headerOpt[i].optionID = optionID;
-
- printf("[%d] Option Data : ", i + 1);
- if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
- {
- free(headerOpt);
- return;
- }
-
- memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
- printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData);
-
- headerOpt[i].optionLength = (uint16_t) strlen(optionData);
- }
- printf("\n=============================================\n");
-
- // create token
- CAToken_t token = NULL;
- uint8_t tokenLength = CA_MAX_TOKEN_LEN;
-
- CAResult_t res = CAGenerateToken(&token, tokenLength);
- if ((CA_STATUS_OK != res) || (!token))
- {
- printf("Token generate error!!\n");
- free(headerOpt);
- return;
- }
-
- printf("Generated token %s\n", token);
-
- res = CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t) optionNum);
- if (CA_STATUS_OK != res)
- {
- printf("Could not start advertise resource\n");
- CADestroyToken(token);
- }
- else
- {
- CADestroyToken(g_last_request_token);
- g_last_request_token = token;
- }
-
- free(headerOpt);
-}
-
void send_notification()
{
CAResult_t res = get_network_type();
if ca_os == 'arduino':
env.AppendUnique(CPPDEFINES = ['SINGLE_THREAD'])
+ env.AppendUnique(CPPDEFINES = ['WITH_ARDUINO'])
+ print "setting WITH_ARDUINO"
ca_common_src = [
ca_path + 'caconnectivitymanager_singlethread.c',
ca_path + 'cainterfacecontroller_singlethread.c',
#include "oic_malloc.h"
#include "oic_string.h"
#include "global.h"
+#include <netdb.h>
/**
* @def NET_DTLS_TAG
*/
static ca_mutex g_dtlsContextMutex = NULL;
-
/**
* @var g_getCredentialsCallback
* @brief callback to get DTLS credentials
*/
static CAGetDTLSCredentialsHandler g_getCredentialsCallback = NULL;
-static stCADtlsPeerInfo_t * GetPeerInfo(const char *peerAddr, uint32_t port)
+static CAEndpoint_t *GetPeerInfo(const CAEndpoint_t *peer)
{
uint32_t list_index = 0;
uint32_t list_length = 0;
- if(NULL == peerAddr || 0 == port)
+ if(NULL == peer)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "CAPeerInfoListContains invalid parameters");
return NULL;
}
- stCADtlsPeerInfo_t *peerInfo;
+ CAEndpoint_t *peerInfo;
list_length = u_arraylist_length(g_caDtlsContext->peerInfoList);
for (list_index = 0; list_index < list_length; list_index++)
{
- peerInfo = (stCADtlsPeerInfo_t *)u_arraylist_get(g_caDtlsContext->peerInfoList, list_index);
+ peerInfo = (CAEndpoint_t *)u_arraylist_get(g_caDtlsContext->peerInfoList, list_index);
if (NULL == peerInfo)
{
continue;
}
- if((0 == strncmp(peerAddr, peerInfo->address.IP.ipAddress, CA_IPADDR_SIZE)) &&
- (port == peerInfo->address.IP.port))
+ if((0 == strncmp(peer->addr, peerInfo->addr, MAX_ADDR_STR_SIZE_CA)) &&
+ (peer->port == peerInfo->port))
{
return peerInfo;
}
}
static CAResult_t CAAddIdToPeerInfoList(const char *peerAddr, uint32_t port,
- const unsigned char * id,uint16_t id_length)
+ const unsigned char *id, uint16_t id_length)
{
if(NULL == peerAddr || NULL == id || 0 == port || 0 == id_length)
{
return CA_STATUS_INVALID_PARAM;
}
- if(NULL != GetPeerInfo(peerAddr, port))
- {
- OIC_LOG(ERROR, NET_DTLS_TAG, "CAAddIdToPeerInfoList peer already exist");
- return CA_STATUS_FAILED;
- }
-
- stCADtlsPeerInfo_t *peerInfo = (stCADtlsPeerInfo_t *)
- OICCalloc(1, sizeof(stCADtlsPeerInfo_t));
- if (NULL == peerInfo)
+ CAEndpoint_t *peer = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
+ if (NULL == peer)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "peerInfo malloc failed!");
return CA_MEMORY_ALLOC_FAILED;
}
- OICStrcpy(peerInfo->address.IP.ipAddress, sizeof(peerInfo->address.IP.ipAddress),
- peerAddr);
- peerInfo->address.IP.port = port;
- OICStrcpyPartial(peerInfo->identity.id, sizeof(peerInfo->identity.id), id, id_length);
- peerInfo->identity.id_length = id_length;
+ OICStrcpy(peer->addr, sizeof(peer->addr), peerAddr);
+ peer->port = port;
+ OICStrcpyPartial(peer->identity.id, sizeof(peer->identity.id), id, id_length);
+ peer->identity.id_length = id_length;
- CAResult_t result = u_arraylist_add(g_caDtlsContext->peerInfoList, (void *)peerInfo);
+ if(NULL != GetPeerInfo(peer))
+ {
+ OIC_LOG(ERROR, NET_DTLS_TAG, "CAAddIdToPeerInfoList peer already exist");
+ OICFree(peer);
+ return CA_STATUS_FAILED;
+ }
+ CAResult_t result = u_arraylist_add(g_caDtlsContext->peerInfoList, (void *)peer);
if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "u_arraylist_add failed!");
- OICFree(peerInfo);
+ OICFree(peer);
}
return result;
}
-
static void CAFreePeerInfoList()
{
uint32_t list_length = u_arraylist_length(g_caDtlsContext->peerInfoList);
for (uint32_t list_index = 0; list_index < list_length; list_index++)
{
- stCADtlsPeerInfo_t * peerInfo = (stCADtlsPeerInfo_t *)u_arraylist_get(
- g_caDtlsContext->peerInfoList, list_index);
+ CAEndpoint_t *peerInfo = (CAEndpoint_t *)u_arraylist_get(
+ g_caDtlsContext->peerInfoList, list_index);
OICFree(peerInfo);
}
u_arraylist_free(&(g_caDtlsContext->peerInfoList));
static void CARemovePeerFromPeerInfoList(const char * addr, uint32_t port)
{
- if(NULL == addr || 0 >= port)
+ if (NULL == addr || 0 >= port)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "CADTLSGetPeerPSKId invalid parameters");
return;
uint32_t list_length = u_arraylist_length(g_caDtlsContext->peerInfoList);
for (uint32_t list_index = 0; list_index < list_length; list_index++)
{
- stCADtlsPeerInfo_t * peerInfo = (stCADtlsPeerInfo_t *)u_arraylist_get(
+ CAEndpoint_t *peerInfo = (CAEndpoint_t *)u_arraylist_get(
g_caDtlsContext->peerInfoList,list_index);
if (NULL == peerInfo)
{
continue;
}
- if((0 == strncmp(addr, peerInfo->address.IP.ipAddress, CA_IPADDR_SIZE)) &&
- (port == peerInfo->address.IP.port))
+ if((0 == strncmp(addr, peerInfo->addr, MAX_ADDR_STR_SIZE_CA)) &&
+ (port == peerInfo->port))
{
OICFree(u_arraylist_remove(g_caDtlsContext->peerInfoList, list_index));
return;
}
}
+static int CASizeOfAddrInfo(stCADtlsAddrInfo_t *addrInfo)
+{
+ VERIFY_NON_NULL_RET(addrInfo, NET_DTLS_TAG, "addrInfo is NULL" , DTLS_FAIL);
+
+ switch (addrInfo->addr.st.ss_family)
+ {
+ case AF_INET:
+ {
+ return sizeof (struct sockaddr_in);
+ }
+ case AF_INET6:
+ {
+ return sizeof (struct sockaddr_in6);
+ }
+ default:
+ {
+ break;
+ }
+ }
+ return sizeof (struct sockaddr_storage);
+}
+
static eDtlsRet_t CAAdapterNetDtlsEncryptInternal(const stCADtlsAddrInfo_t *dstSession,
uint8_t *data, uint32_t dataLen)
{
static bool CAIsAddressMatching(const stCADtlsAddrInfo_t *a, const stCADtlsAddrInfo_t *b)
{
- return (a->size == b->size) &&
- (a->addr.sa.sa_family == b->addr.sa.sa_family) &&
- (a->addr.sin.sin_port == b->addr.sin.sin_port) &&
- memcmp(&a->addr.sin.sin_addr, &b->addr.sin.sin_addr, sizeof(struct in_addr)) == 0;
+ if (a->size != b->size)
+ {
+ return false;
+ }
+ if (memcmp(&a->addr, &b->addr, a->size))
+ {
+ return false;
+ }
+ return true;
}
static void CASendCachedMsg(const stCADtlsAddrInfo_t *dstSession)
stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
- char *remoteAddress = inet_ntoa(addrInfo->addr.sin.sin_addr);
- uint32_t port = ntohs(addrInfo->addr.sin.sin_port);
- CATransportType_t type = (CATransportType_t)addrInfo->ifIndex;
+ CAEndpoint_t endpoint = { 0 };
+ CAConvertAddrToName(&(addrInfo->addr.st), endpoint.addr, &endpoint.port);
+ endpoint.flags = addrInfo->addr.st.ss_family == AF_INET ? CA_IPV4 : CA_IPV6;
+ endpoint.flags |= CA_SECURE;
+ endpoint.adapter = CA_ADAPTER_IP;
+ int type = 0;
if (NULL == g_caDtlsContext)
{
if ((0 <= type) && (MAX_SUPPORTED_ADAPTERS > type) &&
(NULL != g_caDtlsContext->adapterCallbacks[type].recvCallback))
{
- // Get identity of sthe source of packet
- stCADtlsPeerInfo_t * peerInfo = GetPeerInfo(remoteAddress, port);
+ // Get identity of the source of packet
+ CAEndpoint_t *peerInfo = GetPeerInfo(&endpoint);
+ if (peerInfo)
+ {
+ endpoint.identity = peerInfo->identity;
+ }
- g_caDtlsContext->adapterCallbacks[type].recvCallback(remoteAddress, port,
- buf, bufLen, true,
- (peerInfo) ? &(peerInfo->identity) : NULL);
+ g_caDtlsContext->adapterCallbacks[type].recvCallback(&endpoint, buf, bufLen);
}
else
{
stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
- char *remoteAddress = inet_ntoa(addrInfo->addr.sin.sin_addr);
- uint16_t port = ntohs(addrInfo->addr.sin.sin_port);
- CATransportType_t type = (CATransportType_t)addrInfo->ifIndex;
+ CAEndpoint_t endpoint;
+ CAConvertAddrToName(&(addrInfo->addr.st), endpoint.addr, &endpoint.port);
+ endpoint.flags = addrInfo->addr.st.ss_family == AF_INET ? CA_IPV4 : CA_IPV6;
+ endpoint.flags |= CA_SECURE;
+ endpoint.adapter = CA_ADAPTER_IP;
+ int type = 0;
//Mutex is not required for g_caDtlsContext. It will be called in same thread.
int32_t sentLen = 0;
if ((0 <= type) && (MAX_SUPPORTED_ADAPTERS > type) &&
(NULL != g_caDtlsContext->adapterCallbacks[type].sendCallback))
{
- sentLen = g_caDtlsContext->adapterCallbacks[type].sendCallback(remoteAddress, port,
- buf, bufLen);
+ sentLen = g_caDtlsContext->adapterCallbacks[type].sendCallback(&endpoint, buf, bufLen);
}
else
{
}
void CADTLSSetAdapterCallbacks(CAPacketReceivedCallback recvCallback,
- CAPacketSendCallback sendCallback, CATransportType_t type)
+ CAPacketSendCallback sendCallback,
+ CATransportAdapter_t type)
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
ca_mutex_lock(g_dtlsContextMutex);
if ((0 <= type) && (MAX_SUPPORTED_ADAPTERS > type))
{
- g_caDtlsContext->adapterCallbacks[type].recvCallback = recvCallback;
- g_caDtlsContext->adapterCallbacks[type].sendCallback = sendCallback;
+ // TODO: change the zeros to better values.
+ g_caDtlsContext->adapterCallbacks[0].recvCallback = recvCallback;
+ g_caDtlsContext->adapterCallbacks[0].sendCallback = sendCallback;
}
ca_mutex_unlock(g_dtlsContextMutex);
return CA_STATUS_OK ;
}
-CAResult_t CADtlsInitiateHandshake(const CAAddress_t* addrInfo,
- const CATransportType_t transportType)
+CAResult_t CADtlsInitiateHandshake(const CAEndpoint_t *endpoint)
{
stCADtlsAddrInfo_t dst = {};
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN CADtlsInitiateHandshake");
- if(!addrInfo)
+ if(!endpoint)
{
return CA_STATUS_INVALID_PARAM;
}
- if(inet_aton(addrInfo->IP.ipAddress, &dst.addr.sin.sin_addr) == 0)
- {
- OIC_LOG(ERROR, NET_DTLS_TAG, "Failed to convert from ASCII to Network Address");
- return CA_STATUS_FAILED;
- }
- dst.addr.sin.sin_family = AF_INET;
- dst.addr.sin.sin_port = htons(addrInfo->IP.port);
- dst.size = sizeof(dst.addr);
-
- dst.ifIndex = transportType;
+ CAConvertNameToAddr(endpoint->addr, endpoint->port, &(dst.addr.st));
+ dst.ifIndex = 0;
+ dst.size = CASizeOfAddrInfo(&dst);
ca_mutex_lock(g_dtlsContextMutex);
if(NULL == g_caDtlsContext)
return CA_STATUS_OK;
}
-CAResult_t CADtlsClose(const CAAddress_t* addrInfo, const CATransportType_t transportType)
+CAResult_t CADtlsClose(const CAEndpoint_t *endpoint)
{
stCADtlsAddrInfo_t dst = {};
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN CADtlsDisconnect");
- if(!addrInfo)
+ if(!endpoint)
{
return CA_STATUS_INVALID_PARAM;
}
- if(inet_aton(addrInfo->IP.ipAddress, &dst.addr.sin.sin_addr) == 0)
- {
- OIC_LOG(ERROR, NET_DTLS_TAG, "Failed to convert from ASCII to Network Address");
- return CA_STATUS_FAILED;
- }
- dst.addr.sin.sin_family = AF_INET;
- dst.addr.sin.sin_port = htons(addrInfo->IP.port);
- dst.size = sizeof(dst.addr);
-
- dst.ifIndex = transportType;
+ CAConvertNameToAddr(endpoint->addr, endpoint->port, &(dst.addr.st));
+ dst.ifIndex = 0;
+ dst.size = CASizeOfAddrInfo(&dst);
ca_mutex_lock(g_dtlsContextMutex);
- if(NULL == g_caDtlsContext)
+ if (NULL == g_caDtlsContext)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
ca_mutex_unlock(g_dtlsContextMutex);
return CA_STATUS_FAILED;
}
- if(0 > dtls_close(g_caDtlsContext->dtlsContext, (session_t*)(&dst)))
+ if (0 > dtls_close(g_caDtlsContext->dtlsContext, (session_t*)(&dst)))
{
OIC_LOG(ERROR, NET_DTLS_TAG, "Failed to close the session");
ca_mutex_unlock(g_dtlsContextMutex);
return CA_STATUS_OK;
}
-CAResult_t CADtlsGenerateOwnerPSK(const CAAddress_t* addrInfo,
- const CATransportType_t transportType,
+CAResult_t CADtlsGenerateOwnerPSK(const CAEndpoint_t *endpoint,
const uint8_t* label, const size_t labelLen,
const uint8_t* rsrcServerDeviceID, const size_t rsrcServerDeviceIDLen,
const uint8_t* provServerDeviceID, const size_t provServerDeviceIDLen,
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN CADtlsGenerateOwnerPSK");
- if(!addrInfo || !label || 0 == labelLen || !ownerPSK || 0 == ownerPSKSize)
+ if(!endpoint || !label || 0 == labelLen || !ownerPSK || 0 == ownerPSKSize)
{
return CA_STATUS_INVALID_PARAM;
}
stCADtlsAddrInfo_t dst = {};
- if(inet_aton(addrInfo->IP.ipAddress, &dst.addr.sin.sin_addr) == 0)
- {
- OIC_LOG(ERROR, NET_DTLS_TAG, "Failed to convert from ASCII to Network Address");
- return CA_STATUS_FAILED;
- }
- dst.addr.sin.sin_family = AF_INET;
- dst.addr.sin.sin_port = htons(addrInfo->IP.port);
- dst.size = sizeof(dst.addr);
-
- dst.ifIndex = transportType;
+ CAConvertNameToAddr(endpoint->addr, endpoint->port, &(dst.addr.st));
+ dst.ifIndex = 0;
+ dst.size = CASizeOfAddrInfo(&dst);
ca_mutex_lock(g_dtlsContextMutex);
if (NULL == g_caDtlsContext)
if( (NULL == g_caDtlsContext->peerInfoList) ||
(NULL == g_caDtlsContext->cacheList))
{
- OIC_LOG(ERROR, NET_DTLS_TAG, "peerInfoList or cacheList initialization failed!");
+ OIC_LOG(ERROR, NET_DTLS_TAG, "peerInfoList or cacheList initialization failed!");
CAClearCacheList();
CAFreePeerInfoList();
OICFree(g_caDtlsContext);
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
}
-CAResult_t CAAdapterNetDtlsEncrypt(const char *remoteAddress,
- const uint16_t port,
- void *data,
- uint32_t dataLen,
- CATransportType_t transportType)
+CAResult_t CAAdapterNetDtlsEncrypt(const CAEndpoint_t *endpoint,
+ void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
- VERIFY_NON_NULL_RET(remoteAddress, NET_DTLS_TAG,"Param remoteAddress is NULL",CA_STATUS_FAILED);
-
- VERIFY_NON_NULL_RET(data, NET_DTLS_TAG, "Param data is NULL" , CA_STATUS_FAILED);
+ VERIFY_NON_NULL_RET(endpoint, NET_DTLS_TAG,"Param remoteAddress is NULL",
+ CA_STATUS_INVALID_PARAM);
+ VERIFY_NON_NULL_RET(data, NET_DTLS_TAG, "Param data is NULL" ,
+ CA_STATUS_INVALID_PARAM);
if (0 == dataLen)
{
stCADtlsAddrInfo_t addrInfo = {};
- addrInfo.addr.sin.sin_family = AF_INET;
- addrInfo.addr.sin.sin_port = htons(port);
- // Conversion from ASCII format to Network format
- if (inet_aton(remoteAddress, &addrInfo.addr.sin.sin_addr) == 0)
- {
- OIC_LOG(ERROR, NET_DTLS_TAG, "Failed to convert from ASCII to Network Address");
- return CA_STATUS_FAILED;
- }
- addrInfo.size = sizeof(addrInfo.addr);
- addrInfo.ifIndex = transportType;
+ CAConvertNameToAddr(endpoint->addr, endpoint->port, &(addrInfo.addr.st));
+ addrInfo.ifIndex = 0;
+ addrInfo.size = CASizeOfAddrInfo(&addrInfo);
ca_mutex_lock(g_dtlsContextMutex);
if(NULL == g_caDtlsContext)
ca_mutex_unlock(g_dtlsContextMutex);
- if (ret == DTLS_OK)
+ if (ret != DTLS_OK)
{
- OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
- return CA_STATUS_OK;
+ OIC_LOG(ERROR, NET_DTLS_TAG, "OUT FAILURE");
+ return CA_STATUS_FAILED;
}
- OIC_LOG(ERROR, NET_DTLS_TAG, "OUT FAILURE");
- return CA_STATUS_FAILED;
+ OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
+ return CA_STATUS_OK;
}
-
-CAResult_t CAAdapterNetDtlsDecrypt(const char *remoteAddress,
- const uint16_t port,
- uint8_t *data,
- uint32_t dataLen,
- CATransportType_t transportType)
+CAResult_t CAAdapterNetDtlsDecrypt(const CAEndpoint_t *endpoint,
+ uint8_t *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+ VERIFY_NON_NULL_RET(endpoint, NET_DTLS_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
stCADtlsAddrInfo_t addrInfo = {};
- addrInfo.addr.sin.sin_family = AF_INET;
- addrInfo.addr.sin.sin_port = htons(port);
-
- // Conversion from ASCII format to Network format
- if (inet_aton(remoteAddress, &addrInfo.addr.sin.sin_addr) == 0)
- {
- OIC_LOG(ERROR, NET_DTLS_TAG, "Failed to convert from ASCII to Network Address");
- return CA_STATUS_FAILED;
- }
- addrInfo.size = sizeof(addrInfo.addr);
- addrInfo.ifIndex = transportType;
+ CAConvertNameToAddr(endpoint->addr, endpoint->port, &(addrInfo.addr.st));
+ addrInfo.ifIndex = 0;
+ addrInfo.size = CASizeOfAddrInfo(&addrInfo);
ca_mutex_lock(g_dtlsContextMutex);
- if(NULL == g_caDtlsContext)
+ if (NULL == g_caDtlsContext)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
ca_mutex_unlock(g_dtlsContextMutex);
#include <ctype.h>
#include "oic_string.h"
#include "oic_malloc.h"
+#include <errno.h>
+
+#ifndef WITH_ARDUINO
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netdb.h>
+#endif
#ifdef __ANDROID__
#include <jni.h>
OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - token : %s", pdu->hdr->token);
}
-
-CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CATransportType_t type, const char *address)
-{
- CALocalConnectivity_t *info = (CALocalConnectivity_t *)
- OICCalloc(1, sizeof(CALocalConnectivity_t));
- if (NULL == info)
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
- return NULL;
- }
-
- info->type = type;
- if (address && strlen(address))
- {
- if (CA_EDR == type)
- {
- OICStrcpy(info->addressInfo.BT.btMacAddress, sizeof(info->addressInfo.BT.btMacAddress),
- address);
- }
- else if (CA_LE == type)
- {
- OICStrcpy(info->addressInfo.LE.leMacAddress, sizeof(info->addressInfo.LE.leMacAddress),
- address);
- }
- else if (CA_IPV4 == type)
- {
- OICStrcpy(info->addressInfo.IP.ipAddress, sizeof(info->addressInfo.IP.ipAddress),
- address);
- }
- else if (CA_IPV6 == type)
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported");
- OICFree(info);
- return NULL;
- }
- else
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!");
- OICFree(info);
- return NULL;
- }
- }
-
- return info;
-}
-
-CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(const CALocalConnectivity_t *connectivity)
+CAEndpoint_t *CAAdapterCreateEndpoint(CATransportFlags_t flags,
+ CATransportAdapter_t adapter,
+ const char *address,
+ uint16_t port)
{
- VERIFY_NON_NULL_RET(connectivity, CA_ADAPTER_UTILS_TAG, "connectivity is NULL", NULL);
-
- CALocalConnectivity_t *info = (CALocalConnectivity_t *)
- OICCalloc(1, sizeof(CALocalConnectivity_t));
+ VERIFY_NON_NULL_RET(address, CA_ADAPTER_UTILS_TAG, "Endpoint is NULL", NULL);
+ CAEndpoint_t *info = (CAEndpoint_t *)OICCalloc(1, sizeof(CAEndpoint_t));
if (NULL == info)
{
OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
return NULL;
}
- info->type = connectivity->type;
- if (CA_EDR == info->type && strlen(connectivity->addressInfo.BT.btMacAddress))
- {
- OICStrcpy(info->addressInfo.BT.btMacAddress, sizeof(info->addressInfo.BT.btMacAddress),
- connectivity->addressInfo.BT.btMacAddress);
- }
- else if (CA_LE == info->type && strlen(connectivity->addressInfo.LE.leMacAddress))
- {
- OICStrcpy(info->addressInfo.LE.leMacAddress, sizeof(info->addressInfo.LE.leMacAddress),
- connectivity->addressInfo.LE.leMacAddress);
- }
- else if ((CA_IPV4 == info->type)
-
- && strlen(connectivity->addressInfo.IP.ipAddress))
- {
- OICStrcpy(info->addressInfo.IP.ipAddress, sizeof(info->addressInfo.IP.ipAddress),
- connectivity->addressInfo.IP.ipAddress);
- info->addressInfo.IP.port = connectivity->addressInfo.IP.port;
- }
- else if (CA_IPV6 == info->type)
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported");
- OICFree(info);
- return NULL;
- }
- else
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!");
- OICFree(info);
- return NULL;
- }
+ OICStrcpy(info->addr, sizeof(info->addr), address);
+ info->addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
+ info->flags = flags;
+ info->adapter = adapter;
+ info->port = port;
- info->isSecured = connectivity->isSecured;
return info;
}
-void CAAdapterFreeLocalEndpoint(CALocalConnectivity_t *localEndpoint)
+CAEndpoint_t *CAAdapterCreateLocalEndpoint(CATransportFlags_t flags,
+ CATransportAdapter_t adapter, const char *address)
{
- OICFree(localEndpoint);
+ return CAAdapterCreateEndpoint(flags, adapter, address, 0);
}
-CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CATransportType_t type, const char *address,
- const char *resourceUri)
+CAResult_t CACreateEndpoint(CATransportFlags_t flags,
+ CATransportAdapter_t adapter,
+ const CAURI_t uri,
+ uint16_t port,
+ CAEndpoint_t **object)
{
- CARemoteEndpoint_t *info = (CARemoteEndpoint_t *)
- OICCalloc(1, sizeof(CARemoteEndpoint_t));
- if (NULL == info)
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
- return NULL;
- }
-
- info->transportType = type;
- if (address && strlen(address))
- {
- if (CA_EDR == type)
- {
- OICStrcpy(info->addressInfo.BT.btMacAddress, sizeof(info->addressInfo.BT.btMacAddress),
- address);
- }
- else if (CA_LE == type)
- {
- OICStrcpy(info->addressInfo.LE.leMacAddress, sizeof(info->addressInfo.LE.leMacAddress),
- address);
- }
- else if (CA_IPV4 == type)
- {
- OICStrcpy(info->addressInfo.IP.ipAddress, sizeof(info->addressInfo.IP.ipAddress),
- address);
- }
- else if (CA_IPV6 == type)
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported");
- OICFree(info);
- return NULL;
- }
- else
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!");
- OICFree(info);
- return NULL;
- }
- }
-
- if (resourceUri && strlen(resourceUri))
+ VERIFY_NON_NULL_RET(object, CA_ADAPTER_UTILS_TAG, "Endpoint is NULL", CA_STATUS_INVALID_PARAM);
+ CAEndpoint_t *endpoint = CAAdapterCreateEndpoint(flags, adapter, uri, port);
+ if (!endpoint)
{
- info->resourceUri = OICStrdup(resourceUri);
+ return CA_STATUS_FAILED;
}
-
- return info;
+ *object = endpoint;
+ return CA_STATUS_OK;
}
-CARemoteEndpoint_t *CAAdapterCopyRemoteEndpoint(const CARemoteEndpoint_t *remoteEndpoint)
+
+CAEndpoint_t *CAAdapterCloneEndpoint(const CAEndpoint_t *endpoint)
{
- VERIFY_NON_NULL_RET(remoteEndpoint, CA_ADAPTER_UTILS_TAG, "Remote endpoint is NULL", NULL);
+ VERIFY_NON_NULL_RET(endpoint, CA_ADAPTER_UTILS_TAG, "endpoint is NULL", NULL);
- CARemoteEndpoint_t *info = (CARemoteEndpoint_t *)
- OICCalloc(1, sizeof(CARemoteEndpoint_t));
+ CAEndpoint_t *info = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
if (NULL == info)
{
OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
return NULL;
}
+ *info = *endpoint;
- info->transportType = remoteEndpoint->transportType;
- if (CA_EDR == info->transportType && ('\0' != remoteEndpoint->addressInfo.BT.btMacAddress[0]))
- {
- OICStrcpy(info->addressInfo.BT.btMacAddress, sizeof(info->addressInfo.BT.btMacAddress),
- remoteEndpoint->addressInfo.BT.btMacAddress);
- }
- else if (CA_LE == info->transportType
- && ('\0' != remoteEndpoint->addressInfo.LE.leMacAddress[0]))
- {
- OICStrcpy(info->addressInfo.LE.leMacAddress, sizeof(info->addressInfo.LE.leMacAddress),
- remoteEndpoint->addressInfo.LE.leMacAddress);
- }
- else if ((CA_IPV4 == info->transportType)
- && ('\0' != remoteEndpoint->addressInfo.IP.ipAddress[0]))
- {
- OICStrcpy(info->addressInfo.IP.ipAddress, sizeof(info->addressInfo.IP.ipAddress),
- remoteEndpoint->addressInfo.IP.ipAddress);
- info->addressInfo.IP.port = remoteEndpoint->addressInfo.IP.port;
- }
- else if (CA_IPV6 == info->transportType)
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported");
- }
- else
- {
- OIC_LOG(DEBUG, CA_ADAPTER_UTILS_TAG, "Its not matching. May be multicast.");
- }
-
- //For Multicast, remote address will be null while resourceUri will have the service UUID
-
- if (remoteEndpoint->resourceUri && strlen(remoteEndpoint->resourceUri))
- {
- info->resourceUri = OICStrdup(remoteEndpoint->resourceUri);
- }
-
- info->isSecured = remoteEndpoint->isSecured;
- info->identity = remoteEndpoint->identity;
return info;
}
-void CAAdapterFreeRemoteEndpoint(CARemoteEndpoint_t *remoteEndpoint)
+void CAAdapterFreeEndpoint(CAEndpoint_t *remoteEndpoint)
{
- if (remoteEndpoint)
- {
- OICFree(remoteEndpoint->resourceUri);
- OICFree(remoteEndpoint);
- }
+ OICFree(remoteEndpoint);
}
CAResult_t CAParseIPv4AddressInternal(const char *ipAddrStr, uint8_t *ipAddr,
&& ((ipList1[3] & maskList[3]) == (ipList2[3] & maskList[3]));
}
-
bool CAIsMulticastServerStarted(const u_arraylist_t *serverInfoList, const char *ipAddress,
const char *multicastAddress, uint16_t port)
{
return false;
}
- if (info->isMulticastServer && (strncmp(info->ipAddress, multicastAddress,
- strlen(multicastAddress) == 0))
- && (info->port == port) && (strncmp(info->ifAddr, ipAddress, strlen(ipAddress)) == 0))
+ if (info->isMulticastServer && (strncmp(info->endpoint.addr, multicastAddress,
+ strlen(multicastAddress)) == 0)
+ && (info->endpoint.port == port) && (strncmp(info->ifAddr, ipAddress, strlen(ipAddress)) == 0))
{
return info->isServerStarted;
}
continue;
}
- if (!info->isMulticastServer && (strncmp(info->ipAddress, ipAddress,
+ if (!info->isMulticastServer && (strncmp(info->endpoint.addr, ipAddress,
strlen(ipAddress)) == 0)
- && (info->port == port))
+ && (info->endpoint.port == port))
{
return info->isServerStarted;
}
{
continue;
}
- if ((strncmp(info->ipAddress, ipAddress, strlen(ipAddress)) == 0) &&
- (info->isSecured == isSecured))
+ bool ifSecured = info->endpoint.flags & CA_SECURE;
+ if ((strncmp(info->endpoint.addr, ipAddress, strlen(ipAddress)) == 0) &&
+ (ifSecured == isSecured))
{
- return info->port;
+ return info->endpoint.port;
}
}
return 0;
}
-int CAGetSocketFdForUnicastServer(const u_arraylist_t *serverInfoList, const char *ipAddress,
- bool isSecured, bool isMulticast, CATransportType_t type)
+int CAGetSocketFdForUnicastServer(const u_arraylist_t *serverInfoList,
+ bool isMulticast, const CAEndpoint_t *endpoint)
{
VERIFY_NON_NULL_RET(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null", -1);
- VERIFY_NON_NULL_RET(ipAddress, CA_ADAPTER_UTILS_TAG, "ipAddress is null", -1);
+ VERIFY_NON_NULL_RET(endpoint, CA_ADAPTER_UTILS_TAG, "endpoint is null", -1);
+
+ bool isSecured = (endpoint->flags & CA_SECURE) != 0;
uint32_t listLength = u_arraylist_length(serverInfoList);
continue;
}
- if (!CAAdapterIsSameSubnet(info->ipAddress, ipAddress, info->subNetMask))
+ if (!CAAdapterIsSameSubnet(info->endpoint.addr, endpoint->addr, info->subNetMask))
{
continue;
}
- if (!info->isMulticastServer && (info->isSecured == isSecured))
+ bool ifSecured = info->endpoint.flags & CA_SECURE;
+ if (!info->isMulticastServer && (ifSecured == isSecured))
{
OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG,
"CAGetSocketFdForServer found socket [%d]", info->socketFd);
u_arraylist_free(&serverInfoList);
}
+#ifndef WITH_ARDUINO
+/*
+ * These two conversion functions return void because errors can't happen
+ * (because of NI_NUMERIC), and there's nothing to do if they do happen.
+ */
+void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, char *host, uint16_t *port)
+{
+ VERIFY_NON_NULL_VOID(sockAddr, CA_ADAPTER_UTILS_TAG, "sockAddr is null");
+ VERIFY_NON_NULL_VOID(host, CA_ADAPTER_UTILS_TAG, "host is null");
+ VERIFY_NON_NULL_VOID(port, CA_ADAPTER_UTILS_TAG, "port is null");
+
+ int r = getnameinfo((struct sockaddr *)sockAddr,
+ sizeof (struct sockaddr_storage),
+ host, CA_IPADDR_SIZE,
+ NULL, 0,
+ NI_NUMERICHOST|NI_NUMERICSERV);
+ if (r)
+ {
+ if (EAI_SYSTEM == r)
+ {
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getaddrinfo failed: errno %s", strerror(errno));
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getaddrinfo failed: %s", gai_strerror(r));
+ }
+ return;
+ }
+ *port = ntohs(((struct sockaddr_in *)sockAddr)->sin_port); // IPv4 and IPv6
+}
+
+void CAConvertNameToAddr(const char *host, uint16_t port, struct sockaddr_storage *sockaddr)
+{
+ VERIFY_NON_NULL_VOID(host, CA_ADAPTER_UTILS_TAG, "host is null");
+ VERIFY_NON_NULL_VOID(sockaddr, CA_ADAPTER_UTILS_TAG, "sockaddr is null");
+
+ struct addrinfo *addrs;
+ struct addrinfo hints = { 0 };
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = SOCK_DGRAM;
+ hints.ai_flags = AI_NUMERICHOST;
+
+ int r = getaddrinfo(host, NULL, &hints, &addrs);
+ if (r)
+ {
+ if (EAI_SYSTEM == r)
+ {
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getaddrinfo failed: errno %s", strerror(errno));
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getaddrinfo failed: %s", gai_strerror(r));
+ }
+ return;
+ }
+ // assumption: in this case, getaddrinfo will only return one addrinfo
+ // or first is the one we want.
+ if (addrs[0].ai_family == AF_INET6)
+ {
+ memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
+ ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
+ }
+ else
+ {
+ memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
+ ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
+ }
+ freeaddrinfo(addrs);
+}
+#endif // WITH_ARDUINO
+
#ifdef __ANDROID__
void CANativeJNISetContext(JNIEnv *env, jobject context)
{
/**
* implement for BT-EDR adapter common method
*/
-CAResult_t CAEDRGetInterfaceInformation(CALocalConnectivity_t **info)
+CAResult_t CAEDRGetInterfaceInformation(CAEndpoint_t **info)
{
OIC_LOG(DEBUG, TAG, "IN - CAEDRGetInterfaceInformation");
if (!info)
{
- OIC_LOG(ERROR, TAG, "LocalConnectivity info is null");
+ OIC_LOG(ERROR, TAG, "endpoint info is null");
return CA_STATUS_FAILED;
}
}
// Create local endpoint using util function
- CALocalConnectivity_t *endpoint = CAAdapterCreateLocalEndpoint(CA_EDR, macAddress);
+ CAEndpoint_t *endpoint = CAAdapterCreateEndpoint(CA_DEFAULT_FLAGS,
+ CA_RFCOMM_ADAPTER, macAddress, 0);
if (NULL == endpoint)
{
OIC_LOG(ERROR, TAG, "Failed to create Local Endpoint!");
}
// copy unicast server information
- endpoint->isSecured = false;
- CALocalConnectivity_t *netInfo = (CALocalConnectivity_t *) OICMalloc(
- sizeof(CALocalConnectivity_t) * netInfoSize);
+ CAEndpoint_t *netInfo = (CAEndpoint_t *)OICMalloc(sizeof(CAEndpoint_t) * netInfoSize);
if (NULL == netInfo)
{
OIC_LOG(ERROR, TAG, "Invalid input..");
OICFree(macAddress);
- CAAdapterFreeLocalEndpoint(endpoint);
+ CAAdapterFreeEndpoint(endpoint);
return CA_MEMORY_ALLOC_FAILED;
}
- memcpy(netInfo, endpoint, sizeof(CALocalConnectivity_t));
+ *netInfo = *endpoint;
*info = netInfo;
OICFree(macAddress);
- CAAdapterFreeLocalEndpoint(endpoint);
+ CAAdapterFreeEndpoint(endpoint);
OIC_LOG(DEBUG, TAG, "OUT - CAEDRGetInterfaceInformation");
return CA_STATUS_OK;
* @var g_localConnectivity
* @brief Information of local Bluetooth adapter.
*/
-static CALocalConnectivity_t *g_localConnectivity = NULL;
+static CAEndpoint_t *g_localConnectivity = NULL;
/**
* @var g_serverId
void CAEDROnNetworkStatusChanged(void *context);
CAResult_t CAAdapterSendData(const char *remoteAddress, const char *serviceUUID, const void *data,
uint32_t dataLength, uint32_t *sentLength);
-CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CALocalConnectivity_t *connectivity,
+CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CAEndpoint_t *connectivity,
CANetworkStatus_t status);
CAResult_t CAEDRClientSendData(const char *remoteAddress, const char *serviceUUID,
const void *data, uint32_t dataLength, uint32_t *sentLength);
* @fn CACreateEDRData
* @brief Helper function to create CAEDRData
*/
-static CAEDRData *CACreateEDRData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+static CAEDRData *CACreateEDRData(const CAEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
/**
handler.readData = CAReadEDRData;
handler.stopAdapter = CAStopEDR;
handler.terminate = CATerminateEDR;
- registerCallback(handler, CA_EDR);
+ registerCallback(handler, CA_ADAPTER_RFCOMM_BTEDR);
// Initialize Send/Receive data message queues
if (CA_STATUS_OK != CAEDRInitializeQueueHandlers())
return CAStartServer();
}
-int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+int32_t CASendEDRUnicastData(const CAEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength)
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
return -1;
}
- if (0 == strlen(remoteEndpoint->addressInfo.BT.btMacAddress))
+ if (0 == strlen(remoteEndpoint->addr))
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: EDR Address is empty!");
return -1;
uint32_t sentLength = 0;
const char *serviceUUID = OIC_EDR_SERVICE_ID;
- const char *address = remoteEndpoint->addressInfo.BT.btMacAddress;
+ const char *address = remoteEndpoint->addr;
CAResult_t err = CAAdapterSendData(address, serviceUUID, data, dataLength, &sentLength);
if (CA_STATUS_OK != err)
{
return sentLength;
}
-int32_t CASendEDRMulticastData(const void *data, uint32_t dataLength)
+int32_t CASendEDRMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN - CASendEDRMulticastData");
return sentLen;
}
-
-CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+CAResult_t CAGetEDRInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
CAEDRServerTerminate();
// Free LocalConnectivity information
- CAAdapterFreeLocalEndpoint(g_localConnectivity);
+ CAAdapterFreeEndpoint(g_localConnectivity);
g_localConnectivity = NULL;
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
const char *remoteAddress = NULL;
- const char *serviceUUID = NULL;
+ const char *serviceUUID = OIC_EDR_SERVICE_ID;
uint32_t sentLength = 0;
if (NULL == message->remoteEndpoint)
}
else
{
- remoteAddress = message->remoteEndpoint->addressInfo.BT.btMacAddress;
- serviceUUID = message->remoteEndpoint->resourceUri;
+ remoteAddress = message->remoteEndpoint->addr;
}
uint32_t dataSegmentLength = message->dataLen + CA_HEADER_LENGTH;
static uint32_t recvDataLen = 0;
static uint32_t totalDataLen = 0;
static char *defragData = NULL;
- static CARemoteEndpoint_t *remoteEndpoint = NULL;
+ static CAEndpoint_t *remoteEndpoint = NULL;
if (!g_isHeaderAvailable)
{
return;
}
- const char *remoteAddress = message->remoteEndpoint->addressInfo.BT.btMacAddress;
- const char *serviceUUID = message->remoteEndpoint->resourceUri;
+ const char *remoteAddress = message->remoteEndpoint->addr;
+ uint16_t port = message->remoteEndpoint->port;
- remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_EDR, remoteAddress, serviceUUID);
+ remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_RFCOMM_BTEDR, remoteAddress, port);
memcpy(defragData + recvDataLen, message->data + CA_HEADER_LENGTH,
message->dataLen - CA_HEADER_LENGTH);
VERIFY_NON_NULL_VOID(data, EDR_ADAPTER_TAG, "Data is null");
VERIFY_NON_NULL_VOID(sentLength, EDR_ADAPTER_TAG, "Sent data length holder is null");
- static const char serviceUUID[] = OIC_EDR_SERVICE_ID;
// Create remote endpoint
- CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_EDR, remoteAddress,
- serviceUUID);
+ CAEndpoint_t *remoteEndpoint = CAAdapterCreateEndpoint(0,
+ CA_ADAPTER_RFCOMM_BTEDR,
+ remoteAddress,
+ 0);
if (NULL == remoteEndpoint)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create remote endpoint !");
*sentLength = dataLength;
// Free remote endpoint
- CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+ CAAdapterFreeEndpoint(remoteEndpoint);
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
VERIFY_NON_NULL(sentLength, EDR_ADAPTER_TAG, "Sent data length holder is null");
// Create remote endpoint
- CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_EDR, remoteAddress,
- serviceUUID);
+ CAEndpoint_t *remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_RFCOMM_BTEDR, remoteAddress, 0);
if (NULL == remoteEndpoint)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create remote endpoint !");
// Add message to data queue
CAEDRData *edrData = CACreateEDRData(remoteEndpoint, data, dataLength);
- CAQueueingThreadAddData(g_sendQueueHandle, edrData, sizeof(CAEDRData));
+ CAQueueingThreadAddData(g_sendQueueHandle, edrData, sizeof (CAEDRData));
*sentLength = dataLength;
// Free remote endpoint
- CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+ CAAdapterFreeEndpoint(remoteEndpoint);
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT - CAAdapterSendData");
return CA_STATUS_OK;
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
-CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CALocalConnectivity_t *connectivity,
+CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CAEndpoint_t *connectivity,
CANetworkStatus_t status)
{
VERIFY_NON_NULL_RET(connectivity, EDR_ADAPTER_TAG, "connectivity is NULL", NULL);
}
// Create duplicate of Local connectivity
- event->info = CAAdapterCopyLocalEndpoint(connectivity);
+ event->info = CAAdapterCloneEndpoint(connectivity);
event->status = status;
return event;
}
{
if (event)
{
- CAAdapterFreeLocalEndpoint(event->info);
+ CAAdapterFreeEndpoint(event->info);
OICFree(event);
}
}
-CAEDRData *CACreateEDRData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
- uint32_t dataLength)
+CAEDRData *CACreateEDRData(const CAEndpoint_t *remoteEndpoint,
+ const void *data, uint32_t dataLength)
{
- CAEDRData *edrData = (CAEDRData *) OICMalloc(sizeof(CAEDRData));
+ CAEDRData *edrData = (CAEDRData *)OICMalloc(sizeof (CAEDRData));
if (!edrData)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
return NULL;
}
- edrData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint);
+ edrData->remoteEndpoint = CAAdapterCloneEndpoint(remoteEndpoint);
+
edrData->data = OICMalloc(dataLength);
if (NULL == edrData->data)
{
{
VERIFY_NON_NULL_VOID(edrData, EDR_ADAPTER_TAG, "edrData is NULL");
- CAAdapterFreeRemoteEndpoint(edrData->remoteEndpoint);
+ CAAdapterFreeEndpoint(edrData->remoteEndpoint);
OICFree(edrData->data);
OICFree(edrData);
}
handler.stopAdapter = CAStopEDR;
handler.terminate = CATerminateEDR;
- registerCallback(handler, CA_EDR);
+ registerCallback(handler, CA_ADAPTER_RFCOMM_BTEDR);
return CA_STATUS_OK;
}
return CA_STATUS_OK;
}
-int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+int32_t CASendEDRUnicastData(const CAEndpoint_t *endpoint, const void *data,
uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "CASendEDRUnicastData");
return -1;
}
-int32_t CASendEDRMulticastData(const void *data, uint32_t dataLen)
+int32_t CASendEDRMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "CASendEDRMulticastData");
return -1;
}
-CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+CAResult_t CAGetEDRInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
{
OIC_LOG(DEBUG, TAG, "CAGetEDRInterfaceInformation");
connHandler.GetnetInfo = CAGetLEInterfaceInformation;
connHandler.readData = CAReadLEData;
connHandler.terminate = CATerminateLE;
- registerCallback(connHandler, CA_LE);
+ registerCallback(connHandler, CA_ADAPTER_GATT_BTLE);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
-uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen)
+uint32_t CASendLENotification(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
return CA_STATUS_OK;
}
-int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen)
+int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
return dataLen;
}
-int32_t CASendLEMulticastData(const void *data, uint32_t dataLen)
+int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
return dataLen;
}
-CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
}
*size = 0;
- (*info) = (CALocalConnectivity_t *) OICCalloc(1, sizeof(CALocalConnectivity_t));
+ (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof (CAEndpoint_t));
if (NULL == (*info))
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
size_t local_address_len = strlen(local_address);
if(local_address_len >= sizeof(g_localBLEAddress) ||
- local_address_len >= sizeof((*info)->addressInfo.BT.btMacAddress))
+ local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
OICFree(*info);
return CA_STATUS_FAILED;
}
- OICStrcpy((*info)->addressInfo.BT.btMacAddress, sizeof ((*info)->addressInfo.BT.btMacAddress),
- local_address);
+ OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
ca_mutex_lock(g_bleLocalAddressMutex);
OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
ca_mutex_unlock(g_bleLocalAddressMutex);
- (*info)->type = CA_LE;
+ (*info)->adapter = CA_ADAPTER_GATT_BTLE;
*size = 1;
OICFree(local_address);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
VERIFY_NON_NULL_VOID(g_localBLEAddress, NULL, "g_localBLEAddress is null");
- CALocalConnectivity_t localEndpoint = {};
-
+ CAEndpoint_t localEndpoint = {};
+ localEndpoint.adapter = CA_ADAPTER_GATT_BTLE;
ca_mutex_lock(g_bleLocalAddressMutex);
- OICStrcpy(localEndpoint.addressInfo.BT.btMacAddress,
- sizeof(localEndpoint.addressInfo.BT.btMacAddress),
- g_localBLEAddress);
+ OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), g_localBLEAddress);
ca_mutex_unlock(g_bleLocalAddressMutex);
// Start a GattServer/Client if gLeServerStatus is SET
static uint32_t totalDataLen = 0;
static char *defragData = NULL;
static bool isHeaderAvailable = false;
- static CARemoteEndpoint_t *remoteEndpoint = NULL;
+ static CAEndpoint_t *remoteEndpoint = NULL;
ca_mutex_lock(g_bleServerReceiveDataMutex);
return;
}
- const char *remoteAddress = bleData->remoteEndpoint->addressInfo.LE.leMacAddress;
- const char *serviceUUID = bleData->remoteEndpoint->resourceUri;
+ const char *remoteAddress = bleData->remoteEndpoint->addr;
- remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
- serviceUUID);
+ remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
memcpy(defragData + recvDataLen, bleData->data + CA_HEADER_LENGTH,
bleData->dataLen - CA_HEADER_LENGTH);
totalDataLen = 0;
isHeaderAvailable = false;
OICFree(defragData);
- CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+ CAAdapterFreeEndpoint(remoteEndpoint);
ca_mutex_unlock(g_bleServerReceiveDataMutex);
return;
}
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
static const char *remoteAddress = NULL;
- static const char *serviceUUID = NULL;
static uint32_t recvDataLen = 0;
static uint32_t totalDataLen = 0;
static char *defragData = NULL;
static bool isHeaderAvailable = false;
- static CARemoteEndpoint_t *remoteEndpoint = NULL;
+ static CAEndpoint_t *remoteEndpoint = NULL;
ca_mutex_lock(g_bleClientReceiveDataMutex);
return;
}
- remoteAddress = bleData->remoteEndpoint->addressInfo.LE.leMacAddress;
- serviceUUID = bleData->remoteEndpoint->resourceUri;
+ remoteAddress = bleData->remoteEndpoint->addr;
- remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
- serviceUUID);
+ remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
memcpy(defragData, bleData->data + CA_HEADER_LENGTH,
bleData->dataLen - CA_HEADER_LENGTH);
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
OICFree(defragData);
- CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+ CAAdapterFreeEndpoint(remoteEndpoint);
ca_mutex_unlock(g_bleClientReceiveDataMutex);
return;
}
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
result = CAUpdateCharacteristicsToGattClient(
- bleData->remoteEndpoint->addressInfo.LE.leMacAddress, dataSegment, length);
+ bleData->remoteEndpoint->addr, dataSegment, length);
if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
// Send the remaining header.
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
result = CAUpdateCharacteristicsToGattClient(
- bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+ bleData->remoteEndpoint->addr,
bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
CA_SUPPORTED_BLE_MTU_SIZE);
if (CA_STATUS_OK != result)
// send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
result = CAUpdateCharacteristicsToGattClient(
- bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+ bleData->remoteEndpoint->addr,
bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
remainingLen);
if (CA_STATUS_OK != result)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
// Send the first segment with the header.
- result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+ result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addr,
dataSegment,
length,
LE_UNICAST, 0);
{
// Send the remaining header.
result = CAUpdateCharacteristicsToGattServer(
- bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+ bleData->remoteEndpoint->addr,
bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
CA_SUPPORTED_BLE_MTU_SIZE,
LE_UNICAST, 0);
// send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
result = CAUpdateCharacteristicsToGattServer(
- bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
+ bleData->remoteEndpoint->addr,
bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
remainingLen,
LE_UNICAST, 0);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
}
-CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+CALEData_t *CACreateBLEData(const CAEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength)
{
CALEData_t *bleData = (CALEData_t *) OICMalloc(sizeof(CALEData_t));
return NULL;
}
- bleData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint);
+ bleData->remoteEndpoint = CAAdapterCloneEndpoint(remoteEndpoint);
bleData->data = (void *)OICCalloc(dataLength + 1, 1);
if (NULL == bleData->data)
{
{
VERIFY_NON_NULL_VOID(bleData, NULL, "Param bleData is NULL");
- CAAdapterFreeRemoteEndpoint(bleData->remoteEndpoint);
+ CAAdapterFreeEndpoint(bleData->remoteEndpoint);
OICFree(bleData->data);
OICFree(bleData);
}
}
-CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
+CAResult_t CABLEClientSendData(const CAEndpoint_t *remoteEndpoint,
const void *data,
uint32_t dataLen)
{
}
-CAResult_t CABLEServerSendData(const CARemoteEndpoint_t *remoteEndpoint,
+CAResult_t CABLEServerSendData(const CAEndpoint_t *remoteEndpoint,
const void *data,
uint32_t dataLen)
{
CA_STATUS_FAILED);
//Add message to data queue
- CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
- serviceUUID);
+ CAEndpoint_t *remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
if (NULL == remoteEndpoint)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
if (!bleData)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
- CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+ CAAdapterFreeEndpoint(remoteEndpoint);
return CA_MEMORY_ALLOC_FAILED;
}
- CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+ CAAdapterFreeEndpoint(remoteEndpoint);
// Add message to send queue
CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
CA_STATUS_FAILED);
//Add message to data queue
- CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
- serviceUUID);
+ CAEndpoint_t *remoteEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
if (NULL == remoteEndpoint)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
if (!bleData)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
- CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+ CAAdapterFreeEndpoint(remoteEndpoint);
return CA_MEMORY_ALLOC_FAILED;
}
- CAAdapterFreeRemoteEndpoint(remoteEndpoint);
+ CAAdapterFreeEndpoint(remoteEndpoint);
// Add message to send queue
CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
handler.stopAdapter = CAStopLE;
handler.terminate = CATerminateLE;
- registerCallback(handler, CA_LE);
+ registerCallback(handler, CA_ADAPTER_GATT_BTLE);
return CA_STATUS_OK;
}
return CA_STATUS_OK;
}
-int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen)
+int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "CASendLEUnicastData");
return -1;
}
-int32_t CASendLEMulticastData(const void *data, uint32_t dataLen)
+int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "CASendLEMulticastData");
return -1;
}
-CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
{
OIC_LOG(DEBUG, TAG, "CAGetLEInterfaceInformation");
#include "caadapternetdtls.h"
#endif
+CAGlobals_t caglobals;
+
#define TAG PCF("CA")
static bool g_isInitialized = false;
}
#ifdef __WITH_DTLS__
-CAResult_t CARegisterDTLSCredentialsHandler(
- CAGetDTLSCredentialsHandler GetDTLSCredentialsHandler)
+CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSCredentialsHandler GetDTLSCredentialsHandler)
{
OIC_LOG(DEBUG, TAG, "CARegisterDTLSCredentialsHandler");
}
#endif //__WITH_DTLS__
-CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, const CATransportType_t transportType,
- CARemoteEndpoint_t **remoteEndpoint)
+void CADestroyEndpoint(CAEndpoint_t *rep)
{
- OIC_LOG(DEBUG, TAG, "CACreateRemoteEndpoint");
-
- if(!g_isInitialized)
- {
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- CARemoteEndpoint_t *remote = CACreateRemoteEndpointUriInternal(uri, transportType);
-
- if (remote == NULL)
- {
- OIC_LOG(DEBUG, TAG, "remote is NULL!");
- return CA_STATUS_FAILED;
- }
-
- *remoteEndpoint = remote;
-
- return CA_STATUS_OK;
-}
+ OIC_LOG(DEBUG, TAG, "CADestroyEndpoint");
-void CADestroyRemoteEndpoint(CARemoteEndpoint_t *rep)
-{
- OIC_LOG(DEBUG, TAG, "CADestroyRemoteEndpoint");
- CADestroyRemoteEndpointInternal(rep);
+ CADestroyEndpointInternal(rep);
}
CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength)
CADestroyTokenInternal(token);
}
-CAResult_t CAGetNetworkInformation(CALocalConnectivity_t **info, uint32_t *size)
+CAResult_t CAGetNetworkInformation(CAEndpoint_t **info, uint32_t *size)
{
OIC_LOG(DEBUG, TAG, "CAGetNetworkInformation");
return CAGetNetworkInformationInternal(info, size);
}
-CAResult_t CAFindResource(const CAURI_t resourceUri, const CAToken_t token, uint8_t tokenLength)
-{
- OIC_LOG(DEBUG, TAG, "CAFindResource");
-
- if(!g_isInitialized)
- {
- return CA_STATUS_NOT_INITIALIZED;
- }
- return CADetachMessageResourceUri(resourceUri, token, tokenLength, NULL, 0);
-
-}
-
-CAResult_t CASendRequest(const CARemoteEndpoint_t *object,const CARequestInfo_t *requestInfo)
+CAResult_t CASendRequest(const CAEndpoint_t *object,const CARequestInfo_t *requestInfo)
{
OIC_LOG(DEBUG, TAG, "CASendGetRequest");
return CADetachRequestMessage(object, requestInfo);
}
-CAResult_t CASendRequestToAll(const CAGroupEndpoint_t *object,
- const CARequestInfo_t *requestInfo)
-{
- OIC_LOG(DEBUG, TAG, "CASendRequestToAll");
-
- if(!g_isInitialized)
- {
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- return CADetachRequestToAllMessage(object, requestInfo);
-}
-
-CAResult_t CASendNotification(const CARemoteEndpoint_t *object,
- const CAResponseInfo_t *responseInfo)
+CAResult_t CASendNotification(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
{
OIC_LOG(DEBUG, TAG, "CASendNotification");
}
-CAResult_t CASendResponse(const CARemoteEndpoint_t *object,
- const CAResponseInfo_t *responseInfo)
+CAResult_t CASendResponse(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
{
OIC_LOG(DEBUG, TAG, "CASendResponse");
}
-CAResult_t CAAdvertiseResource(const CAURI_t resourceUri,const CAToken_t token,
- uint8_t tokenLength, const CAHeaderOption_t *options,
- const uint8_t numOptions)
-{
- OIC_LOG(DEBUG, TAG, "CAAdvertiseResource");
-
- if(!g_isInitialized)
- {
- return CA_STATUS_NOT_INITIALIZED;
- }
- return CADetachMessageResourceUri(resourceUri, token, tokenLength, options, numOptions);
-
-}
-
CAResult_t CASelectNetwork(const uint32_t interestedNetwork)
{
OIC_LOG_V(DEBUG, TAG, "Selected network : %d", interestedNetwork);
return CA_STATUS_NOT_INITIALIZED;
}
- if (!(interestedNetwork & 0xf))
- {
- return CA_NOT_SUPPORTED;
- }
-
CAResult_t res = CA_STATUS_OK;
- if (interestedNetwork & CA_IPV4)
+ if (interestedNetwork & CA_ADAPTER_IP)
{
- res = CAAddNetworkType(CA_IPV4);
- OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_IPV4) function returns error : %d", res);
+ res = CAAddNetworkType(CA_ADAPTER_IP);
+ OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_IP_ADAPTER) function returns error : %d", res);
}
-
- if (interestedNetwork & CA_EDR)
+ else if (interestedNetwork & CA_ADAPTER_RFCOMM_BTEDR)
{
- res = CAAddNetworkType(CA_EDR);
- OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_EDR) function returns error : %d", res);
+ res = CAAddNetworkType(CA_ADAPTER_RFCOMM_BTEDR);
+ OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_RFCOMM_ADAPTER) function returns error : %d", res);
}
-
- if (interestedNetwork & CA_LE)
+ else if (interestedNetwork & CA_ADAPTER_GATT_BTLE)
+ {
+ res = CAAddNetworkType(CA_ADAPTER_GATT_BTLE);
+ OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_GATT_ADAPTER) function returns error : %d", res);
+ }
+ else
{
- res = CAAddNetworkType(CA_LE);
- OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_LE) function returns error : %d", res);
+ res = CA_NOT_SUPPORTED;
}
return res;
return CA_STATUS_NOT_INITIALIZED;
}
- if (!(nonInterestedNetwork & 0xf))
- {
- return CA_NOT_SUPPORTED;
- }
-
CAResult_t res = CA_STATUS_OK;
- if (nonInterestedNetwork & CA_IPV4)
+ if (nonInterestedNetwork & CA_ADAPTER_IP)
{
- res = CARemoveNetworkType(CA_IPV4);
- OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_IPV4) function returns error : %d", res);
+ res = CARemoveNetworkType(CA_ADAPTER_IP);
+ OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_IP_ADAPTER) function returns error : %d", res);
}
-
- if (nonInterestedNetwork & CA_EDR)
+ else if (nonInterestedNetwork & CA_ADAPTER_RFCOMM_BTEDR)
{
- res = CARemoveNetworkType(CA_EDR);
- OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_EDR) function returns error : %d", res);
+ res = CARemoveNetworkType(CA_ADAPTER_RFCOMM_BTEDR);
+ OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_RFCOMM_ADAPTER) function returns error : %d", res);
}
-
- if (nonInterestedNetwork & CA_LE)
+ else if (nonInterestedNetwork & CA_ADAPTER_GATT_BTLE)
+ {
+ res = CARemoveNetworkType(CA_ADAPTER_GATT_BTLE);
+ OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_GATT_ADAPTER) function returns error : %d", res);
+ }
+ else
{
- res = CARemoveNetworkType(CA_LE);
- OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_LE) function returns error : %d", res);
+ res = CA_STATUS_FAILED;
}
return res;
return CADtlsEnableAnonECDHCipherSuite(enable);
}
-CAResult_t CAGenerateOwnerPSK(const CAAddress_t* addrInfo,
- const CATransportType_t transportType,
+CAResult_t CAGenerateOwnerPSK(const CAEndpoint_t* endpoint,
const uint8_t* label, const size_t labelLen,
const uint8_t* rsrcServerDeviceID, const size_t rsrcServerDeviceIDLen,
const uint8_t* provServerDeviceID, const size_t provServerDeviceIDLen,
CAResult_t res = CA_STATUS_OK;
//newOwnerLabel and prevOwnerLabe can be NULL
- if(!addrInfo || !label || 0 == labelLen || !ownerPSK || 0 == ownerPSKSize)
+ if (!endpoint || !label || 0 == labelLen || !ownerPSK || 0 == ownerPSKSize)
{
return CA_STATUS_INVALID_PARAM;
}
- res = CADtlsGenerateOwnerPSK(addrInfo, transportType, label, labelLen,
+ res = CADtlsGenerateOwnerPSK(endpoint, label, labelLen,
rsrcServerDeviceID, rsrcServerDeviceIDLen,
provServerDeviceID, provServerDeviceIDLen,
ownerPSK, ownerPSKSize);
- if(CA_STATUS_OK != res)
+ if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "Failed to CAGenerateOwnerPSK : %d", res);
}
return res;
}
-CAResult_t CAInitiateHandshake(const CAAddress_t* addrInfo,
- const CATransportType_t transportType)
+CAResult_t CAInitiateHandshake(const CAEndpoint_t *endpoint)
{
OIC_LOG_V(DEBUG, TAG, "IN : CAInitiateHandshake");
CAResult_t res = CA_STATUS_OK;
- if(!addrInfo)
+ if (!endpoint)
{
return CA_STATUS_INVALID_PARAM;
}
- res = CADtlsInitiateHandshake(addrInfo, transportType);
- if(CA_STATUS_OK != res)
+ res = CADtlsInitiateHandshake(endpoint);
+ if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "Failed to CADtlsInitiateHandshake : %d", res);
}
return res;
}
-CAResult_t CACloseDtlsSession(const CAAddress_t* addrInfo,
- const CATransportType_t transportType)
+CAResult_t CACloseDtlsSession(const CAEndpoint_t *endpoint)
{
OIC_LOG_V(DEBUG, TAG, "IN : CACloseDtlsSession");
CAResult_t res = CA_STATUS_OK;
- if(!addrInfo)
+ if (!endpoint)
{
return CA_STATUS_INVALID_PARAM;
}
- res = CADtlsClose(addrInfo, transportType);
- if(CA_STATUS_OK != res)
+ res = CADtlsClose(endpoint);
+ if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "Failed to CADtlsClose : %d", res);
}
#define TAG "CM_ST"
+CAGlobals_t caglobals;
+
static bool g_isInitialized = false;
CAResult_t CAInitialize()
OIC_LOG(DEBUG, TAG, "OUT");
}
-CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, const CATransportType_t transportType,
- CARemoteEndpoint_t **remoteEndpoint)
-{
- OIC_LOG(DEBUG, TAG, "IN");
-
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- CARemoteEndpoint_t *remote = CACreateRemoteEndpointUriInternal(uri, transportType);
-
- if (remote == NULL)
- {
- OIC_LOG(ERROR, TAG, "remote endpoint is NULL");
- return CA_STATUS_FAILED;
- }
-
- *remoteEndpoint = remote;
-
- OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
-}
-
-void CADestroyRemoteEndpoint(CARemoteEndpoint_t *rep)
+void CADestroyEndpoint(CAEndpoint_t *rep)
{
- CADestroyRemoteEndpointInternal(rep);
+ CADestroyEndpointInternal(rep);
}
CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength)
OIC_LOG(DEBUG, TAG, "OUT");
}
-CAResult_t CAGetNetworkInformation(CALocalConnectivity_t **info, uint32_t *size)
+CAResult_t CAGetNetworkInformation(CAEndpoint_t **info, uint32_t *size)
{
if (!g_isInitialized)
{
return CAGetNetworkInformationInternal(info, size);
}
-CAResult_t CAFindResource(const CAURI_t resourceUri, const CAToken_t token, uint8_t tokenLength)
+CAResult_t CASendRequest(const CAEndpoint_t *object,const CARequestInfo_t *requestInfo)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- return CADetachMessageResourceUri(resourceUri, token, tokenLength, NULL, 0);
-}
-
-CAResult_t CASendRequest(const CARemoteEndpoint_t *object,const CARequestInfo_t *requestInfo)
-{
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
+ OIC_LOG(DEBUG, TAG, "CASendGetRequest");
return CADetachRequestMessage(object, requestInfo);
}
-CAResult_t CASendRequestToAll(const CAGroupEndpoint_t *object,
- const CARequestInfo_t *requestInfo)
-{
- OIC_LOG(DEBUG, TAG, "CASendRequestToAll");
-
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- return CADetachRequestToAllMessage(object, requestInfo);
-}
-
-CAResult_t CASendNotification(const CARemoteEndpoint_t *object,
+CAResult_t CASendNotification(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo)
{
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
+ OIC_LOG(DEBUG, TAG, "CASendNotification");
return CADetachResponseMessage(object, responseInfo);
}
-CAResult_t CASendResponse(const CARemoteEndpoint_t *object,
+CAResult_t CASendResponse(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo)
{
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
+ OIC_LOG(DEBUG, TAG, "CASendResponse");
return CADetachResponseMessage(object, responseInfo);
}
-CAResult_t CAAdvertiseResource(const CAURI_t resourceUri,const CAToken_t token,
- uint8_t tokenLength, const CAHeaderOption_t *options,
- const uint8_t numOptions)
-{
- if (!g_isInitialized)
- {
- OIC_LOG(ERROR, TAG, "not initialized");
- return CA_STATUS_NOT_INITIALIZED;
- }
- return CADetachMessageResourceUri(resourceUri, token, tokenLength, options, numOptions);
-}
-
CAResult_t CASelectNetwork(const uint32_t interestedNetwork)
{
OIC_LOG_V(DEBUG, TAG, "Selected n/W=%d", interestedNetwork);
}
CAResult_t res = CA_STATUS_OK;
- if (interestedNetwork & CA_IPV4)
+ if (interestedNetwork & CA_ADAPTER_IP)
{
- res = CAAddNetworkType(CA_IPV4);
+ res = CAAddNetworkType(CA_ADAPTER_IP);
if (res != CA_STATUS_OK)
{
OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
}
}
- if (interestedNetwork & CA_EDR)
+ if (interestedNetwork & CA_ADAPTER_RFCOMM_BTEDR)
{
- res = CAAddNetworkType(CA_EDR);
+ res = CAAddNetworkType(CA_ADAPTER_RFCOMM_BTEDR);
if (res != CA_STATUS_OK)
{
OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
}
}
- if (interestedNetwork & CA_LE)
+ if (interestedNetwork & CA_ADAPTER_GATT_BTLE)
{
- res = CAAddNetworkType(CA_LE);
+ res = CAAddNetworkType(CA_ADAPTER_GATT_BTLE);
if (res != CA_STATUS_OK)
{
OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
CAResult_t res = CA_STATUS_OK;
- if (nonInterestedNetwork & CA_IPV4)
+ if (nonInterestedNetwork & CA_ADAPTER_IP)
{
- res = CARemoveNetworkType(CA_IPV4);
+ res = CARemoveNetworkType(CA_ADAPTER_IP);
if (res != CA_STATUS_OK)
{
OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
}
}
- if (nonInterestedNetwork & CA_EDR)
+ if (nonInterestedNetwork & CA_ADAPTER_RFCOMM_BTEDR)
{
- res = CARemoveNetworkType(CA_EDR);
+ res = CARemoveNetworkType(CA_ADAPTER_RFCOMM_BTEDR);
if (res != CA_STATUS_OK)
{
OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
}
}
- if (nonInterestedNetwork & CA_LE)
+ if (nonInterestedNetwork & CA_ADAPTER_GATT_BTLE)
{
- res = CARemoveNetworkType(CA_LE);
+ res = CARemoveNetworkType(CA_ADAPTER_GATT_BTLE);
if (res != CA_STATUS_OK)
{
OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
#define CA_MEMORY_ALLOC_CHECK(arg) {if (arg == NULL) \
{OIC_LOG(ERROR, TAG, "memory error");goto memory_error_exit;} }
-#define CA_TRANSPORT_TYPE_NUM 4
+#define CA_TRANSPORT_TYPE_NUM 3
static CAConnectivityHandler_t g_adapterHandler[CA_TRANSPORT_TYPE_NUM] = {};
static CAErrorHandleCallback g_errorHandleCallback = NULL;
-static int CAGetAdapterIndex(CATransportType_t cType)
+static int CAGetAdapterIndex(CATransportAdapter_t cType)
{
switch (cType)
{
- case CA_IPV4:
+ case CA_ADAPTER_IP:
return 0;
- case CA_IPV6:
+ case CA_ADAPTER_RFCOMM_BTEDR:
return 1;
- case CA_EDR:
+ case CA_ADAPTER_GATT_BTLE:
return 2;
- case CA_LE:
- return 3;
+ default:
+ break;
}
- OIC_LOG(DEBUG, TAG, "CA_TRANSPORT_TYPE_NUM is not 4");
+ OIC_LOG(DEBUG, TAG, "CA_TRANSPORT_TYPE_NUM is not 3");
return -1;
}
-static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportType_t cType)
+static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportAdapter_t cType)
{
OIC_LOG(DEBUG, TAG, "CARegisterCallback - Entry");
OIC_LOG_V(DEBUG, TAG, "%d type adapter, register complete!", cType);
}
-static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
- uint32_t dataLen)
+static void CAReceivedPacketCallback(const CAEndpoint_t *endpoint, void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "receivedPacketCallback in interface controller");
}
else
{
- OICFree(endpoint);
- endpoint = NULL;
OICFree(data);
- data = NULL;
OIC_LOG(ERROR, TAG, "network packet received callback is NULL!");
}
}
-static void CANetworkChangedCallback(CALocalConnectivity_t *info,
- CANetworkStatus_t status)
+static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
{
OIC_LOG(DEBUG, TAG, "Network Changed callback");
}
}
-static void CAAdapterErrorHandleCallback(const CARemoteEndpoint_t *endpoint, const void *data,
- uint32_t dataLen, CAResult_t result)
+static void CAAdapterErrorHandleCallback(const CAEndpoint_t *endpoint,
+ const void *data, uint32_t dataLen,
+ CAResult_t result)
{
OIC_LOG(DEBUG, TAG, "received error from adapter in interfacecontroller");
// Initialize adapters and register callback.
#ifdef IP_ADAPTER
- CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
- handle);
+ CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, handle);
#endif /* IP_ADAPTER */
#ifdef EDR_ADAPTER
- CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
- handle);
+ CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, handle);
#endif /* EDR_ADAPTER */
#ifdef LE_ADAPTER
- CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
- handle);
+ CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, handle);
#endif /* LE_ADAPTER */
}
g_errorHandleCallback = errorCallback;
}
-CAResult_t CAStartAdapter(CATransportType_t transportType)
+CAResult_t CAStartAdapter(CATransportAdapter_t transportType)
{
OIC_LOG_V(DEBUG, TAG, "Start the adapter of CAConnectivityType[%d]", transportType);
return CA_STATUS_OK;
}
-void CAStopAdapter(CATransportType_t transportType)
+void CAStopAdapter(CATransportAdapter_t transportType)
{
OIC_LOG_V(DEBUG, TAG, "Stop the adapter of CATransportType[%d]", transportType);
}
}
-CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size)
+CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, uint32_t *size)
{
if (info == NULL || size == NULL)
{
return CA_STATUS_INVALID_PARAM;
}
- CALocalConnectivity_t *tempInfo[CA_TRANSPORT_TYPE_NUM] = { 0 };
+ CAEndpoint_t *tempInfo[CA_TRANSPORT_TYPE_NUM] = { 0 };
uint32_t tempSize[CA_TRANSPORT_TYPE_NUM] = { 0 };
CAResult_t res = CA_STATUS_FAILED;
// #3. add data into result
// memory allocation
-
- CALocalConnectivity_t *resInfo = (CALocalConnectivity_t *)
- OICCalloc(resSize, sizeof(CALocalConnectivity_t));
+ CAEndpoint_t *resInfo = (CAEndpoint_t *) OICCalloc(resSize, sizeof (*resInfo));
CA_MEMORY_ALLOC_CHECK(resInfo);
// #4. save data
return CA_MEMORY_ALLOC_FAILED;
}
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length)
+CAResult_t CASendUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
{
OIC_LOG(DEBUG, TAG, "Send unicast data to enabled interface..");
return CA_STATUS_INVALID_PARAM;
}
- CATransportType_t type = endpoint->transportType;
+ CATransportAdapter_t type = endpoint->adapter;
int index = CAGetAdapterIndex(type);
return res;
}
-CAResult_t CASendMulticastData(const void *data, uint32_t length)
+CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
{
OIC_LOG(DEBUG, TAG, "Send multicast data to enabled interface..");
continue;
}
- CATransportType_t connType = *(CATransportType_t *) ptrType;
+ CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
int index = CAGetAdapterIndex(connType);
return CA_MEMORY_ALLOC_FAILED;
}
memcpy(payload, data, length);
- sentDataLen = g_adapterHandler[index].sendDataToAll(payload, length);
+ sentDataLen = g_adapterHandler[index].sendDataToAll(endpoint, payload, length);
OICFree(payload);
}
continue;
}
- CATransportType_t connType = *(CATransportType_t *) ptrType;
+ CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
int index = CAGetAdapterIndex(connType);
if (index == -1)
continue;
}
- CATransportType_t connType = *(CATransportType_t *) ptrType;
+ CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
int index = CAGetAdapterIndex(connType);
static CAErrorHandleCallback g_errorHandleCallback = NULL;
-static int CAGetAdapterIndex(CATransportType_t cType)
+static int CAGetAdapterIndex(CATransportAdapter_t cType)
{
switch (cType)
{
- case CA_IPV4:
+ case CA_ADAPTER_IP:
return 0;
- case CA_IPV6:
+ case CA_ADAPTER_RFCOMM_BTEDR:
return 1;
- case CA_EDR:
+ case CA_ADAPTER_GATT_BTLE:
return 2;
- case CA_LE:
- return 3;
}
OIC_LOG(DEBUG, TAG, "CA_CONNECTIVITY_TYPE_NUM is not 4");
return -1;
}
-static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportType_t cType)
+static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportAdapter_t cType)
{
OIC_LOG(DEBUG, TAG, "IN");
OIC_LOG(DEBUG, TAG, "OUT");
}
-static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
+static void CAReceivedPacketCallback(CAEndpoint_t *endpoint, void *data,
uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "IN");
g_errorHandleCallback = errorCallback;
}
-static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
+static void CANetworkChangedCallback(CAEndpoint_t *info, CANetworkStatus_t status)
{
OIC_LOG(DEBUG, TAG, "IN");
OIC_LOG(DEBUG, TAG, "OUT");
}
-CAResult_t CAStartAdapter(CATransportType_t transportType)
+CAResult_t CAStartAdapter(CATransportAdapter_t transportType)
{
OIC_LOG_V(DEBUG, TAG, "transportType[%d]", transportType);
return CA_STATUS_OK;
}
-void CAStopAdapter(CATransportType_t transportType)
+void CAStopAdapter(CATransportAdapter_t transportType)
{
OIC_LOG_V(DEBUG, TAG, "transportType[%d]", transportType);
OIC_LOG(DEBUG, TAG, "OUT");
}
-CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size)
+CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, uint32_t *size)
{
OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL(info, TAG, "info");
VERIFY_NON_NULL(size, TAG, "size");
- CALocalConnectivity_t *tempInfo[CA_CONNECTIVITY_TYPE_NUM] = { 0 };
+ CAEndpoint_t *tempInfo[CA_CONNECTIVITY_TYPE_NUM] = { 0 };
uint32_t tempSize[CA_CONNECTIVITY_TYPE_NUM] = { 0 };
CAResult_t res = CA_STATUS_FAILED;
// #3. add data into result
// memory allocation
- CALocalConnectivity_t *resInfo =
- (CALocalConnectivity_t *) OICCalloc(resSize, sizeof(CALocalConnectivity_t));
+ CAEndpoint_t *resInfo = (CAEndpoint_t *)OICCalloc(resSize, sizeof(CAEndpoint_t));
CA_MEMORY_ALLOC_CHECK(resInfo);
uint8_t i = 0;
continue;
}
- memcpy(resInfo + i, tempInfo[index], sizeof(CALocalConnectivity_t) * tempSize[index]);
+ memcpy(resInfo + i, tempInfo[index], sizeof(CAEndpoint_t) * tempSize[index]);
i += tempSize[index];
return CA_MEMORY_ALLOC_FAILED;
}
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length)
+CAResult_t CASendUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
{
OIC_LOG(DEBUG, TAG, "IN");
if (endpoint == NULL)
{
- OIC_LOG(DEBUG, TAG, "RemoteEndpoint is NULL");
+ OIC_LOG(DEBUG, TAG, "Endpoint is NULL");
return CA_STATUS_INVALID_PARAM;
}
- CATransportType_t type = endpoint->transportType;
+ CATransportAdapter_t type = endpoint->adapter;
int index = CAGetAdapterIndex(type);
return res;
}
-CAResult_t CASendMulticastData(const void *data, uint32_t length)
+CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length)
{
OIC_LOG(DEBUG, TAG, "IN");
continue;
}
- CATransportType_t connType = *(CATransportType_t *) ptrType;
+ CATransportAdapter_t connType = *(CATransportAdapter_t *) ptrType;
int index = CAGetAdapterIndex(connType);
uint32_t sentDataLen = 0;
if (g_adapterHandler[index].sendDataToAll != NULL)
{
- sentDataLen = g_adapterHandler[index].sendDataToAll(data, length);
+ sentDataLen = g_adapterHandler[index].sendDataToAll(endpoint, data, length);
}
if (sentDataLen == length)
continue;
}
- CATransportType_t connType = *(CATransportType_t *) ptrType;
+ CATransportAdapter_t connType = *(CATransportAdapter_t *) ptrType;
int index = CAGetAdapterIndex(connType);
continue;
}
- CATransportType_t connType = *(CATransportType_t *) ptrType;
+ CATransportAdapter_t connType = *(CATransportAdapter_t *) ptrType;
int index = CAGetAdapterIndex(connType);
return CA_STATUS_FAILED;
}
- CATransportType_t connType = *(CATransportType_t *) ptrType;
+ CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
int index = CAGetAdapterIndex(connType);
typedef struct
{
CASendDataType_t type;
- CARemoteEndpoint_t *remoteEndpoint;
+ CAEndpoint_t *remoteEndpoint;
CARequestInfo_t *requestInfo;
CAResponseInfo_t *responseInfo;
CAErrorInfo_t *errorInfo;
static CAResponseCallback g_responseHandler = NULL;
static CAErrorCallback g_errorHandler = NULL;
-static void CAErrorHandler(const CARemoteEndpoint_t *remoteEndpoint,
- const void *data, uint32_t dataLen, CAResult_t result);
+static void CAErrorHandler(const CAEndpoint_t *endpoint,
+ const void *data, uint32_t dataLen,
+ CAResult_t result);
static bool CAIsSelectedNetworkAvailable()
{
return true;
}
-static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size)
+static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
{
OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
- CARemoteEndpoint_t* ep = CACloneRemoteEndpoint(endpoint);
+ CAEndpoint_t* ep = CACloneEndpoint(endpoint);
if (NULL == ep)
{
OIC_LOG(ERROR, TAG, "clone failed");
return;
}
- CAResponseInfo_t* resInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
+ CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
if (NULL == resInfo)
{
OIC_LOG(ERROR, TAG, "calloc failed");
- CADestroyRemoteEndpointInternal(ep);
+ CAAdapterFreeEndpoint(ep);
return;
}
OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
OICFree(resInfo->info.token);
OICFree(resInfo);
- CADestroyRemoteEndpointInternal(ep);
+ CAAdapterFreeEndpoint(ep);
return;
}
if (NULL == cadata)
{
OIC_LOG(ERROR, TAG, "memory allocation failed !");
- CADestroyRemoteEndpointInternal(ep);
+ CAAdapterFreeEndpoint(ep);
OICFree(resInfo);
return;
}
if (NULL != cadata->remoteEndpoint)
{
- CADestroyRemoteEndpointInternal((CARemoteEndpoint_t *) cadata->remoteEndpoint);
+ CADestroyEndpointInternal(cadata->remoteEndpoint);
}
if (NULL != cadata->requestInfo)
// parse the data and call the callbacks.
// #1 parse the data
// #2 get endpoint
- CARemoteEndpoint_t *rep = (CARemoteEndpoint_t *)(data->remoteEndpoint);
+ CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
if (NULL == rep)
{
CASendDataType_t type = data->type;
+ coap_pdu_t *pdu = NULL;
+
if (SEND_TYPE_UNICAST == type)
{
- coap_pdu_t *pdu = NULL;
if (NULL != data->requestInfo)
{
OIC_LOG(DEBUG, TAG, "requestInfo is available..");
- pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
- data->requestInfo->method,
- data->requestInfo->info);
+ pdu = CAGeneratePDU(data->requestInfo->method, &data->requestInfo->info);
}
else if (NULL != data->responseInfo)
{
OIC_LOG(DEBUG, TAG, "responseInfo is available..");
- pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
- data->responseInfo->result,
- data->responseInfo->info);
+ pdu = CAGeneratePDU(data->responseInfo->result, &data->responseInfo->info);
}
else
{
{
OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
- CAInfo_t info = data->requestInfo->info;
-
- info.options = data->options;
- info.numOptions = data->numOptions;
+ CAInfo_t *info = &data->requestInfo->info;
- coap_pdu_t *pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri, CA_GET,
- info);
+ info->options = data->options;
+ info->numOptions = data->numOptions;
+ pdu = CAGeneratePDU(CA_GET, info);
if (NULL != pdu)
{
CALogPDUInfo(pdu);
- res = CASendMulticastData(pdu->hdr, pdu->length);
- if(CA_STATUS_OK != res)
+ res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
+ if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
OIC_LOG(DEBUG, TAG, "OUT");
}
-static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+static void CAReceivedPacketCallback(const CAEndpoint_t *endpoint, void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
if (NULL == pdu)
{
OIC_LOG(ERROR, TAG, "Parse PDU failed");
- CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
- char uri[CA_MAX_URI_LENGTH] = { };
-
if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
{
CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
{
OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
coap_delete_pdu(pdu);
- CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
- CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo, uri, sizeof(uri));
+ CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo);
if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
OICFree(ReqInfo);
coap_delete_pdu(pdu);
- CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
OIC_LOG(DEBUG, TAG, "Request- token");
OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token, CA_MAX_TOKEN_LEN);
OIC_LOG_V(DEBUG, TAG, "Request- msgID : %d", ReqInfo->info.messageId);
- if (NULL != endpoint)
- {
- endpoint->resourceUri = (char *) OICMalloc(sizeof(uri) + 1);
- if (NULL == endpoint->resourceUri)
- {
- OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
- OICFree(ReqInfo);
- coap_delete_pdu(pdu);
- CAAdapterFreeRemoteEndpoint(endpoint);
- return;
- }
- memcpy(endpoint->resourceUri, uri, sizeof(uri));
- endpoint->resourceUri[sizeof(uri)] = '\0';
- OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
- }
// store the data at queue.
CAData_t *cadata = NULL;
cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
if (NULL == cadata)
{
OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
- OICFree(ReqInfo);
+ CADestroyRequestInfoInternal(ReqInfo);
coap_delete_pdu(pdu);
- CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
cadata->type = SEND_TYPE_UNICAST;
- cadata->remoteEndpoint = endpoint;
+ cadata->remoteEndpoint = CAAdapterCloneEndpoint(endpoint);
cadata->requestInfo = ReqInfo;
cadata->responseInfo = NULL;
CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
{
OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
coap_delete_pdu(pdu);
- CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
- CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo, uri, sizeof(uri));
+ CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo);
if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
OICFree(ResInfo);
coap_delete_pdu(pdu);
- CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
OIC_LOG_V(DEBUG, TAG, "Response- token : %s", ResInfo->info.token);
OIC_LOG_V(DEBUG, TAG, "Response- msgID: %d", ResInfo->info.messageId);
- if (NULL != endpoint)
- {
- endpoint->resourceUri = (char *) OICMalloc(sizeof(uri) + 1);
- if (NULL == endpoint->resourceUri)
- {
- OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
- OICFree(ResInfo);
- coap_delete_pdu(pdu);
- CAAdapterFreeRemoteEndpoint(endpoint);
- return;
- }
- memcpy(endpoint->resourceUri, uri, sizeof(uri));
- endpoint->resourceUri[sizeof(uri)] = '\0';
- OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
- }
-
// store the data at queue.
CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
if (NULL == cadata)
{
OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
- OICFree(ResInfo);
+ CADestroyResponseInfoInternal(ResInfo);
coap_delete_pdu(pdu);
- CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
cadata->type = SEND_TYPE_UNICAST;
- cadata->remoteEndpoint = endpoint;
+ cadata->remoteEndpoint = CAAdapterCloneEndpoint(endpoint);
cadata->requestInfo = NULL;
// for retransmission
OIC_LOG(DEBUG, TAG, "OUT");
}
-static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
+static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
{
OIC_LOG(DEBUG, TAG, "IN");
// get endpoint
CAData_t *td = (CAData_t *) msg;
- CARemoteEndpoint_t *rep = td->remoteEndpoint;
-
- if (NULL == rep)
- {
- return;
- }
if (td->requestInfo && g_requestHandler)
{
OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
- g_requestHandler(rep, td->requestInfo);
+ g_requestHandler(td->remoteEndpoint, td->requestInfo);
}
else if (td->responseInfo && g_responseHandler)
{
OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
- g_responseHandler(rep, td->responseInfo);
+ g_responseHandler(td->remoteEndpoint, td->responseInfo);
}
else if (td->errorInfo && g_errorHandler)
{
OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
- g_errorHandler(rep, td->errorInfo);
+ g_errorHandler(td->remoteEndpoint, td->errorInfo);
}
CADataDestroyer(msg, sizeof(CAData_t));
OIC_LOG(DEBUG, TAG, "CAHandleRequestResponseCallbacks OUT");
}
-CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object, const CARequestInfo_t *request)
+CAResult_t CADetachRequestMessage(const CAEndpoint_t *object, const CARequestInfo_t *request)
{
OIC_LOG(DEBUG, TAG, "IN");
return CA_STATUS_FAILED;
}
- CARemoteEndpoint_t *remoteEndpoint = NULL;
+ CAEndpoint_t *remoteEndpoint = NULL;
CARequestInfo_t *requestInfo = NULL;
CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
CA_MEMORY_ALLOC_CHECK(data);
// clone remote endpoint
- remoteEndpoint = CACloneRemoteEndpoint(object);
+ remoteEndpoint = CACloneEndpoint(object);
CA_MEMORY_ALLOC_CHECK(remoteEndpoint);
// clone request info
CA_MEMORY_ALLOC_CHECK(requestInfo);
// save data
- data->type = SEND_TYPE_UNICAST;
+ data->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
data->remoteEndpoint = remoteEndpoint;
data->requestInfo = requestInfo;
data->responseInfo = NULL;
// memory error label.
memory_error_exit:
- CADestroyRemoteEndpointInternal(remoteEndpoint);
+ CAAdapterFreeEndpoint(remoteEndpoint);
CADestroyRequestInfoInternal(requestInfo);
OICFree(data);
return CA_MEMORY_ALLOC_FAILED;
}
-CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
- const CARequestInfo_t *request)
-{
- OIC_LOG(DEBUG, TAG, "IN");
-
- if (NULL == object || NULL == request || NULL == object->resourceUri)
- {
- return CA_STATUS_INVALID_PARAM;
- }
-
- if ((request->method < CA_GET) || (request->method > CA_DELETE))
- {
- OIC_LOG(ERROR, TAG, "Invalid method type!");
-
- return CA_STATUS_INVALID_PARAM;
- }
-
- if (false == CAIsSelectedNetworkAvailable())
- {
- return CA_STATUS_FAILED;
- }
-
- CARemoteEndpoint_t *remoteEndpoint = NULL;
- CARequestInfo_t *requestInfo = NULL;
-
- // allocate & initialize
- CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
- CA_MEMORY_ALLOC_CHECK(data);
-
- CAAddress_t addr = {};
- remoteEndpoint = CACreateRemoteEndpointInternal(object->resourceUri, addr,
- object->transportType);
-
- // clone request info
- requestInfo = CACloneRequestInfo(request);
- CA_MEMORY_ALLOC_CHECK(requestInfo);
-
- // save data
- data->type = SEND_TYPE_MULTICAST;
- data->remoteEndpoint = remoteEndpoint;
- data->requestInfo = requestInfo;
- data->responseInfo = NULL;
-
- // add thread
- CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
-
- OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
-
-// memory error label.
-memory_error_exit:
-
- CADestroyRequestInfoInternal(requestInfo);
- CADestroyRemoteEndpointInternal(remoteEndpoint);
- OICFree(data);
- OIC_LOG(DEBUG, TAG, "OUT");
- return CA_MEMORY_ALLOC_FAILED;
-}
-
-CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
+CAResult_t CADetachResponseMessage(const CAEndpoint_t *object,
const CAResponseInfo_t *response)
{
OIC_LOG(DEBUG, TAG, "IN");
return CA_STATUS_FAILED;
}
- CARemoteEndpoint_t *remoteEndpoint = NULL;
+ CAEndpoint_t *remoteEndpoint = NULL;
CAResponseInfo_t *responseInfo = NULL;
// allocate & initialize
CA_MEMORY_ALLOC_CHECK(data);
// clone remote endpoint
- remoteEndpoint = CACloneRemoteEndpoint(object);
+ remoteEndpoint = CACloneEndpoint(object);
CA_MEMORY_ALLOC_CHECK(remoteEndpoint);
// clone response info
// memory error label.
memory_error_exit:
- CADestroyRemoteEndpointInternal(remoteEndpoint);
+ CAAdapterFreeEndpoint(remoteEndpoint);
CADestroyResponseInfoInternal(responseInfo);
OICFree(data);
OIC_LOG(DEBUG, TAG, "OUT");
uint8_t tokenLength, const CAHeaderOption_t *options,
uint8_t numOptions)
{
- OIC_LOG(DEBUG, TAG, "IN");
- VERIFY_NON_NULL(resourceUri, TAG, "resourceUri is NULL");
- VERIFY_NON_NULL(token, TAG, "Token is NULL");
-
- if (false == CAIsSelectedNetworkAvailable())
- {
- return CA_STATUS_FAILED;
- }
-
- CARemoteEndpoint_t *remoteEndpoint = NULL;
- CARequestInfo_t *reqInfo = NULL;
- char *tempToken = NULL;
-
- // allocate & initialize
- CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
- CA_MEMORY_ALLOC_CHECK(data);
-
- CAAddress_t addr = {};
- remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, addr,
- CA_IPV4 | CA_EDR | CA_LE);
-
- // create request info
- reqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
- CA_MEMORY_ALLOC_CHECK(reqInfo);
-
- if (tokenLength)
- {
- // copy token value
- tempToken = (char *) OICMalloc(tokenLength);
- CA_MEMORY_ALLOC_CHECK(tempToken);
- memcpy(tempToken, token, tokenLength);
- }
-
- // save request info data
- reqInfo->method = CA_GET;
- reqInfo->info.type = CA_MSG_NONCONFIRM;
-
- reqInfo->info.token = tempToken;
- reqInfo->info.tokenLength = tokenLength;
-
- // save data
- data->type = SEND_TYPE_MULTICAST;
- data->remoteEndpoint = remoteEndpoint;
- data->requestInfo = reqInfo;
-
- data->responseInfo = NULL;
- data->options = NULL;
- data->numOptions = 0;
- if (NULL != options && 0 < numOptions)
- {
- // copy data
- CAHeaderOption_t *headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t)
- * numOptions);
- CA_MEMORY_ALLOC_CHECK(headerOption);
-
- memcpy(headerOption, options, sizeof(CAHeaderOption_t) * numOptions);
-
- data->options = headerOption;
- data->numOptions = numOptions;
- }
-
- // add thread
- CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
-
- OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
-
-// memory error label.
-memory_error_exit:
-
- CADestroyRemoteEndpointInternal(remoteEndpoint);
-
- OICFree(tempToken);
- OICFree(reqInfo);
- OICFree(data);
- OIC_LOG(DEBUG, TAG, "OUT");
- return CA_MEMORY_ALLOC_FAILED;
+ return CA_NOT_SUPPORTED;
}
void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
void CATerminateMessageHandler()
{
OIC_LOG(DEBUG, TAG, "IN");
- CATransportType_t connType;
+ CATransportAdapter_t connType;
u_arraylist_t *list = CAGetSelectedNetworkList();
uint32_t length = u_arraylist_length(list);
continue;
}
- connType = *(CATransportType_t *) ptrType;
+ connType = *(CATransportAdapter_t *)ptrType;
CAStopAdapter(connType);
}
OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->token, pdu->hdr->token_length);
}
-void CAErrorHandler(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
- uint32_t dataLen, CAResult_t result)
+void CAErrorHandler(const CAEndpoint_t *endpoint,
+ const void *data, uint32_t dataLen,
+ CAResult_t result)
{
OIC_LOG(DEBUG, TAG, "IN");
- VERIFY_NON_NULL_VOID(remoteEndpoint, TAG, "remoteEndpoint");
+ VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
VERIFY_NON_NULL_VOID(data, TAG, "data");
uint32_t code = CA_NOT_FOUND;
//Do not free remoteEndpoint and data. Currently they will be freed in data thread
//Get PDU data
- coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
+ coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code);
if (NULL == pdu)
{
OIC_LOG(ERROR, TAG, "Parse PDU failed");
return;
}
- char uri[CA_MAX_URI_LENGTH] = { 0, };
-
- CAErrorInfo_t *errorInfo = (CAErrorInfo_t *) OICCalloc(1, sizeof(CAErrorInfo_t));
+ CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
if (NULL == errorInfo)
{
OIC_LOG(ERROR, TAG, "CAErrorHandler, Memory allocation failed!");
return;
}
- CAResult_t res = CAGetErrorInfoFromPDU(pdu, errorInfo, uri, CA_MAX_URI_LENGTH);
+ CAResult_t res = CAGetErrorInfoFromPDU(pdu, errorInfo);
if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "CAGetErrorInfoFromPDU failed : %d", res);
errorInfo->info.tokenLength);
OIC_LOG_V(DEBUG, TAG, "CAErrorHandler, msgID : %d", errorInfo->info.messageId);
- CARemoteEndpoint_t *rep = NULL;
- rep = CACloneRemoteEndpoint(remoteEndpoint);
- if(!rep)
+ CAEndpoint_t *rep = NULL;
+ rep = CACloneEndpoint(endpoint);
+ if (!rep)
{
- OIC_LOG(ERROR, TAG, "CAErrorHandler, CloneRemoteEndpoint Failed");
+ OIC_LOG(ERROR, TAG, "CAErrorHandler, CloneEndpoint Failed");
OICFree(errorInfo);
coap_delete_pdu(pdu);
return;
}
- if(NULL == rep->resourceUri)
- {
- CAURI_t resourceUri = OICStrdup(uri);
- if (NULL == resourceUri)
- {
- OIC_LOG(ERROR, TAG, "CAErrorHandler, Memory allocation failed!");
- OICFree(errorInfo);
- coap_delete_pdu(pdu);
- return;
- }
-
- OIC_LOG_V(DEBUG, TAG, "URI : %s", resourceUri);
- rep->resourceUri = resourceUri;
- }
-
// store the data at queue.
CAData_t *cadata = NULL;
cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
if (NULL == cadata)
{
OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
- CADestroyRemoteEndpointInternal(rep);
+ CADestroyEndpointInternal(rep);
OICFree(errorInfo);
coap_delete_pdu(pdu);
return;
cadata->responseInfo = NULL;
cadata->errorInfo = errorInfo;
cadata->dataType = CA_ERROR_DATA;
+
CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
coap_delete_pdu(pdu);
typedef struct
{
CASendDataType_t type;
- CARemoteEndpoint_t *remoteEndpoint;
+ CAEndpoint_t *remoteEndpoint;
CARequestInfo_t *requestInfo;
CAResponseInfo_t *responseInfo;
CAHeaderOption_t *options;
static CAResponseCallback g_responseHandler = NULL;
static CAErrorCallback g_errorHandler = NULL;
-static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size)
+static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
{
OIC_LOG(DEBUG, TAG, "IN");
- CARemoteEndpoint_t* ep = CACloneRemoteEndpoint(endpoint);
+ CAEndpoint_t* ep = CACloneEndpoint(endpoint);
if (NULL == ep)
{
OIC_LOG(ERROR, TAG, "clone failed");
if (NULL == resInfo)
{
OIC_LOG(ERROR, TAG, "calloc failed");
- CADestroyRemoteEndpointInternal(ep);
+ CADestroyEndpointInternal(ep);
return;
}
g_responseHandler(ep, resInfo);
}
- CADestroyRemoteEndpointInternal(ep);
+ CADestroyEndpointInternal(ep);
OICFree(resInfo);
OIC_LOG(DEBUG, TAG, "OUT");
{
OIC_LOG(DEBUG, TAG, "reqInfo avlbl");
- pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
- data->requestInfo->method,
- data->requestInfo->info);
+ pdu = (coap_pdu_t *)CAGeneratePDU(data->requestInfo->method, &data->requestInfo->info);
}
else if (NULL != data->responseInfo)
{
OIC_LOG(DEBUG, TAG, "resInfo avlbl");
- pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
- data->responseInfo->result,
- data->responseInfo->info);
+ pdu = (coap_pdu_t *)CAGeneratePDU(data->responseInfo->result, &data->responseInfo->info);
}
else
{
{
OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
- CAInfo_t info = data->requestInfo->info;
+ CAInfo_t *info = &data->requestInfo->info;
- info.options = data->options;
- info.numOptions = data->numOptions;
+ info->options = data->options;
+ info->numOptions = data->numOptions;
- coap_pdu_t *pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri, CA_GET,
- info);
+ coap_pdu_t *pdu = (coap_pdu_t *)CAGeneratePDU(CA_GET, info);
if (NULL != pdu)
{
CALogPDUInfo(pdu);
- res = CASendMulticastData(pdu->hdr, pdu->length);
+ res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
if(CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
OIC_LOG(DEBUG, TAG, "OUT");
}
-static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+static void CAReceivedPacketCallback(CAEndpoint_t *endpoint, void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL_VOID(data, TAG, "data");
return;
}
- CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo, uri, sizeof(uri));
+ CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo);
if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
OIC_LOG_V(DEBUG, TAG, "code: %d", ReqInfo->method);
OIC_LOG(DEBUG, TAG, "token:");
OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token, CA_MAX_TOKEN_LEN);
- if (NULL != endpoint)
- {
- endpoint->resourceUri = (char *) OICMalloc(sizeof(uri) + 1);
- if (NULL == endpoint->resourceUri)
- {
- OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
- OICFree(ReqInfo);
- coap_delete_pdu(pdu);
- return;
- }
- memcpy(endpoint->resourceUri, uri, sizeof(uri));
- endpoint->resourceUri[sizeof(uri)] = '\0';
- OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
- }
if (ReqInfo)
{
return;
}
- CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo, uri, sizeof(uri));
+ CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo);
if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
}
OIC_LOG_V(DEBUG, TAG, "code: %d", ResInfo->result);
- if (NULL != endpoint)
- {
- endpoint->resourceUri = (char *) OICMalloc(sizeof(uri) + 1);
- if (NULL == endpoint->resourceUri)
- {
- OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
- OICFree(ResInfo);
- coap_delete_pdu(pdu);
- return;
- }
- memcpy(endpoint->resourceUri, uri, sizeof(uri));
- endpoint->resourceUri[sizeof(uri)] = '\0';
- OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
- }
-
// for retransmission
void *retransmissionPdu = NULL;
CARetransmissionReceivedData(&g_retransmissionContext, endpoint, pdu->hdr, pdu->length,
}
}
- if (endpoint && endpoint->resourceUri)
- {
- OICFree(endpoint->resourceUri);
- endpoint->resourceUri = NULL;
- }
if (pdu)
{
coap_delete_pdu(pdu);
OIC_LOG(DEBUG, TAG, "OUT");
}
-static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
+static void CANetworkChangedCallback(CAEndpoint_t *info, CANetworkStatus_t status)
{
OIC_LOG(DEBUG, TAG, "IN");
CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
}
-CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object, const CARequestInfo_t *request)
+CAResult_t CADetachRequestMessage(const CAEndpoint_t *object, const CARequestInfo_t *request)
{
OIC_LOG(DEBUG, TAG, "IN");
return CA_MEMORY_ALLOC_FAILED;
}
-CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
- const CARequestInfo_t *request)
-{
- OIC_LOG(DEBUG, TAG, "IN");
-
- if (NULL == object || NULL == request || NULL == object->resourceUri)
- {
- return CA_STATUS_INVALID_PARAM;
- }
-
- if ((request->method < CA_GET) || (request->method > CA_DELETE))
- {
- OIC_LOG(ERROR, TAG, "Invalid method type!");
-
- return CA_STATUS_INVALID_PARAM;
- }
-
- // allocate & initialize
- CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
- CA_MEMORY_ALLOC_CHECK(data);
-
- CAAddress_t addr = {0};
- CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(object->resourceUri, addr,
- object->transportType);
-
- // save data
- data->type = SEND_TYPE_MULTICAST;
- data->remoteEndpoint = remoteEndpoint;
- data->requestInfo = request;
- data->responseInfo = NULL;
-
- CAProcessData(data);
- CADestroyRemoteEndpointInternal(remoteEndpoint);
-
- OICFree(data);
- OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
-
-// memory error label.
-memory_error_exit:
-
- OICFree(data);
- OIC_LOG(DEBUG, TAG, "OUT");
- return CA_MEMORY_ALLOC_FAILED;
-}
-
-CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
+CAResult_t CADetachResponseMessage(const CAEndpoint_t *object,
const CAResponseInfo_t *response)
{
OIC_LOG(DEBUG, TAG, "IN");
return CA_MEMORY_ALLOC_FAILED;
}
-CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
- uint8_t tokenLength, const CAHeaderOption_t *options,
- uint8_t numOptions)
-{
- OIC_LOG(DEBUG, TAG, "IN");
- VERIFY_NON_NULL(resourceUri, TAG, "resourceUri is NULL");
- VERIFY_NON_NULL(token, TAG, "Token is NULL");
-
- // allocate & initialize
- CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
- CA_MEMORY_ALLOC_CHECK(data);
-
- CAAddress_t addr = {0};
- CARemoteEndpoint_t *remoteEndpoint =
- CACreateRemoteEndpointInternal(resourceUri, addr, CA_IPV4 | CA_EDR | CA_LE);
-
- // create request info
- CARequestInfo_t *reqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
- CA_MEMORY_ALLOC_CHECK(reqInfo);
-
- // save request info data
- reqInfo->method = CA_GET;
- reqInfo->info.type = CA_MSG_NONCONFIRM;
-
- reqInfo->info.token = token;
- reqInfo->info.tokenLength = tokenLength;
-
- // save data
- data->type = SEND_TYPE_MULTICAST;
- data->remoteEndpoint = remoteEndpoint;
- data->requestInfo = reqInfo;
-
- data->responseInfo = NULL;
- data->options = NULL;
- data->numOptions = 0;
- CAHeaderOption_t *headerOption = NULL;
- if (NULL != options && numOptions > 0)
- {
- // copy data
- headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * numOptions);
- CA_MEMORY_ALLOC_CHECK(headerOption);
- memcpy(headerOption, options, sizeof(CAHeaderOption_t) * numOptions);
-
- data->options = headerOption;
- data->numOptions = numOptions;
- }
-
- CAProcessData(data);
-
- CADestroyRemoteEndpoint(remoteEndpoint);
- OICFree(headerOption);
- OICFree(data);
- OICFree(reqInfo);
- OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
-
-// memory error label.
-memory_error_exit:
-
- CADestroyRemoteEndpointInternal(remoteEndpoint);
-
- OICFree(reqInfo);
- OICFree(data);
- OIC_LOG(DEBUG, TAG, "OUT");
- return CA_MEMORY_ALLOC_FAILED;
-}
-
-void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
- CAErrorCallback errorHandler)
+void CASetInterfaceCallbacks(CARequestCallback ReqHandler,
+ CAResponseCallback RespHandler, CAErrorCallback errorHandler)
{
OIC_LOG(DEBUG, TAG, "IN");
g_requestHandler = ReqHandler;
#include <stdlib.h>
#include "canetworkconfigurator.h"
-#include "cainterfacecontroller_singlethread.h"
+#include "cainterfacecontroller.h"
#include "uarraylist.h"
#include "logger.h"
#define TAG "CANW"
static u_arraylist_t *g_selectedNetworkList = NULL;
-static uint32_t NETWORK_IP = CA_IPV4;
-static uint32_t NETWORK_EDR = CA_EDR;
-static uint32_t NETWORK_LE = CA_LE;
+static uint32_t NETWORK_IP = CA_ADAPTER_IP;
+static uint32_t NETWORK_RFCOMM = CA_ADAPTER_RFCOMM_BTEDR;
+static uint32_t NETWORK_GATT = CA_ADAPTER_GATT_BTLE;
-
-CAResult_t CAAddNetworkType(CATransportType_t transportType)
+CAResult_t CAAddNetworkType(CATransportAdapter_t transportType)
{
OIC_LOG(DEBUG, TAG, "IN");
if (NULL == g_selectedNetworkList)
CAResult_t res = CA_STATUS_OK;
switch (transportType)
{
- case CA_IPV4:
- {
-
+ case CA_ADAPTER_IP:
#ifndef IP_ADAPTER
OIC_LOG(DEBUG, TAG, "Add network type(IP) - Not Supported");
return CA_NOT_SUPPORTED;
goto exit;
}
res = u_arraylist_add(g_selectedNetworkList, &NETWORK_IP);
- }
- break;
- case CA_IPV6:
- {
- OIC_LOG(ERROR, TAG, "Currently IPV6 is not supported");
- return CA_NOT_SUPPORTED;
- }
-
- case CA_EDR:
- {
+ break;
+ case CA_ADAPTER_RFCOMM_BTEDR:
#ifndef EDR_ADAPTER
OIC_LOG(DEBUG, TAG, "Add network type(EDR) - Not Supported");
return CA_NOT_SUPPORTED;
#endif /* EDR_ADAPTER */
OIC_LOG(DEBUG, TAG, "Add network type(EDR)");
- if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_EDR))
+ if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_RFCOMM))
{
goto exit;
}
- res = u_arraylist_add(g_selectedNetworkList, &NETWORK_EDR);
- }
- break;
-
- case CA_LE:
- {
+ res = u_arraylist_add(g_selectedNetworkList, &NETWORK_RFCOMM);
+ break;
+ case CA_ADAPTER_GATT_BTLE:
#ifndef LE_ADAPTER
OIC_LOG(DEBUG, TAG, "Add network type(LE) - Not Supported");
return CA_NOT_SUPPORTED;
#endif /* LE_ADAPTER */
OIC_LOG(DEBUG, TAG, "Add network type(LE)");
- if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_LE))
+ if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_GATT))
{
goto exit;
}
- res = u_arraylist_add(g_selectedNetworkList, &NETWORK_LE);
- }
- break;
-
+ res = u_arraylist_add(g_selectedNetworkList, &NETWORK_GATT);
+ break;
+ default:
+ break;
}
if (CA_STATUS_OK != res)
return res;
}
// start selected interface adapter
- res = CAStartAdapter((CATransportType_t)transportType);
+ res = CAStartAdapter(transportType);
OIC_LOG(DEBUG, TAG, "OUT");
return res;
return CA_STATUS_OK;
}
-CAResult_t CARemoveNetworkType(CATransportType_t transportType)
+CAResult_t CARemoveNetworkType(CATransportAdapter_t transportType)
{
OIC_LOG(DEBUG, TAG, "IN");
continue;
}
- CATransportType_t connType = *(CATransportType_t *) ptrType;
+ CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
if (transportType == connType)
{
switch (transportType)
{
- case CA_IPV4:
-
+ case CA_ADAPTER_IP:
#ifndef IP_ADAPTER
OIC_LOG(DEBUG, TAG, "Remove network type(IP) - Not Supported");
return CA_NOT_SUPPORTED;
#endif /* IP_ADAPTER */
break;
- case CA_IPV6:
- {
- OIC_LOG(ERROR, TAG, "Currently IPV6 is not supported");
- return CA_NOT_SUPPORTED;
- }
-
- case CA_EDR:
-
+ case CA_ADAPTER_RFCOMM_BTEDR:
#ifndef EDR_ADAPTER
OIC_LOG(DEBUG, TAG, "Remove network type(EDR) - Not Supported");
return CA_NOT_SUPPORTED;
OIC_LOG(DEBUG, TAG, "Remove network type(EDR)");
u_arraylist_remove(g_selectedNetworkList, index);
#endif /* EDR_ADAPTER */
-
break;
- case CA_LE:
-
+ case CA_ADAPTER_GATT_BTLE:
#ifndef LE_ADAPTER
OIC_LOG(DEBUG, TAG, "Remove network type(LE) - Not Supported");
return CA_NOT_SUPPORTED;
OIC_LOG(DEBUG, TAG, "Remove network type(LE)");
u_arraylist_remove(g_selectedNetworkList, index);
#endif /* LE_ADAPTER */
+ break;
+ default:
break;
}
return g_selectedNetworkList;
}
-CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_t *size)
+CAResult_t CAGetNetworkInformationInternal(CAEndpoint_t **info, uint32_t *size)
{
OIC_LOG(DEBUG, TAG, "get network information.");
#define TAG "CA"
+/**
+ * @def VERIFY_NON_NULL_RET
+ * @brief Macro to verify the validity of input argument
+ */
+#define VERIFY_NON_NULL_RET(arg, log_tag, log_message,ret) \
+ if (NULL == arg ){ \
+ OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
+ return ret; \
+ }
+
#define CA_BUFSIZE (128)
#define CA_PDU_MIN_SIZE (4)
#define CA_PORT_BUFFER_SIZE (4)
static uint32_t SEED = 0;
-CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo,
- char *outUri, uint32_t buflen)
+CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo)
{
OIC_LOG(DEBUG, TAG, "IN");
- if (NULL == pdu || NULL == outReqInfo || NULL == outUri)
+ if (NULL == pdu || NULL == outReqInfo)
{
OIC_LOG(ERROR, TAG, "parameter is null");
return CA_STATUS_INVALID_PARAM;
}
uint32_t code = CA_NOT_FOUND;
-
- OIC_LOG_V(DEBUG, TAG, "buffer length : %d", buflen);
- CAResult_t ret = CAGetInfoFromPDU(pdu, &code, &(outReqInfo->info), outUri, buflen);
+ CAResult_t ret = CAGetInfoFromPDU(pdu, &code, &(outReqInfo->info));
outReqInfo->method = code;
+
OIC_LOG(DEBUG, TAG, "OUT");
return ret;
}
-CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
- char *outUri, uint32_t buflen)
+CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo)
{
OIC_LOG(DEBUG, TAG, "IN");
- if (NULL == pdu || NULL == outResInfo || NULL == outUri)
+ if (NULL == pdu || NULL == outResInfo)
{
OIC_LOG(ERROR, TAG, "parameter is null");
return CA_STATUS_INVALID_PARAM;
}
uint32_t code = CA_NOT_FOUND;
- CAResult_t ret = CAGetInfoFromPDU(pdu, &code, &(outResInfo->info), outUri, buflen);
+ CAResult_t ret = CAGetInfoFromPDU(pdu, &code, &(outResInfo->info));
outResInfo->result = code;
+
OIC_LOG(DEBUG, TAG, "OUT");
return ret;
}
-CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, CAErrorInfo_t *errorInfo,
- char *uri, uint32_t buflen)
+CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, CAErrorInfo_t *errorInfo)
{
OIC_LOG(DEBUG, TAG, "IN");
- if (!pdu || !errorInfo || !uri)
+ if (!pdu)
{
OIC_LOG(ERROR, TAG, "parameter is null");
return CA_STATUS_INVALID_PARAM;
}
uint32_t code = 0;
- CAResult_t ret = CAGetInfoFromPDU(pdu, &code, &errorInfo->info, uri, buflen);
+ CAResult_t ret = CAGetInfoFromPDU(pdu, &code, &errorInfo->info);
OIC_LOG(DEBUG, TAG, "OUT");
return ret;
}
-coap_pdu_t *CAGeneratePDU(const char *uri, uint32_t code, const CAInfo_t info)
+coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info)
{
OIC_LOG(DEBUG, TAG, "IN");
// RESET have to use only 4byte (empty message)
// and ACKNOWLEDGE can use empty message when code is empty.
- if (CA_MSG_RESET == info.type || (CA_EMPTY == code && CA_MSG_ACKNOWLEDGE == info.type))
+ if (CA_MSG_RESET == info->type || (CA_EMPTY == code && CA_MSG_ACKNOWLEDGE == info->type))
{
OIC_LOG(DEBUG, TAG, "code is empty");
if (!(pdu = CAGeneratePDUImpl((code_t) code, NULL, info, NULL, 0)))
{
coap_list_t *optlist = NULL;
- if (CA_MSG_ACKNOWLEDGE != info.type)
+ if (CA_MSG_ACKNOWLEDGE != info->type)
{
+ const char *uri = info->resourceUri;
if (NULL == uri)
{
OIC_LOG(ERROR, TAG, "uri NULL");
coap_delete_list(optlist);
return NULL;
}
- size_t lenPayload = info.payload ? strlen(info.payload) : 0;
- pdu = CAGeneratePDUImpl((code_t) code, optlist, info, info.payload, lenPayload);
+ size_t lenPayload = info->payload ? strlen(info->payload) : 0;
+ pdu = CAGeneratePDUImpl((code_t)code, optlist, info, info->payload, lenPayload);
if (NULL == pdu)
{
OIC_LOG(ERROR, TAG, "pdu NULL");
return outpdu;
}
-coap_pdu_t *CAGeneratePDUImpl(code_t code, coap_list_t *options, const CAInfo_t info,
+coap_pdu_t *CAGeneratePDUImpl(code_t code, coap_list_t *options, const CAInfo_t *info,
const char *payload, size_t payloadSize)
{
OIC_LOG(DEBUG, TAG, "IN");
+ VERIFY_NON_NULL_RET(info, TAG, "info is NULL", NULL);
coap_pdu_t *pdu = coap_new_pdu();
return NULL;
}
- OIC_LOG_V(DEBUG, TAG, "msgID is %d", info.messageId);
+ OIC_LOG_V(DEBUG, TAG, "msgID is %d", info->messageId);
uint16_t message_id;
- if (0 == info.messageId)
+ if (0 == info->messageId)
{
/* initialize message id */
prng((uint8_t * ) &message_id, sizeof(message_id));
else
{
/* use saved message id */
- message_id = info.messageId;
+ message_id = info->messageId;
}
pdu->hdr->id = message_id;
OIC_LOG_V(DEBUG, TAG, "messageId in pdu is %d, %d", message_id, pdu->hdr->id);
- pdu->hdr->type = info.type;
+ pdu->hdr->type = info->type;
pdu->hdr->code = COAP_RESPONSE_CODE(code);
- if (info.token && CA_EMPTY != code)
+ if (info->token && CA_EMPTY != code)
{
- uint32_t tokenLength = info.tokenLength;
+ uint32_t tokenLength = info->tokenLength;
OIC_LOG_V(DEBUG, TAG, "token info token length: %d, token :", tokenLength);
- OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)info.token, tokenLength);
+ OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)info->token, tokenLength);
- int32_t ret = coap_add_token(pdu, tokenLength, (unsigned char *) info.token);
+ int32_t ret = coap_add_token(pdu, tokenLength, (unsigned char *)info->token);
if (0 == ret)
{
OIC_LOG(ERROR, TAG, "can't add token");
int ret = coap_insert(optlist,
CACreateNewOptionNode(COAP_OPTION_URI_PORT,
coap_encode_var_bytes(portbuf, uri.port),
- portbuf),
+ (char *)portbuf),
CAOrderOpts);
if (ret <= 0)
{
if (uri.path.s && uri.path.length)
{
- CAResult_t ret = CAParseUriPartial(uri.path.s, uri.path.length, COAP_OPTION_URI_PATH,
- optlist);
+ CAResult_t ret = CAParseUriPartial(uri.path.s, uri.path.length,
+ COAP_OPTION_URI_PATH, optlist);
if (CA_STATUS_OK != ret)
{
OIC_LOG(ERROR, TAG, "CAParseUriPartial failed(uri path)");
{
int ret = coap_insert(optlist,
CACreateNewOptionNode(target, COAP_OPT_LENGTH(pBuf),
- COAP_OPT_VALUE(pBuf)),
+ (char *)COAP_OPT_VALUE(pBuf)),
CAOrderOpts);
if (ret <= 0)
{
return CA_STATUS_OK;
}
-CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t info, coap_list_t **optlist)
+CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **optlist)
{
OIC_LOG(DEBUG, TAG, "IN");
+ VERIFY_NON_NULL_RET(info, TAG, "info is NULL", CA_STATUS_INVALID_PARAM);
- OIC_LOG_V(DEBUG, TAG, "parse Head Opt: %d", info.numOptions);
+ OIC_LOG_V(DEBUG, TAG, "parse Head Opt: %d", info->numOptions);
if (!optlist)
{
return CA_STATUS_INVALID_PARAM;
}
- for (uint32_t i = 0; i < info.numOptions; i++)
+ for (uint32_t i = 0; i < info->numOptions; i++)
{
- if(!(info.options + i))
+ if(!(info->options + i))
{
OIC_LOG(ERROR, TAG, "options is not available");
return CA_STATUS_FAILED;
}
- uint32_t id = (info.options + i)->optionID;
+ uint32_t id = (info->options + i)->optionID;
if (COAP_OPTION_URI_PATH == id || COAP_OPTION_URI_QUERY == id)
{
OIC_LOG_V(DEBUG, TAG, "not Header Opt: %d", id);
}
else
{
- if ((info.options + i)->optionData && (info.options + i)->optionLength > 0)
+ if ((info->options + i)->optionData && (info->options + i)->optionLength > 0)
{
OIC_LOG_V(DEBUG, TAG, "Head opt ID: %d", id);
- OIC_LOG_V(DEBUG, TAG, "Head opt data: %s", (info.options + i)->optionData);
- OIC_LOG_V(DEBUG, TAG, "Head opt length: %d", (info.options + i)->optionLength);
+ OIC_LOG_V(DEBUG, TAG, "Head opt data: %s", (info->options + i)->optionData);
+ OIC_LOG_V(DEBUG, TAG, "Head opt length: %d", (info->options + i)->optionLength);
int ret = coap_insert(optlist,
- CACreateNewOptionNode(id, (info.options + i)->optionLength,
- (info.options + i)->optionData),
+ CACreateNewOptionNode(id, (info->options + i)->optionLength,
+ (info->options + i)->optionData),
CAOrderOpts);
if (ret <= 0)
{
return CA_STATUS_OK;
}
-coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const uint8_t *data)
+coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const char *data)
{
OIC_LOG(DEBUG, TAG, "IN");
return count;
}
-CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo,
- char *outUri, uint32_t buflen)
+CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo)
{
OIC_LOG(DEBUG, TAG, "IN");
- if (!pdu || !outCode || !outInfo || !outUri)
+ if (!pdu || !outCode || !outInfo)
{
OIC_LOG(ERROR, TAG, "NULL pointer param");
return CA_STATUS_INVALID_PARAM;
}
uint32_t length = strlen(optionResult);
- OIC_LOG_V(DEBUG, TAG, "URL length:%d,%d,%d", length, buflen, strlen(outUri));
- if (buflen >= length)
+ OIC_LOG_V(DEBUG, TAG, "URL length:%d", length);
+
+ outInfo->resourceUri = OICMalloc(length + 1);
+ if (!outInfo->resourceUri)
{
- memcpy(outUri, optionResult, length);
-#ifdef ARDUINO
- OIC_LOG_V(DEBUG, TAG, "made URL:%s\n", optionResult);
-#else
- OIC_LOG_V(DEBUG, TAG, "made URL : %s, %s", optionResult, outUri);
-#endif
+ OIC_LOG(ERROR, TAG, "Out of memory");
+ OICFree(outInfo->options);
+ OICFree(outInfo->token);
+ return CA_MEMORY_ALLOC_FAILED;
}
+ memcpy(outInfo->resourceUri, optionResult, length);
+ outInfo->resourceUri[length] = '\0';
+ OIC_LOG_V(DEBUG, TAG, "made URL : %s, %s", optionResult, outInfo->resourceUri);
+
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
#define TAG "CA"
-CARemoteEndpoint_t *CACloneRemoteEndpoint(const CARemoteEndpoint_t *rep)
+CAEndpoint_t *CACloneEndpoint(const CAEndpoint_t *rep)
{
if (NULL == rep)
{
}
// allocate the remote end point structure.
- CARemoteEndpoint_t *clone = (CARemoteEndpoint_t *) OICMalloc(sizeof(CARemoteEndpoint_t));
+ CAEndpoint_t *clone = (CAEndpoint_t *)OICMalloc(sizeof (CAEndpoint_t));
if (NULL == clone)
{
OIC_LOG(ERROR, TAG, "CACloneRemoteEndpoint Out of memory");
}
*clone = *rep;
- if (NULL != rep->resourceUri)
- {
- // allocate reference uri field
- char *temp = OICStrdup(rep->resourceUri);
- if (NULL == temp)
- {
- OIC_LOG(ERROR, TAG, "CACloneRemoteEndpoint Out of memory");
-
- CADestroyRemoteEndpointInternal(clone);
-
- return NULL;
- }
-
- // save the uri
- clone->resourceUri = temp;
- }
-
return clone;
}
-#define COAP_PREFIX "coap://"
-#define COAP_PREFIX_LEN 7
-#define COAPS_PREFIX "coaps://"
-#define COAPS_PREFIX_LEN 8
-
-
-// return 1 : ip
-// return 0 : mac
-static int32_t getCAAddress(const char *pAddress, CAAddress_t *outAddress)
-{
- if (NULL == pAddress || NULL == outAddress)
- {
- OIC_LOG(ERROR, TAG, "parameter is null");
- return -1;
- }
-
- // simple parse, it will be change.
- // 10.11.12.13:4545 (ip)
- // 10:11:12:13:45:45 (mac)
-
- int32_t len = strlen(pAddress);
-
- int32_t isIp = 0;
- int32_t ipLen = 0;
-
- int i = 0;
- for (i = 0; i < len; i++)
- {
- if (pAddress[i] == '.')
- {
- isIp = 1;
- }
-
- // found port number start index
- if (isIp && pAddress[i] == ':')
- {
- ipLen = i;
- break;
- }
- }
-
- if (isIp)
- {
- if(ipLen && ipLen < sizeof(outAddress->IP.ipAddress))
- {
- OICStrcpyPartial(outAddress->IP.ipAddress, sizeof(outAddress->IP.ipAddress),
- pAddress, ipLen);
- }
- else if (!ipLen && len < sizeof(outAddress->IP.ipAddress))
- {
- OICStrcpy(outAddress->IP.ipAddress, sizeof(outAddress->IP.ipAddress),
- pAddress);
- }
- else
- {
- OIC_LOG_V(ERROR, TAG, "IP Address too long: %d", ipLen==0 ? len : ipLen);
- return -1;
- }
-
-
- if (ipLen > 0)
- {
- outAddress->IP.port = atoi(pAddress + ipLen + 1);
- }
-
- OIC_LOG_V(DEBUG, TAG, "ip: %s, port: %d", outAddress->IP.ipAddress, outAddress->IP.port);
- }
- else
- {
- OICStrcpy(outAddress->BT.btMacAddress, sizeof(outAddress->BT.btMacAddress),
- pAddress);
-
- OIC_LOG_V(DEBUG, TAG, "mac address : %s", outAddress->BT.btMacAddress);
- }
-
- return isIp;
-}
-
-CARemoteEndpoint_t *CACreateRemoteEndpointUriInternal(const CAURI_t uri,
- const CATransportType_t transportType)
-{
- // support URI type
- // coap://10.11.12.13:4545/resource_uri
- // coap://10:11:12:13:45:45/resource_uri
-
- if (NULL == uri)
- {
- OIC_LOG(ERROR, TAG, "parameter is null");
- return NULL;
- }
-
- // parse uri
- // #1. check prefix
- int startIndex = 0;
- bool secured = false;
- if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
- {
- OIC_LOG_V(DEBUG, TAG, "uri has '%s' prefix.", COAP_PREFIX);
- startIndex = COAP_PREFIX_LEN;
- }
-
- if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
- {
- OIC_LOG_V(DEBUG, TAG, "uri has '%s' prefix.", COAPS_PREFIX);
- startIndex = COAPS_PREFIX_LEN;
- secured = true;
- }
-
- // #2. copy uri for parse
- int32_t len = strlen(uri) - startIndex;
-
- if (len <= 0)
- {
- OIC_LOG(ERROR, TAG, "uri length is 0!");
- return NULL;
- }
-
- char *cloneUri = (char *) OICCalloc(len + 1, sizeof(char));
- if (NULL == cloneUri)
- {
- OIC_LOG(ERROR, TAG, "CACreateRemoteEndpointUriInternal Out of memory");
- return NULL;
- }
-
- memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
- cloneUri[len] = '\0';
-
- // #3. parse address
- // #4. parse resource uri
- char *pAddress = cloneUri;
- char *pResourceUri = NULL;
-
- int32_t i = 0;
- for (i = 0; i < len; i++)
- {
- if (cloneUri[i] == '/')
- {
- // separate
- cloneUri[i] = 0;
-
- pResourceUri = &cloneUri[i + 1];
-
- break;
- }
-
- }
-
- OIC_LOG_V(DEBUG, TAG, "pAddress : %s", pAddress);
-
- OIC_LOG_V(DEBUG, TAG, "pResourceUri : %s", pResourceUri == NULL ? "" : pResourceUri);
-
- // address
- CAAddress_t address = {};
-
- int resType = getCAAddress(pAddress, &address);
- if (resType == -1)
- {
- OIC_LOG(DEBUG, TAG, "address parse error");
-
- OICFree(cloneUri);
- return NULL;
- }
-
- // resource uri
- CAURI_t resourceUri = pResourceUri;
-
- CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, address,
- transportType);
- if (NULL == remoteEndpoint)
- {
- OIC_LOG(ERROR, TAG, "create remote endpoint fail");
-
- OICFree(cloneUri);
- return NULL;
- }
- remoteEndpoint->isSecured = secured;
-
- OICFree(cloneUri);
-
- OIC_LOG_V(DEBUG, TAG, "Remote endpoint successfully created [%d]!", remoteEndpoint->isSecured);
- return remoteEndpoint;
-}
-
-CARemoteEndpoint_t *CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
- const CAAddress_t addr,
- const CATransportType_t type)
-{
- if (NULL == resourceUri)
- {
- OIC_LOG(ERROR, TAG, "uri is null value");
- return NULL;
- }
-
- // allocate the remote end point structure.
- CARemoteEndpoint_t *rep = (CARemoteEndpoint_t *) OICCalloc(1, sizeof(CARemoteEndpoint_t));
-
- if (NULL == rep)
- {
- OIC_LOG(ERROR, TAG, "CACreateRemoteEndpointInternal of memory");
- return NULL;
- }
-
- // allocate reference uri field
- char *temp = OICStrdup(resourceUri);
- if (NULL == temp)
- {
- OIC_LOG(ERROR, TAG, "CACreateRemoteEndpointInternal Out of memory");
-
- CADestroyRemoteEndpointInternal(rep);
-
- return NULL;
- }
-
- // save the uri
- rep->resourceUri = temp;
-
- // save the addressInfo
- rep->addressInfo = addr;
-
- // save the type
- rep->transportType = type;
-
- return rep;
-}
-
CARequestInfo_t *CACloneRequestInfo(const CARequestInfo_t *rep)
{
if (NULL == rep)
return clone;
}
-void CADestroyRemoteEndpointInternal(CARemoteEndpoint_t *rep)
+void CADestroyEndpointInternal(CAEndpoint_t *rep)
{
- if (NULL == rep)
- {
- OIC_LOG(ERROR, TAG, "parameter is null");
- return;
- }
-
- // free uri field
- OICFree((char *) rep->resourceUri);
-
- // free remote end point structure.
OICFree(rep);
}
uint64_t timeout; /**< timeout value. microseconds */
uint8_t triedCount; /**< retransmission count */
uint16_t messageId; /**< coap PDU message id */
- CARemoteEndpoint_t *endpoint; /**< remote endpoint */
+ CAEndpoint_t *endpoint; /**< remote endpoint */
void *pdu; /**< coap PDU */
uint32_t size; /**< coap PDU size */
} CARetransmissionData_t;
if (currentTime >= timeStamp + timeout)
{
- OIC_LOG_V(DEBUG, TAG, "%d microseconds time out!!, tried count(%d)", timeout, triedCount);
+ OIC_LOG_V(DEBUG, TAG, "%d microseconds time out!!, tried count(%ld)", timeout, triedCount);
return true;
}
removedData->size);
}
- CADestroyRemoteEndpointInternal(removedData->endpoint);
+ CADestroyEndpointInternal(removedData->endpoint);
OICFree(removedData->pdu);
OICFree(removedData);
else if (!context->isStop)
{
// check each RETRANSMISSION_CHECK_PERIOD_SEC time.
- OIC_LOG_V(DEBUG, TAG, "wait..(%d)microseconds",
+ OIC_LOG_V(DEBUG, TAG, "wait..(%ld)microseconds",
RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC);
// wait
}
CAResult_t CARetransmissionSentData(CARetransmission_t *context,
- const CARemoteEndpoint_t* endpoint, const void* pdu,
- uint32_t size)
+ const CAEndpoint_t *endpoint,
+ const void *pdu, uint32_t size)
{
if (NULL == context || NULL == endpoint || NULL == pdu)
{
}
// #0. check support transport type
- if (!(context->config.supportType & endpoint->transportType))
+ if (!(context->config.supportType & endpoint->adapter))
{
OIC_LOG_V(DEBUG, TAG, "not supported transport type for retransmission..(%d)",
- endpoint->transportType);
+ endpoint->adapter);
return CA_NOT_SUPPORTED;
}
memcpy(pduData, pdu, size);
// clone remote endpoint
- CARemoteEndpoint_t *remoteEndpoint = CACloneRemoteEndpoint(endpoint);
+ CAEndpoint_t *remoteEndpoint = CACloneEndpoint(endpoint);
if (NULL == remoteEndpoint)
{
OICFree(retData);
// found index
if (NULL != currData->endpoint && currData->messageId == messageId
- && (currData->endpoint->transportType == endpoint->transportType))
+ && (currData->endpoint->adapter == endpoint->adapter))
{
OIC_LOG(ERROR, TAG, "Duplicate message ID");
}
CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
- const CARemoteEndpoint_t *endpoint, const void *pdu,
+ const CAEndpoint_t *endpoint, const void *pdu,
uint32_t size, void **retransmissionPdu)
{
OIC_LOG(DEBUG, TAG, "IN - CARetransmissionReceivedData");
}
// #0. check support transport type
- if (!(context->config.supportType & endpoint->transportType))
+ if (!(context->config.supportType & endpoint->adapter))
{
OIC_LOG_V(DEBUG, TAG, "not supported transport type for retransmission..(%d)",
- endpoint->transportType);
+ endpoint->adapter);
return CA_STATUS_OK;
}
// found index
if (NULL != retData->endpoint && retData->messageId == messageId
- && (retData->endpoint->transportType == endpoint->transportType))
+ && (retData->endpoint->adapter == endpoint->adapter))
{
// get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
// if retransmission was finish..token will be unavailable.
OIC_LOG_V(DEBUG, TAG, "remove retransmission CON data!!, message id(%d)",
messageId);
- CADestroyRemoteEndpointInternal(removedData->endpoint);
+ CADestroyEndpointInternal(removedData->endpoint);
OICFree(removedData->pdu);
OICFree(removedData);
clock_gettime(CLOCK_MONOTONIC, &getTs);
currentTime = (getTs.tv_sec * (uint64_t)1000000000 + getTs.tv_nsec)/1000;
- OIC_LOG_V(DEBUG, TAG, "current time = %d", currentTime);
+ OIC_LOG_V(DEBUG, TAG, "current time = %ld", currentTime);
#else
#if _POSIX_TIMERS > 0
struct timespec ts;
uint16_t messageId;
/** remote endpoint **/
- CARemoteEndpoint_t *endpoint;
+ CAEndpoint_t *endpoint;
/** coap PDU **/
void *pdu;
removedData->size);
}
- CADestroyRemoteEndpointInternal(removedData->endpoint);
+ CADestroyEndpointInternal(removedData->endpoint);
OICFree(removedData->pdu);
OICFree(removedData);
if (NULL == config)
{
// setDefault
- cfg.supportType = (CATransportType_t) DEFAULT_RETRANSMISSION_TYPE;
+ cfg.supportType = (CATransportAdapter_t) DEFAULT_RETRANSMISSION_TYPE;
cfg.tryingCount = DEFAULT_RETRANSMISSION_COUNT;
}
else
return CA_STATUS_OK;
}
-CAResult_t CARetransmissionSentData(CARetransmission_t *context, const CARemoteEndpoint_t *endpoint,
+CAResult_t CARetransmissionSentData(CARetransmission_t *context, const CAEndpoint_t *endpoint,
const void *pdu, uint32_t size)
{
OIC_LOG(DEBUG, TAG, "IN");
}
// #0. check support connectivity type
- if (!(context->config.supportType & endpoint->transportType))
+ if (!(context->config.supportType & endpoint->adapter))
{
OIC_LOG(ERROR, TAG, "error");
OIC_LOG_V(ERROR, TAG, "not supported conntype=%d", endpoint->transportType);
memcpy(pduData, pdu, size);
// clone remote endpoint
- CARemoteEndpoint_t *remoteEndpoint = CACloneRemoteEndpoint(endpoint);
+ CAEndpoint_t *remoteEndpoint = CACloneEndpoint(endpoint);
if (NULL == remoteEndpoint)
{
OICFree(retData);
}
CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
- const CARemoteEndpoint_t *endpoint, const void *pdu,
+ const CAEndpoint_t *endpoint, const void *pdu,
uint32_t size, void **retransmissionPdu)
{
OIC_LOG(DEBUG, TAG, "IN");
}
// #0. check support connectivity type
- if (!(context->config.supportType & endpoint->transportType))
+ if (!(context->config.supportType & endpoint->adapter))
{
- OIC_LOG_V(DEBUG, TAG, "not supp conntype=%d", endpoint->transportType);
+ OIC_LOG_V(DEBUG, TAG, "not supp conntype=%d", endpoint->adapter);
return CA_STATUS_OK;
}
// found index
if (NULL != retData->endpoint && retData->messageId == messageId
- && (retData->endpoint->transportType == endpoint->transportType))
+ && (retData->endpoint->adapter == endpoint->adapter))
{
// get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
// if retransmission was finish..token will be unavailable.
OIC_LOG_V(DEBUG, TAG, "remove RTCON data, msgid=%d", messageId);
- CADestroyRemoteEndpointInternal(removedData->endpoint);
+ CADestroyEndpointInternal(removedData->endpoint);
OICFree(removedData->pdu);
OICFree(removedData);
target_os = env.get('TARGET_OS')
inc_files = env.get('CPPPATH')
+secured = env.get('SECURED')
src_dir = './ip_adapter/'
if target_os == 'tizen':
env.AppendUnique(CA_SRC=[src_dir+'caipadapter_singlethread.c'])
env.AppendUnique(CPPPATH=[src_dir+'arduino/'])
else:
- env.AppendUnique(CA_SRC=[src_dir+'caipadapter.c'])
- env.AppendUnique(CA_SRC=[src_dir+'caipclient.c'])
- env.AppendUnique(CA_SRC=[src_dir+'caipserver.c'])
+ env.AppendUnique(CA_SRC=[src_dir+'caipadapter.c'])
+ env.AppendUnique(CA_SRC=[src_dir+'caipclient.c'])
+ env.AppendUnique(CA_SRC=[src_dir+'caipserver.c'])
#Source files to build in Linux platform
if target_os in ['linux','darwin','ios']:
*/
typedef struct
{
- CARemoteEndpoint_t *remoteEndpoint;
+ CAEndpoint_t *remoteEndpoint;
void *data;
uint32_t dataLen;
+ bool isMulticast;
} CAIPData;
/**
static void CAIPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status);
-static void CAIPPacketReceivedCB(const char *ipAddress, uint16_t port, const void *data,
- uint32_t dataLength, bool isSecured,
- const CARemoteId_t *identity);
+static void CAIPPacketReceivedCB(const CAEndpoint_t *endpoint,
+ const void *data, uint32_t dataLength);
#ifdef __WITH_DTLS__
-static uint32_t CAIPPacketSendCB(const char *ipAddress, uint16_t port,
- const void *data, uint32_t dataLength);
+static uint32_t CAIPPacketSendCB(const CAEndpoint_t *endpoint,
+ const void *data, uint32_t dataLength);
#endif
static CAResult_t CAIPStopServers();
static void CAIPSendDataThread(void *threadData);
-static CAIPData *CACreateIPData(const CARemoteEndpoint_t *remoteEndpoint,
- const void *data, uint32_t dataLength);
+static CAIPData *CACreateIPData(const CAEndpoint_t *remoteEndpoint,
+ const void *data, uint32_t dataLength,
+ bool isMulticast);
void CAFreeIPData(CAIPData *ipData);
static void CADataDestroyer(void *data, uint32_t size);
VERIFY_NON_NULL_VOID(address, IP_ADAPTER_TAG, "address is NULL");
- CALocalConnectivity_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_IPV4, address);
+ CAEndpoint_t *localEndpoint = CAAdapterCreateEndpoint(0, CA_ADAPTER_IP, address, port);
if (!localEndpoint)
{
OIC_LOG(ERROR, IP_ADAPTER_TAG, "localEndpoint creation failed!");
return;
}
- localEndpoint->addressInfo.IP.port = port;
-
if (g_networkChangeCallback)
{
g_networkChangeCallback(localEndpoint, status);
OIC_LOG(ERROR, IP_ADAPTER_TAG, "g_networkChangeCallback is NULL");
}
- CAAdapterFreeLocalEndpoint(localEndpoint);
+ CAAdapterFreeEndpoint(localEndpoint);
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
}
}
#ifdef __WITH_DTLS__
-uint32_t CAIPPacketSendCB(const char *ipAddress, uint16_t port,
- const void *data, uint32_t dataLength)
+uint32_t CAIPPacketSendCB(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
- VERIFY_NON_NULL_RET(ipAddress, IP_ADAPTER_TAG, "ipAddress is NULL", 0);
-
+ VERIFY_NON_NULL_RET(endpoint, IP_ADAPTER_TAG, "endpoint is NULL", 0);
VERIFY_NON_NULL_RET(data, IP_ADAPTER_TAG, "data is NULL", 0);
- uint32_t sentLength = CAIPSendData(ipAddress, port, data, dataLength, false, true);
+ uint32_t sentLength = CAIPSendData(endpoint, data, dataLength, false);
OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Successfully sent %d of encrypted data!", sentLength);
}
#endif
-void CAIPPacketReceivedCB(const char *ipAddress, uint16_t port, const void *data,
- uint32_t dataLength, bool isSecured,
- const CARemoteId_t *identity)
+void CAIPPacketReceivedCB(const CAEndpoint_t *endpoint, const void *data,
+ uint32_t dataLength)
{
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
- VERIFY_NON_NULL_VOID(ipAddress, IP_ADAPTER_TAG, "ipAddress is NULL");
-
+ VERIFY_NON_NULL_VOID(endpoint, IP_ADAPTER_TAG, "ipAddress is NULL");
VERIFY_NON_NULL_VOID(data, IP_ADAPTER_TAG, "data is NULL");
- OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Address: %s, port:%d", ipAddress, port);
+ OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Address: %s, port:%d", endpoint->addr, endpoint->port);
- // CA is freeing this memory
- CARemoteEndpoint_t *endPoint = CAAdapterCreateRemoteEndpoint(CA_IPV4, ipAddress, NULL );
- if (!endPoint)
- {
- OIC_LOG(ERROR, IP_ADAPTER_TAG, "EndPoint creation failed!");
- return;
- }
- endPoint->addressInfo.IP.port = port;
- endPoint->isSecured = isSecured;
- if (identity)
- {
- endPoint->identity = *identity;
- }
-
-
- void *buf = OICCalloc(dataLength + 1, sizeof(char));
+ void *buf = OICCalloc(dataLength + 1, sizeof (char));
if (!buf)
{
OIC_LOG(ERROR, IP_ADAPTER_TAG, "Memory Allocation failed!");
- CAAdapterFreeRemoteEndpoint(endPoint);
return;
}
memcpy(buf, data, dataLength);
+
if (g_networkPacketCallback)
{
- g_networkPacketCallback(endPoint, buf, dataLength);
+ g_networkPacketCallback(endpoint, buf, dataLength);
}
else
{
OICFree(buf);
- CAAdapterFreeRemoteEndpoint(endPoint);
}
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
}
CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
- CANetworkPacketReceivedCallback networkPacketCallback,
- CANetworkChangeCallback netCallback, ca_thread_pool_t handle)
+ CANetworkPacketReceivedCallback networkPacketCallback,
+ CANetworkChangeCallback netCallback, ca_thread_pool_t handle)
{
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
VERIFY_NON_NULL(registerCallback, IP_ADAPTER_TAG, "registerCallback");
#ifdef __WITH_DTLS__
CAAdapterNetDtlsInit();
- CADTLSSetAdapterCallbacks(CAIPPacketReceivedCB, CAIPPacketSendCB, CA_IPV4);
+ CADTLSSetAdapterCallbacks(CAIPPacketReceivedCB, CAIPPacketSendCB, 0);
#endif
CAConnectivityHandler_t ipHandler;
ipHandler.readData = CAReadIPData;
ipHandler.stopAdapter = CAStopIP;
ipHandler.terminate = CATerminateIP;
- registerCallback(ipHandler, CA_IPV4);
+ registerCallback(ipHandler, CA_ADAPTER_IP);
if (CA_STATUS_OK != CAIPInitializeQueueHandles())
{
return CAStartIPListeningServer();
}
-int32_t CASendIPUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
- uint32_t dataLength)
+int32_t CASendIPUnicastData(const CAEndpoint_t *remoteEndpoint,
+ const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
}
// Create IPData to add to queue
- CAIPData *ipData = CACreateIPData(remoteEndpoint, data, dataLength);
+ CAIPData *ipData = CACreateIPData(remoteEndpoint, data, dataLength, false);
if (!ipData)
{
OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to create ipData!");
}
}
-int32_t CASendIPMulticastData(const void *data, uint32_t dataLength)
+int32_t CASendIPMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
}
// Create IPData to add to queue
- CAIPData *ipData = CACreateIPData(NULL, data, dataLength);
+ CAIPData *ipData = CACreateIPData(endpoint, data, dataLength, true);
if (!ipData)
{
OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to create ipData!");
}
}
-CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
{
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN");
}
#endif
- CALocalConnectivity_t *conInfo = (CALocalConnectivity_t *) OICCalloc(
- netInfoSize, sizeof(CALocalConnectivity_t));
+ CAEndpoint_t *conInfo = (CAEndpoint_t *)OICCalloc(netInfoSize, sizeof (CAEndpoint_t));
if (!conInfo)
{
OIC_LOG(ERROR, IP_ADAPTER_TAG, "Malloc Failed");
continue;
}
- conInfo[count].type = CA_IPV4;
- conInfo[count].isSecured = false;
- conInfo[count].addressInfo.IP.port = CAGetServerPortNum(netInfo->ipAddress, false);
- OICStrcpy(conInfo[count].addressInfo.IP.ipAddress,
- sizeof(conInfo[count].addressInfo.IP.ipAddress),
+ conInfo[count].adapter = CA_ADAPTER_IP;
+ conInfo[count].flags = 0;
+ conInfo[count].port = CAGetServerPortNum(netInfo->ipAddress, false);
+ OICStrcpy(conInfo[count].addr,
+ sizeof(conInfo[count].addr),
netInfo->ipAddress);
#ifdef __WITH_DTLS__
// copy secure unicast server information
{
count ++;
- conInfo[count].type = CA_IPV4;
- conInfo[count].isSecured = true;
- conInfo[count].addressInfo.IP.port = CAGetServerPortNum(netInfo->ipAddress, true);
- OICStrcpy(conInfo[count].addressInfo.IP.ipAddress,
- sizeof(conInfo[count].addressInfo.IP.ipAddress),
- netInfo->ipAddress);
+ conInfo[count].adapter = CA_ADAPTER_IP;
+ conInfo[count].flags = CA_SECURE;
+ conInfo[count].port = CAGetServerPortNum(netInfo->ipAddress, true);
+ OICStrcpy(conInfo[count].addr,
+ sizeof(conInfo[count].addr),
+ netInfo->ipAddress);
}
#endif
count ++;
CAStopIP();
#ifdef __WITH_DTLS__
- CADTLSSetAdapterCallbacks(NULL, NULL, CA_IPV4);
+ CADTLSSetAdapterCallbacks(NULL, NULL, 0);
#endif
CAIPSetPacketReceiveCallback(NULL);
return;
}
- //If remoteEndpoint is NULL, its Multicast, else its Unicast.
- if (ipData->remoteEndpoint)
+ if (ipData->isMulticast)
+ {
+ //Processing for sending multicast
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Multicast Data is called");
+ strncpy(ipData->remoteEndpoint->addr, CA_MULTICAST_IP, MAX_ADDR_STR_SIZE_CA);
+ ipData->remoteEndpoint->port = CA_MCAST_PORT;
+ CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, true);
+ }
+ else
{
//Processing for sending unicast
- char *address = ipData->remoteEndpoint->addressInfo.IP.ipAddress;
- uint16_t port = ipData->remoteEndpoint->addressInfo.IP.port;
-
#ifdef __WITH_DTLS__
- if (!ipData->remoteEndpoint->isSecured)
- {
- OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Unicast Data is called");
- CAIPSendData(address, port, ipData->data, ipData->dataLen, false,
- ipData->remoteEndpoint->isSecured);
- }
- else
+ if (ipData->remoteEndpoint->flags & CA_SECURE)
{
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt called!");
- CAResult_t result = CAAdapterNetDtlsEncrypt(address, port, ipData->data,
- ipData->dataLen, CA_IPV4);
-
+ CAResult_t result = CAAdapterNetDtlsEncrypt(ipData->remoteEndpoint,
+ ipData->data, ipData->dataLen);
if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, IP_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt failed!");
OIC_LOG_V(DEBUG, IP_ADAPTER_TAG,
"CAAdapterNetDtlsEncrypt returned with result[%d]", result);
}
+ else
+ {
+ OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Unicast Data is called");
+ CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, false);
+ }
#else
- CAIPSendData(address, port, ipData->data, ipData->dataLen, false,
- ipData->remoteEndpoint->isSecured);
+ CAIPSendData(ipData->remoteEndpoint, ipData->data, ipData->dataLen, false);
#endif
}
- else
- {
- //Processing for sending multicast
- OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Multicast Data is called");
- CAIPSendData(CA_MULTICAST_IP, CA_MCAST_PORT, ipData->data,
- ipData->dataLen, true, false);
- }
OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT");
}
-CAIPData *CACreateIPData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
- uint32_t dataLength)
+CAIPData *CACreateIPData(const CAEndpoint_t *remoteEndpoint, const void *data,
+ uint32_t dataLength, bool isMulticast)
{
VERIFY_NON_NULL_RET(data, IP_ADAPTER_TAG, "IPData is NULL", NULL);
return NULL;
}
- ipData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint);
+ ipData->remoteEndpoint = CAAdapterCloneEndpoint(remoteEndpoint);
ipData->data = (void *) OICMalloc(dataLength);
if (!ipData->data)
{
memcpy(ipData->data, data, dataLength);
ipData->dataLen = dataLength;
+ ipData->isMulticast = isMulticast;
+
return ipData;
}
{
VERIFY_NON_NULL_VOID(ipData, IP_ADAPTER_TAG, "ipData is NULL");
- CAAdapterFreeRemoteEndpoint(ipData->remoteEndpoint);
+ CAAdapterFreeEndpoint(ipData->remoteEndpoint);
OICFree(ipData->data);
OICFree(ipData);
}
void CAIPNotifyNetworkChange(const char *address, uint16_t port, CANetworkStatus_t status)
{
- CALocalConnectivity_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_IPV4, address);
+ CAEndpoint_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_IPV4, address);
if (!localEndpoint)
{
OIC_LOG(ERROR, TAG, "Out of memory!");
return;
}
- localEndpoint->addressInfo.IP.port = port;
+ localEndpoint->port = port;
if (NULL != g_networkChangeCallback)
{
g_networkChangeCallback(localEndpoint, status);
}
- CAAdapterFreeLocalEndpoint(localEndpoint);
+ CAAdapterFreeEndpoint(localEndpoint);
}
void CAIPConnectionStateCB(const char *ipAddr,
OIC_LOG_V(DEBUG, TAG, "data:%s", data);
/* CA is freeing this memory */
- CARemoteEndpoint_t *endPoint = CAAdapterCreateRemoteEndpoint(CA_IPV4, ipAddress, NULL);
+ CAEndpoint_t *endPoint = CAAdapterCreateEndpoint(CA_DEFAULT_FLAGS, CA_IPV4, ipAddress, port);
if (NULL == endPoint)
{
OIC_LOG(ERROR, TAG, "Out of memory!");
return;
}
- endPoint->addressInfo.IP.port = port;
if (g_networkPacketCallback)
{
g_networkPacketCallback(endPoint, data, dataLength);
}
- CAAdapterFreeRemoteEndpoint(endPoint);
+ CAAdapterFreeEndpoint(endPoint);
OIC_LOG(DEBUG, TAG, "OUT");
}
return CAStartIPListeningServer();
}
-int32_t CASendIPUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
- uint32_t dataLength)
+int32_t CASendIPUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, TAG, "IN");
- VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint", -1);
+ VERIFY_NON_NULL_RET(endpoint, TAG, "remoteEndpoint", -1);
VERIFY_NON_NULL_RET(data, TAG, "data", -1);
if (dataLength == 0)
{
return -1;
}
- CAIPSendData(remoteEndpoint->addressInfo.IP.ipAddress,
- remoteEndpoint->addressInfo.IP.port, data, dataLength, false);
+ CAIPSendData(endpoint->addr, endpoint->port, data, dataLength, false);
OIC_LOG(DEBUG, TAG, "OUT");
return dataLength;
}
-int32_t CASendIPMulticastData(const void *data, uint32_t dataLength)
+int32_t CASendIPMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, TAG, "IN");
return dataLength;
}
-CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
{
OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL(info, TAG, "info");
return CA_MEMORY_ALLOC_FAILED;
}
- (*info)->addressInfo.IP.port = g_unicastServerport;
+ (*info)->port = g_unicastServerport;
(*size) = 1;
OICFree(ipAddress);
#define IP_CLIENT_TAG "IP_CLIENT"
#define OC_MULTICAST_IP "224.0.1.187"
-static uint32_t CASendData(const char *remoteAddress, uint16_t port, const void *data,
+static uint32_t CASendData(const CAEndpoint_t *endpoint, const void *data,
uint32_t dataLength, int sockfd)
{
OIC_LOG(DEBUG, IP_CLIENT_TAG, "IN");
- VERIFY_NON_NULL_RET(remoteAddress, IP_CLIENT_TAG, "IP address is NULL", 0);
+ VERIFY_NON_NULL_RET(endpoint, IP_CLIENT_TAG, "IP address is NULL", 0);
VERIFY_NON_NULL_RET(data, IP_CLIENT_TAG, "data is NULL", 0);
if (0 == dataLength)
struct sockaddr_in destAddr = { 0 };
destAddr.sin_family = AF_INET;
- destAddr.sin_port = htons(port);
+ destAddr.sin_port = htons(endpoint->port);
- int ret = inet_pton(AF_INET, remoteAddress, &(destAddr.sin_addr));
+ int ret = inet_pton(AF_INET, endpoint->addr, &(destAddr.sin_addr));
if (1 != ret)
{
OIC_LOG(ERROR, IP_CLIENT_TAG, "inet_pton failed!");
}
OIC_LOG_V(INFO, IP_CLIENT_TAG, "Sending data is successful, sent bytes[%d] to ip[%s:%d]",
- sendDataLength, remoteAddress, port);
+ sendDataLength, endpoint->addr, endpoint->port);
OIC_LOG(DEBUG, IP_CLIENT_TAG, "OUT");
return sendDataLength;
}
-uint32_t CAIPSendData(const char *remoteAddress, uint16_t remotePort, const void *data,
- uint32_t dataLength, bool isMulticast, bool isSecured)
+uint32_t CAIPSendData(const CAEndpoint_t *endpoint, const void *data,
+ uint32_t dataLength, bool isMulticast)
{
u_arraylist_t *tempServerInfoList = u_arraylist_create();
if (!tempServerInfoList)
}
uint32_t len = 0;
- if (isMulticast || strcmp(remoteAddress, OC_MULTICAST_IP) == 0)
+ if (isMulticast || strcmp(endpoint->addr, OC_MULTICAST_IP) == 0)
{
uint32_t listIndex = 0;
uint32_t listLength = u_arraylist_length(tempServerInfoList);
{
CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(tempServerInfoList,
listIndex);
- if (!info || info->isMulticastServer || info->isSecured)
+ if (!info || info->isMulticastServer || (info->endpoint.flags & CA_SECURE))
{
continue;
}
}
OIC_LOG_V(DEBUG, IP_CLIENT_TAG,
- "CA IP Multicast SendData with src ip %s port %d sockFd %d",
- info->ipAddress, info->port, info->socketFd);
- len = CASendData(remoteAddress, remotePort, data, dataLength, info->socketFd);
+ "CA IP Multicast SendData with src ip %s port %d sockFd %d",
+ info->endpoint.addr, info->endpoint.port, info->socketFd);
+ len = CASendData(endpoint, data, dataLength, info->socketFd);
}
}
else
{
- int sockFd = CAGetSocketFdForUnicastServer(tempServerInfoList, remoteAddress, isSecured,
- isMulticast, CA_IPV4);
-
+ int sockFd = CAGetSocketFdForUnicastServer(tempServerInfoList, isMulticast, endpoint);
if (sockFd < 0)
{
OIC_LOG(ERROR, IP_CLIENT_TAG, "Invalid Socket Fd");
OIC_LOG_V(DEBUG, IP_CLIENT_TAG, "IP unicast SendData sockFd %d", sockFd);
- len = CASendData(remoteAddress, remotePort, data, dataLength, sockFd);
+ len = CASendData(endpoint, data, dataLength, sockFd);
}
CAClearServerInfoList(tempServerInfoList);
{
OIC_LOG_V(ERROR, IP_SERVER_TAG,
"data Received server information ip %s, port %d socket %d",
- info->ipAddress, info->port, sd);
+ info->endpoint.addr, info->endpoint.port, sd);
memset(recvBuffer, 0, sizeof(recvBuffer));
struct sockaddr_in srcSockAddress = { 0 };
}
OICFree(netMask);
- if (info->isSecured)
+ CAEndpoint_t ep;
+ strncpy(ep.addr, srcIPAddress, MAX_ADDR_STR_SIZE_CA);
+ ep.port = srcPort;
+ ep.flags = CA_IPV4;
+ ep.adapter = CA_ADAPTER_IP;
+
+ if (info->endpoint.flags & CA_SECURE)
{
#ifdef __WITH_DTLS__
- CAResult_t ret = CAAdapterNetDtlsDecrypt(srcIPAddress, srcPort,
- (uint8_t *)recvBuffer, recvLen,
- CA_IPV4);
+ ep.flags |= CA_SECURE;
+ (void)CAAdapterNetDtlsDecrypt(&ep, (uint8_t *)recvBuffer, recvLen);
OIC_LOG_V(DEBUG, IP_SERVER_TAG,
"CAAdapterNetDtlsDecrypt returns [%d]", ret);
#endif
if (g_adapterEthServerContext->packetReceivedCallback)
{
- g_adapterEthServerContext->packetReceivedCallback(srcIPAddress, srcPort,
- recvBuffer, recvLen,
- false, NULL);
+ g_adapterEthServerContext->packetReceivedCallback(&ep,
+ recvBuffer, recvLen);
}
ca_mutex_unlock(g_mutexAdapterServerContext);
OICStrcpy(info->subNetMask, sizeof(info->subNetMask), netMask);
OICFree(netMask);
}
- OICStrcpy(info->ipAddress, sizeof(info->ipAddress), localAddress);
- info->port = *port;
+ OICStrcpy(info->endpoint.addr, sizeof(info->endpoint.addr), localAddress);
+ info->endpoint.port = *port;
+ info->endpoint.flags = isSecured ? CA_SECURE : 0;
+ info->endpoint.adapter = CA_ADAPTER_IP;
info->socketFd = unicastServerFd;
- info->isSecured = isSecured;
info->isServerStarted = true;
info->isMulticastServer = false;
OICStrcpy(info->ifAddr, sizeof(info->ifAddr), localAddress);
OICFree(netMask);
}
- OICStrcpy(info->ipAddress, sizeof(info->ipAddress), multicastAddress);
- info->port = multicastPort;
+ OICStrcpy(info->endpoint.addr, sizeof(info->endpoint.addr), multicastAddress);
+ info->endpoint.port = multicastPort;
+ info->endpoint.flags = 0;
info->socketFd = mulicastServerFd;
- info->isSecured = false;
info->isServerStarted = true;
info->isMulticastServer = true;
OICStrcpy(info->ifAddr, sizeof(info->ifAddr), localAddress);
struct ip_mreq multicastMemberReq = { { 0 }, { 0 } };
multicastMemberReq.imr_interface.s_addr = inet_addr(info->ifAddr);
- inet_aton(info->ipAddress, &multicastMemberReq.imr_multiaddr);
+ inet_aton(info->endpoint.addr, &multicastMemberReq.imr_multiaddr);
if (-1 == setsockopt(info->socketFd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
(char *) &multicastMemberReq, sizeof(struct ip_mreq)))
{
return CA_STATUS_FAILED;
}
}
- else if (strncmp(interfaceAddress, info->ipAddress, strlen(info->ipAddress)) == 0)
+ else if (strncmp(interfaceAddress, info->endpoint.addr, strlen(info->endpoint.addr)) == 0)
{
if (u_arraylist_remove(g_serverInfoList, listIndex))
{
struct ip_mreq multicastMemberReq = { { 0 }, { 0 } };
multicastMemberReq.imr_interface.s_addr = inet_addr(info->ifAddr);
- inet_aton(info->ipAddress, &multicastMemberReq.imr_multiaddr);
+ inet_aton(info->endpoint.addr, &multicastMemberReq.imr_multiaddr);
if (-1 == setsockopt(info->socketFd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
(char *) &multicastMemberReq, sizeof(struct ip_mreq)))
{
}
};
-void request_handler(CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo);
-void response_handler(CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo);
-void error_handler(const CARemoteEndpoint_t *object, const CAErrorInfo_t* errorInfo);
-
+void request_handler(CAEndpoint_t* object, CARequestInfo_t* requestInfo);
+void response_handler(CAEndpoint_t* object, CAResponseInfo_t* responseInfo);
+void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
CAResult_t checkGetNetworkInfo();
CAResult_t checkSelectNetwork();
-
-
-void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
{
}
-void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
{
}
-void error_handler(const CARemoteEndpoint_t *object, const CAErrorInfo_t* errorInfo)
+void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo)
{
if(!object || !errorInfo)
{
}
static char* uri = NULL;
-static CARemoteEndpoint_t* tempRep = NULL;
+static CAEndpoint_t* tempRep = NULL;
static CARequestInfo_t requestInfo;
static CAInfo_t requestData;
static CAInfo_t responseData;
static const char SECURE_INFO_DATA[] =
"{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
- "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
+ "\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
static const char NORMAL_INFO_DATA[] =
"{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
- "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
+ "\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
#ifdef __WITH_DTLS__
{
uri = (char *) URI;
- EXPECT_EQ(CA_STATUS_OK, CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep));
+ EXPECT_EQ(CA_STATUS_OK, CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep));
if (tempRep != NULL)
{
- CADestroyRemoteEndpoint(tempRep);
+ CADestroyEndpoint(tempRep);
tempRep = NULL;
}
}
{
uri = (char *) URI;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
EXPECT_TRUE(tempRep != NULL);
if (tempRep != NULL)
{
- EXPECT_STRNE(NULL, tempRep->resourceUri);
- }
-
- if (tempRep != NULL)
- {
- CADestroyRemoteEndpoint(tempRep);
+ CADestroyEndpoint(tempRep);
tempRep = NULL;
}
}
{
uri = NULL;
- EXPECT_EQ(CA_STATUS_FAILED, CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep));
+ EXPECT_EQ(CA_STATUS_FAILED, CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep));
if (tempRep != NULL)
{
- CADestroyRemoteEndpoint(tempRep);
+ CADestroyEndpoint(tempRep);
tempRep = NULL;
}
}
-// check values of remoteEndpoint when uri is NULL
-TEST_F(CATests, CreateRemoteEndpointTestWithNullUri)
-{
- uri = NULL;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
-
- if (tempRep != NULL)
- {
- EXPECT_STREQ(NULL, tempRep->resourceUri);
-
- }
-
- if (tempRep != NULL)
- {
- CADestroyRemoteEndpoint(tempRep);
- tempRep = NULL;
- }
-}
-
-// CADestroyRemoteEndpoint TC
-// check destroyed remoteEndpoint
-TEST_F(CATests, DestroyRemoteEndpointTest)
-{
- uri = (char *) URI;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
-
- CADestroyRemoteEndpoint(tempRep);
- tempRep = NULL;
-
- char * check = (char *) "destroy success";
- EXPECT_STREQ(check, "destroy success");
-}
-
// CAGerateToken TC
// check return value
TEST_F(CATests, GenerateTokenTestGood)
EXPECT_STREQ(check, "destroy success");
}
-// CAFindResource TC
-// check return value
-TEST(FindResourceTest, DISABLED_TC_14_Positive_01)
-{
- uri = (char *) RESOURCE_URI;
-
- CAGenerateToken(&tempToken, tokenLength);
- EXPECT_EQ(CA_STATUS_OK, CAFindResource(uri, tempToken, tokenLength));
- CADestroyToken(tempToken);
-}
-
-// check return value when uri is NULL
-TEST_F(CATests, FindResourceTest)
-{
- uri = NULL;
- CAGenerateToken(&tempToken, tokenLength);
- EXPECT_EQ(CA_STATUS_INVALID_PARAM, CAFindResource(uri, tempToken, tokenLength));
- CADestroyToken(tempToken);
-}
-
// CASendRequest TC
// check return value
TEST(SendRequestTest, DISABLED_TC_16_Positive_01)
{
uri = (char *) URI;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
memset(&requestData, 0, sizeof(CAInfo_t));
CAGenerateToken(&tempToken, tokenLength);
int length = strlen(NORMAL_INFO_DATA) + strlen("a/light");
requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
-
if(!requestData.payload)
{
CADestroyToken(tempToken);
FAIL() << "requestData.payload allocation failed";
}
-
snprintf(requestData.payload, length, NORMAL_INFO_DATA, "a/light");
requestData.type = CA_MSG_NONCONFIRM;
free(requestData.payload);
- CADestroyRemoteEndpoint(tempRep);
+ CADestroyEndpoint(tempRep);
tempRep = NULL;
}
TEST_F(CATests, SendRequestTestWithNullURI)
{
uri = NULL;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
memset(&requestData, 0, sizeof(CAInfo_t));
CAGenerateToken(&tempToken, tokenLength);
int length = strlen(NORMAL_INFO_DATA) + strlen("a/light");
requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
-
if(!requestData.payload)
{
CADestroyToken(tempToken);
FAIL() << "requestData.payload allocation failed";
}
-
snprintf(requestData.payload, length, NORMAL_INFO_DATA, "a/light");
requestData.type = CA_MSG_NONCONFIRM;
if (tempRep != NULL)
{
- CADestroyRemoteEndpoint(tempRep);
+ CADestroyEndpoint(tempRep);
tempRep = NULL;
}
}
TEST_F(CATests, SendRequestTestWithNullAddr)
{
uri = (char *) URI;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendRequest(tempRep, NULL));
if (tempRep != NULL)
{
- CADestroyRemoteEndpoint(tempRep);
+ CADestroyEndpoint(tempRep);
tempRep = NULL;
}
}
TEST(SendResponseTest, DISABLED_TC_19_Positive_01)
{
uri = (char *) URI;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
memset(&responseData, 0, sizeof(CAInfo_t));
responseData.type = CA_MSG_NONCONFIRM;
EXPECT_EQ(CA_STATUS_OK, CASendResponse(tempRep, &responseInfo));
CADestroyToken(tempToken);
- CADestroyRemoteEndpoint(tempRep);
+ CADestroyEndpoint(tempRep);
tempRep = NULL;
}
TEST(SendResponseTest, DISABLED_TC_20_Negative_01)
{
uri = NULL;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
memset(&responseData, 0, sizeof(CAInfo_t));
responseData.type = CA_MSG_NONCONFIRM;
CADestroyToken(tempToken);
if (tempRep != NULL)
{
- CADestroyRemoteEndpoint(tempRep);
+ CADestroyEndpoint(tempRep);
tempRep = NULL;
}
}
TEST_F(CATests, SendResponseTest)
{
uri = (char *) URI;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendResponse(tempRep, NULL));
if (tempRep != NULL)
{
- CADestroyRemoteEndpoint(tempRep);
+ CADestroyEndpoint(tempRep);
tempRep = NULL;
}
}
TEST(SendNotificationTest, DISABLED_TC_22_Positive_01)
{
uri = (char *) URI;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
memset(&responseData, 0, sizeof(CAInfo_t));
responseData.type = CA_MSG_NONCONFIRM;
CADestroyToken(tempToken);
if (tempRep != NULL)
{
- CADestroyRemoteEndpoint(tempRep);
+ CADestroyEndpoint(tempRep);
tempRep = NULL;
}
}
TEST_F(CATests, SendNotificationTest)
{
uri = NULL;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
+ CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, uri, 0, &tempRep);
memset(&responseData, 0, sizeof(CAInfo_t));
responseData.type = CA_MSG_NONCONFIRM;
CADestroyToken(tempToken);
if (tempRep != NULL)
{
- CADestroyRemoteEndpoint(tempRep);
+ CADestroyEndpoint(tempRep);
tempRep = NULL;
}
}
-// CAAdvertiseResource TC
-// check return value
-TEST(AdvertiseResourceTest, DISABLED_TC_24_Positive_01)
-{
- uri = (char *) RESOURCE_URI;
- int optionNum = 2;
-
- CAHeaderOption_t* headerOpt;
- headerOpt = (CAHeaderOption_t *) calloc(1, optionNum * sizeof(CAHeaderOption_t));
-
- if(!headerOpt)
- {
- FAIL() <<"Allocation for headerOpt failed";
- }
-
- char* tmpOptionData1 = (char *) "Hello";
- size_t tmpOptionDataLen = (strlen(tmpOptionData1) < CA_MAX_HEADER_OPTION_DATA_LENGTH) ?
- strlen(tmpOptionData1) : CA_MAX_HEADER_OPTION_DATA_LENGTH - 1;
- headerOpt[0].optionID = 3000;
- memcpy(headerOpt[0].optionData, tmpOptionData1, tmpOptionDataLen);
- headerOpt[0].optionLength = (uint16_t) tmpOptionDataLen;
-
- char* tmpOptionData2 = (char *) "World";
- tmpOptionDataLen = (strlen(tmpOptionData2) < CA_MAX_HEADER_OPTION_DATA_LENGTH) ?
- strlen(tmpOptionData2) : CA_MAX_HEADER_OPTION_DATA_LENGTH - 1;
- headerOpt[1].optionID = 3001;
- memcpy(headerOpt[1].optionData, tmpOptionData2, tmpOptionDataLen);
- headerOpt[1].optionLength = (uint16_t) tmpOptionDataLen;
-
- CAGenerateToken(&tempToken, tokenLength);
-
- EXPECT_EQ(CA_STATUS_OK, CAAdvertiseResource(uri, tempToken, tokenLength,
- headerOpt, (uint8_t )optionNum));
-
- CADestroyToken(tempToken);
-
- free(headerOpt);
-}
-
-// check return value when uri is NULL
-TEST_F(CATests, AdvertiseResourceTest)
-{
- uri = NULL;
- int optionNum = 2;
-
- CAHeaderOption_t* headerOpt;
- headerOpt = (CAHeaderOption_t *) calloc(1, optionNum * sizeof(CAHeaderOption_t));
-
- if(!headerOpt)
- {
- FAIL() << "Allocation for headerOpt failed";
- }
-
- char* tmpOptionData1 = (char *) "Hello";
- size_t tmpOptionDataLen = (strlen(tmpOptionData1) < CA_MAX_HEADER_OPTION_DATA_LENGTH) ?
- strlen(tmpOptionData1) : CA_MAX_HEADER_OPTION_DATA_LENGTH - 1;
- headerOpt[0].optionID = 3000;
- memcpy(headerOpt[0].optionData, tmpOptionData1, tmpOptionDataLen);
- headerOpt[0].optionLength = (uint16_t) tmpOptionDataLen;
-
- char* tmpOptionData2 = (char *) "World";
- tmpOptionDataLen = (strlen(tmpOptionData2) < CA_MAX_HEADER_OPTION_DATA_LENGTH) ?
- strlen(tmpOptionData2) : CA_MAX_HEADER_OPTION_DATA_LENGTH - 1;
- headerOpt[1].optionID = 3001;
- memcpy(headerOpt[1].optionData, tmpOptionData2, tmpOptionDataLen);
- headerOpt[1].optionLength = (uint16_t) tmpOptionDataLen;
-
- CAGenerateToken(&tempToken, tokenLength);
-
- EXPECT_EQ(CA_STATUS_INVALID_PARAM, CAAdvertiseResource(uri, tempToken, tokenLength,
- headerOpt, (uint8_t )optionNum));
-
- CADestroyToken(tempToken);
-
- free(headerOpt);
-}
-
// CASelectNewwork TC
// check return value
TEST_F(CATests, SelectNetworkTestGood)
CAResult_t checkSelectNetwork()
{
- CAResult_t res = CASelectNetwork(CA_IPV4);
+ CAResult_t res = CASelectNetwork(CA_ADAPTER_IP);
if (CA_STATUS_OK == res)
{
- EXPECT_EQ(CA_STATUS_OK, CAUnSelectNetwork(CA_IPV4));
+ EXPECT_EQ(CA_STATUS_OK, CAUnSelectNetwork(CA_ADAPTER_IP));
return CA_STATUS_OK;
}
if (CA_NOT_SUPPORTED == res)
{
- EXPECT_EQ(CA_STATUS_FAILED, CAUnSelectNetwork(CA_IPV4));
+ EXPECT_EQ(CA_STATUS_FAILED, CAUnSelectNetwork(CA_ADAPTER_IP));
return CA_STATUS_OK;
}
EXPECT_EQ(CA_STATUS_OK, CAHandleRequestResponse());
}
-// CASendRequestToAll TC
-// check return value
-TEST(SendRequestToAllTest, DISABLED_TC_31_Positive_01)
-{
- CASelectNetwork(CA_IPV4);
-
- uri = (char *) RESOURCE_URI;
- CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep);
- CAGroupEndpoint_t *group = NULL;
- group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
- if(!group)
- {
- FAIL() << "Allocation for group failed";
- }
-
- group->transportType = tempRep->transportType;
- group->resourceUri = tempRep->resourceUri;
-
- memset(&requestData, 0, sizeof(CAInfo_t));
- CAGenerateToken(&tempToken, tokenLength);
- requestData.token = tempToken;
- requestData.tokenLength = tokenLength;
-
- requestData.payload = (char *) "Temp Json Payload";
- requestData.type = CA_MSG_NONCONFIRM;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
- requestInfo.method = CA_GET;
- requestInfo.info = requestData;
-
- EXPECT_EQ(CA_STATUS_OK, CASendRequestToAll(group, &requestInfo));
-
- CADestroyToken(tempToken);
-
- CADestroyRemoteEndpoint(tempRep);
- tempRep = NULL;
-
- free(group);
-}
-
-// check return value when group->resourceUri is NULL
-TEST(SendRequestToAllTest, DISABLED_TC_32_Negative_01)
-{
- uri = (char *) RESOURCE_URI;
- CAGroupEndpoint_t *group = NULL;
-
- memset(&requestData, 0, sizeof(CAInfo_t));
- CAGenerateToken(&tempToken, tokenLength);
- requestData.token = tempToken;
- requestData.tokenLength = tokenLength;
-
- requestData.payload = (char *) "Temp Json Payload";
- requestData.type = CA_MSG_NONCONFIRM;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
- requestInfo.method = CA_GET;
- requestInfo.info = requestData;
-
- EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendRequestToAll(group, &requestInfo));
-
- CADestroyToken(tempToken);
-}
-
// CAGetNetworkInformation TC
// check return value
TEST_F (CATests, GetNetworkInformationTestGood)
CAResult_t checkGetNetworkInfo()
{
- CALocalConnectivity_t *tempInfo = NULL;
+ CAEndpoint_t *tempInfo = NULL;
uint32_t tempSize = 0;
CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
} SPResult;
-/**
- * Connectivity types.
- */
-typedef enum
-{
- SP_IPV4 = (1 << 0),
- SP_IPV6 = (1 << 1),
- SP_CONN_EDR = (1 << 2),
- SP_CONN_LE = (1 << 3)
-} SPConnectivityType;
-
typedef struct SPTargetDeviceInfo SPTargetDeviceInfo_t;
typedef struct SPDevInfo SPDevInfo_t;
*/
struct SPTargetDeviceInfo
{
- char ip[DEV_ADDR_SIZE_MAX]; /**< IP address in IPv4 dot-decimal notation. **/
- int port; /**< Remote endpoint port. **/
- SPConnectivityType connType; /**< Connectivity type. **/
- OicSecPstat_t *pstat; /**< Pointer to target's pstat resource. **/
- OicSecDoxm_t *doxm; /**< Pointer to target's doxm resource. **/
- SPTargetDeviceInfo_t *next; /**< Next pointer. **/
+ OCDevAddr endpoint; /**< target address **/
+ OicSecPstat_t *pstat; /**< Pointer to target's pstat resource. **/
+ OicSecDoxm_t *doxm; /**< Pointer to target's doxm resource. **/
+ SPTargetDeviceInfo_t *next; /**< Next pointer. **/
};
/**
*/
struct SPDevInfo
{
- OicUuid_t deviceId; /**< Device ID. **/
- char ip[DEV_ADDR_SIZE_MAX]; /**< IP address in IPv4 dot-decimal notation. **/
- int port; /**< Remote endpoint port. **/
- SPConnectivityType connType; /**< Connectivity type. **/
- SPDevInfo_t *next; /**< Next pointer. **/
+ OCDevAddr endpoint; /**< target address **/
+ OicUuid_t deviceId; /**< Device ID. **/
+ SPDevInfo_t *next; /**< Next pointer. **/
};
-
/**
* The function is responsible for discovery of device is current subnet. It will list
* all the device in subnet which are not yet owned. Please call OCInit with OC_CLIENT_SERVER as
#define COAPS_QUERY "coaps://%s:%d%s"
#define CA_SECURE_PORT 5684
-void (*handler)(const CARemoteEndpoint_t *, const CAResponseInfo_t *);
+void (*handler)(const CAEndpoint_t *, const CAResponseInfo_t *);
/**
* CA token to keep track of response.
}
/**
- * Convert SP network types to CA network types,
- *
- * @param[in] connType connection type.
- * @return CA connectivity type corresponding to SP connectivity type.
- */
-static CATransportType_t getConnectivity(SPConnectivityType connType)
-{
- switch (connType)
- {
- case SP_IPV4:
- {
- return CA_IPV4;
- }
- case SP_IPV6:
- {
- return CA_IPV6;
- }
- case SP_CONN_EDR:
- {
- return CA_EDR;
- }
- case SP_CONN_LE:
- {
- return CA_LE;
- }
- default:
- {
- return CA_IPV4;
- }
- }
- return CA_IPV4;
-}
-
-/**
- * Convert CA network types to SP network types,
- *
- * @param[in] connType connection type.
- * @return SPConnectitivty type corresponding to CATransportType_t.
- */
-static SPConnectivityType getConnectivitySP(CATransportType_t connType)
-{
- switch (connType)
- {
- case CA_IPV4:
- {
- return SP_IPV4;
- }
- case CA_IPV6:
- {
- return SP_IPV6;
- }
- case CA_EDR:
- {
- return SP_CONN_EDR;
- }
- case CA_LE:
- {
- return SP_CONN_LE;
- }
- default:
- {
- return SP_IPV4;
- }
- }
- return SP_IPV4;
-}
-
-/**
* Function to delete memory allocated to linked list.
*
*/
/**
* Function to send request to resource server.
- * @param[in] uri Request URI.
+ * @param[in] method method to be used for sending rquest.
+ * @param[in] endpoint endpoint address
+ * @param[in] secure use secure connection
+ * @param[in] resourceUri resourceUri token.
* @param[in] payload Payload to be sent with data. NULL is case message
* doesn't have payload.
* @param[in] payloadLen Size of data to be sent.
- * @param[in] token CA token.
- * @param[in] method method to be used for sending rquest.
- * @param[in] conntype Connectivity type.
* @return CA_STATUS_OK on success, otherwise error code.
*/
-static CAResult_t sendCARequest(CAURI_t uri, char *payload, int payloadLen,
- CAToken_t token, CAMethod_t method, SPConnectivityType conntype)
+static CAResult_t sendCARequest(CAMethod_t method,
+ const OCDevAddr *devAddr,
+ OCTransportFlags secure,
+ const char *resourceUri,
+ char *payload, int payloadLen)
{
- CARemoteEndpoint_t *endpoint = NULL;
- CATransportType_t caConnType = getConnectivity(conntype);
- if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, caConnType, &endpoint) || !endpoint)
+ if (CA_STATUS_OK != CAGenerateToken(&gToken, CA_MAX_TOKEN_LEN))
+ {
+ OC_LOG(ERROR, TAG, "Error while generating token");
+ return CA_MEMORY_ALLOC_FAILED;
+ }
+
+ CAEndpoint_t *endpoint = NULL;
+ if (CA_STATUS_OK != CACreateEndpoint((CATransportFlags_t)secure,
+ devAddr->adapter, devAddr->addr,
+ devAddr->port, &endpoint))
{
OC_LOG(ERROR, TAG, "Failed to create remote endpoint");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return CA_STATUS_FAILED;
}
CAMessageType_t msgType = CA_MSG_CONFIRM;
CAInfo_t requestData = { 0 };
- requestData.token = token;
+ requestData.token = gToken;
requestData.tokenLength = CA_MAX_TOKEN_LEN;
if (payload && '\0' != (*(payload + payloadLen)))
{
OC_LOG(ERROR, TAG, "Payload not properly terminated.");
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return CA_STATUS_INVALID_PARAM;
}
requestData.payload = payload;
CARequestInfo_t requestInfo = { 0 };
requestInfo.method = method;
requestInfo.info = requestData;
+ requestInfo.isMulticast = false;
CAResult_t caResult = CA_STATUS_OK;
caResult = CASendRequest(endpoint, &requestInfo);
if (CA_STATUS_OK != caResult)
{
OC_LOG(ERROR, TAG, "Send Request Error !!");
}
- CADestroyRemoteEndpoint(endpoint);
+ CADestroyEndpoint(endpoint);
return caResult;
}
*
* @param[in] ip IP of target device.
* @param[in] port port of remote server.
- * @param[in] connType connectivity type of endpoint.
+ * @param[in] adapter adapter type of endpoint.
* @param[in] doxm pointer to doxm instance.
* @return SP_RESULT_SUCCESS for success and errorcode otherwise.
*/
-static SPResult addDevice(const char *ip, int port, SPConnectivityType connType, OicSecDoxm_t *doxm)
+static SPResult addDevice(const char *ip, int port, OCTransportAdapter adapter, OicSecDoxm_t *doxm)
{
if (NULL == ip || 0 >= port)
{
return SP_RESULT_INVALID_PARAM;
}
- SPTargetDeviceInfo_t *ptr = (SPTargetDeviceInfo_t *) OICCalloc(1, sizeof(SPTargetDeviceInfo_t));
+ SPTargetDeviceInfo_t *ptr = (SPTargetDeviceInfo_t *)OICCalloc(1, sizeof (SPTargetDeviceInfo_t));
if (NULL == ptr)
{
OC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
return SP_RESULT_MEM_ALLOCATION_FAIL;
}
- SPStringCopy(ptr->ip, ip, sizeof(ptr->ip));
- ptr->port = port;
- ptr->connType = connType;
+ SPStringCopy(ptr->endpoint.addr, ip, MAX_ADDR_STR_SIZE);
+ ptr->endpoint.port = port;
+ ptr->endpoint.adapter = adapter;
ptr->doxm = doxm;
* @param[in] object Remote endpoint object
* @param[in] requestInfo Datastructure containing request information.
*/
-static void ProvisionDiscoveryHandler(const CARemoteEndpoint_t *object,
+static void ProvisionDiscoveryHandler(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo)
{
if ((gStateManager & SP_DISCOVERY_STARTED) && gToken)
OC_LOG(DEBUG, TAG, "Successfully converted pstat json to bin.");
OICFree(pTempPayload);
- SPConnectivityType connType = getConnectivitySP(object->transportType);
- SPResult res = addDevice(object->addressInfo.IP.ipAddress, object->addressInfo.IP.port,
- connType, ptrDoxm);
+ SPResult res = addDevice(object->addr, object->port, object->adapter, ptrDoxm);
if (SP_RESULT_SUCCESS != res)
{
OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
* @param[in] object Remote endpoint object
* @param[in] requestInfo Datastructure containing request information.
*/
-static void OwnerShipTransferModeHandler(const CARemoteEndpoint_t *object,
+static void OwnerShipTransferModeHandler(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo)
{
if ((gStateManager & SP_UP_OWN_TR_METH_STARTED) && gToken)
* @param[in] object Remote endpoint object
* @param[in] requestInfo Datastructure containing request information.
*/
-static void ListMethodsHandler(const CARemoteEndpoint_t *object,
+static void ListMethodsHandler(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo)
{
if ((gStateManager & SP_LIST_METHODS_STARTED) && gToken)
* @param[in] object Remote endpoint object
* @param[in] requestInfo Datastructure containing request information.
*/
-static void OperationModeUpdateHandler(const CARemoteEndpoint_t *object,
+static void OperationModeUpdateHandler(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo)
{
if ((gStateManager & SP_UPDATE_OP_MODE_STARTED) && gToken)
* @param[in] object Remote endpoint object
* @param[in] requestInfo Datastructure containing request information.
*/
-static void OwnerShipUpdateHandler(const CARemoteEndpoint_t *object,
+static void OwnerShipUpdateHandler(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo)
{
if ((gStateManager & SP_UPDATE_OWNER_STARTED) && gToken)
* @param[in] object Remote endpoint object
* @param[in] requestInfo Datastructure containing request information.
*/
-static void ACLProvisioningHandler(const CARemoteEndpoint_t *object,
+static void ACLProvisioningHandler(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo)
{
if ((gStateManager & SP_PROV_ACL_STARTED) && gToken)
* @param[in] object Remote endpoint object
* @param[in] requestInfo Datastructure containing request information.
*/
-static void FinalizeProvisioningHandler(const CARemoteEndpoint_t *object,
+static void FinalizeProvisioningHandler(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo)
{
if ((gStateManager & SP_UP_HASH_STARTED) && gToken)
* @param[in] object Remote endpoint object
* @param[in] requestInfo Datastructure containing request information.
*/
-static void CredProvisioningHandler(const CARemoteEndpoint_t *object,
+static void CredProvisioningHandler(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo)
{
if ((gStateManager & SP_PROV_CRED_STARTED) && gToken)
* @param[in] object Remote endpoint object
* @param[in] responseInfo Datastructure containing response information.
*/
-static void SPResponseHandler(const CARemoteEndpoint_t *object,
+static void SPResponseHandler(const CAEndpoint_t *object,
const CAResponseInfo_t *responseInfo)
{
if ((NULL != responseInfo) && (NULL != responseInfo->info.token))
* @param[in] object Remote endpoint object
* @param[in] errorInfo Datastructure containing error information.
*/
-static void SPErrorHandler(const CARemoteEndpoint_t *object,
+static void SPErrorHandler(const CAEndpoint_t *object,
const CAErrorInfo_t *errorInfo)
{
OC_LOG(INFO, TAG, "Error Handler.");
* @param[in] object Remote endpoint object
* @param[in] requestInfo Datastructure containing request information.
*/
-static void SPRequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+static void SPRequestHandler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
{
OC_LOG(INFO, TAG, "Request Handler.");
}
OC_LOG(ERROR, TAG, "Error while generating token.");
return SP_RESULT_INTERNAL_ERROR;
}
- res = CAFindResource(DOXM_OWNED_FALSE_MULTICAST_QUERY, gToken, CA_MAX_TOKEN_LEN);
+
+ CAEndpoint_t endpoint = { CA_DEFAULT_FLAGS };
+
+ CAMessageType_t msgType = CA_MSG_NONCONFIRM;
+ CAInfo_t requestData = { 0 };
+ requestData.token = gToken;
+ requestData.tokenLength = CA_MAX_TOKEN_LEN;
+ requestData.payload = NULL;
+ requestData.type = msgType;
+ requestData.resourceUri = DOXM_OWNED_FALSE_MULTICAST_QUERY;
+ CARequestInfo_t requestInfo = { 0 };
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
+ requestInfo.isMulticast = true;
+ res = CASendRequest(&endpoint, &requestInfo);
+
handler = &ProvisionDiscoveryHandler;
gStateManager |= SP_DISCOVERY_STARTED;
if (CA_STATUS_OK != res)
SPTargetDeviceInfo_t *deviceInfo, OicSecOxm_t selectedMethod)
{
SPResult res = SP_RESULT_INTERNAL_ERROR;
- char uri[CA_MAX_URI_LENGTH] = {0};
- size_t uriLen = sizeof(uri);
- snprintf(uri, uriLen - 1, COAP_QUERY, deviceInfo->ip,
- deviceInfo->port, OIC_RSRC_DOXM_URI);
- uri[uriLen - 1] = '\0';
deviceInfo->doxm->oxmSel = selectedMethod;
char *payload = BinToDoxmJSON(deviceInfo->doxm);
OC_LOG_V(DEBUG, TAG, "Payload: %s", payload);
int payloadLen = strlen(payload);
- CAMethod_t method = CA_PUT;
- if (CA_STATUS_OK != CAGenerateToken(&gToken, CA_MAX_TOKEN_LEN))
- {
- OC_LOG(ERROR, TAG, "Error while generating token");
- OICFree(payload);
- return SP_RESULT_INTERNAL_ERROR;
- }
handler = &OwnerShipTransferModeHandler;
gStateManager |= SP_UP_OWN_TR_METH_STARTED;
- CAResult_t result = sendCARequest(uri, payload, payloadLen, gToken, method,
- deviceInfo->connType);
+ CAResult_t result = sendCARequest(CA_PUT,
+ &deviceInfo->endpoint,
+ OC_DEFAULT_FLAGS,
+ OIC_RSRC_DOXM_URI,
+ payload, payloadLen);
OICFree(payload);
if (CA_STATUS_OK != result)
{
* @return SP_SUCCESS on success
*/
static SPResult getProvisioningStatusResource(unsigned short timeout,
- SPTargetDeviceInfo_t *deviceInfo)
+ SPTargetDeviceInfo_t *deviceInfo)
{
- char uri[CA_MAX_URI_LENGTH] = {0};
- size_t uriLen = sizeof(uri);
- snprintf(uri, uriLen - 1, COAP_QUERY, deviceInfo->ip,
- deviceInfo->port, OIC_RSRC_PSTAT_URI);
- uri[uriLen - 1] = '\0';
- CAMethod_t method = CA_GET;
- if (CA_STATUS_OK != CAGenerateToken(&gToken, CA_MAX_TOKEN_LEN))
- {
- OC_LOG(ERROR, TAG, "Error while generating token");
- return SP_RESULT_INTERNAL_ERROR;
- }
handler = &ListMethodsHandler;
gStateManager |= SP_LIST_METHODS_STARTED;
- CAResult_t result = sendCARequest(uri, NULL, 0, gToken, method, deviceInfo->connType);
+
+ CAResult_t result = sendCARequest(CA_GET,
+ &deviceInfo->endpoint,
+ OC_DEFAULT_FLAGS,
+ OIC_RSRC_PSTAT_URI,
+ NULL, 0);
if (CA_STATUS_OK != result)
{
OC_LOG(ERROR, TAG, "Failure while sending request.");
* @param[in] deviceInfo Device Info.
* @return SP_SUCCESS on success
*/
-static SPResult updateOperationMode(unsigned short timeout, SPTargetDeviceInfo_t *deviceInfo,
+static SPResult updateOperationMode(unsigned short timeout,
+ SPTargetDeviceInfo_t *deviceInfo,
OicSecDpom_t selectedOperationMode)
{
SPResult res = SP_RESULT_INTERNAL_ERROR;
- char uri[CA_MAX_URI_LENGTH] = {0};
- size_t uriLen = sizeof(uri);
- snprintf(uri, uriLen - 1, COAP_QUERY, deviceInfo->ip,
- deviceInfo->port , OIC_RSRC_PSTAT_URI);
- uri[uriLen - 1] = '\0';
-
-
deviceInfo->pstat->om = selectedOperationMode;
char *payloadBuffer = BinToPstatJSON(deviceInfo->pstat);
}
size_t payloadLen = strlen(payloadBuffer);
-
- CAMethod_t method = CA_PUT;
- if (CA_STATUS_OK != CAGenerateToken(&gToken, CA_MAX_TOKEN_LEN))
- {
- OC_LOG(ERROR, TAG, "Error while generating token");
- if (payloadBuffer)
- {
- OICFree(payloadBuffer);
- }
- return SP_RESULT_INTERNAL_ERROR;
- }
handler = &OperationModeUpdateHandler;
gStateManager |= SP_UPDATE_OP_MODE_STARTED;
- CAResult_t result = sendCARequest(uri, payloadBuffer, payloadLen, gToken, method,
- deviceInfo->connType);
+
+ CAResult_t result = sendCARequest(CA_PUT,
+ &deviceInfo->endpoint,
+ OC_DEFAULT_FLAGS,
+ OIC_RSRC_PSTAT_URI,
+ payloadBuffer, payloadLen);
if (CA_STATUS_OK != result)
{
OC_LOG(ERROR, TAG, "Error while sending request.");
}
OC_LOG(INFO, TAG, "Anonymous cipher suite Enabled.");
- CAAddress_t address = {};
- strncpy(address.IP.ipAddress, deviceInfo->ip, DEV_ADDR_SIZE_MAX);
- address.IP.ipAddress[DEV_ADDR_SIZE_MAX - 1] = '\0';
- address.IP.port = CA_SECURE_PORT;
-
- caresult = CAInitiateHandshake(&address, deviceInfo->connType);
+ caresult = CAInitiateHandshake((CAEndpoint_t *)&deviceInfo->endpoint);
if (CA_STATUS_OK != caresult)
{
OC_LOG_V(ERROR, TAG, "DTLS handshake failure.");
static SPResult sendOwnershipInfo(unsigned short timeout,
SPTargetDeviceInfo_t *selectedDeviceInfo)
{
- char uri[CA_MAX_URI_LENGTH] = {0};
- size_t uriLen = sizeof(uri);
- snprintf(uri, uriLen - 1, COAPS_QUERY, selectedDeviceInfo->ip,
- CA_SECURE_PORT, OIC_RSRC_DOXM_URI);
- uri[uriLen - 1] = '\0';
-
OicUuid_t provTooldeviceID = {};
+
if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
{
OC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
}
memcpy(selectedDeviceInfo->doxm->owner.id, provTooldeviceID.id , UUID_LENGTH);
-
selectedDeviceInfo->doxm->owned = true;
char *payloadBuffer = BinToDoxmJSON(selectedDeviceInfo->doxm);
}
int payloadLen = strlen(payloadBuffer);
- CAMethod_t method = CA_PUT;
- if (CA_STATUS_OK != CAGenerateToken(&gToken, CA_MAX_TOKEN_LEN))
- {
- OC_LOG(ERROR, TAG, "Error while generating token");
- OICFree(payloadBuffer);
- return SP_RESULT_INTERNAL_ERROR;
-
- }
handler = &OwnerShipUpdateHandler;
gStateManager |= SP_UPDATE_OWNER_STARTED;
- CAResult_t result = sendCARequest(uri, payloadBuffer, payloadLen, gToken, method,
- selectedDeviceInfo->connType);
+ CAResult_t result = sendCARequest(CA_PUT,
+ &selectedDeviceInfo->endpoint,
+ OC_SECURE,
+ OIC_RSRC_DOXM_URI,
+ payloadBuffer, payloadLen);
if (CA_STATUS_OK != result)
{
OC_LOG(ERROR, TAG, "Error while sending request.");
static SPResult saveOwnerPSK(SPTargetDeviceInfo_t *selectedDeviceInfo)
{
SPResult result = SP_RESULT_INTERNAL_ERROR;
- CAAddress_t address = {};
- strncpy(address.IP.ipAddress, selectedDeviceInfo->ip, DEV_ADDR_SIZE_MAX);
- address.IP.ipAddress[DEV_ADDR_SIZE_MAX - 1] = '\0';
- address.IP.port = CA_SECURE_PORT;
+
+ CAEndpoint_t endpoint = {0};
+ strncpy(endpoint.addr, selectedDeviceInfo->endpoint.addr, MAX_ADDR_STR_SIZE_CA);
+ endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
+ endpoint.port = CA_SECURE_PORT;
OicUuid_t provTooldeviceID = {};
if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {};
//Generating OwnerPSK
- CAResult_t pskRet = CAGenerateOwnerPSK(&address, selectedDeviceInfo->connType,
- (uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS), provTooldeviceID.id,
+ CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
+ (uint8_t *)OXM_JUST_WORKS, strlen(OXM_JUST_WORKS), provTooldeviceID.id,
sizeof(provTooldeviceID.id), selectedDeviceInfo->doxm->deviceID.id,
sizeof(selectedDeviceInfo->doxm->deviceID.id), ownerPSK,
OWNER_PSK_LENGTH_128);
return SP_RESULT_MEM_ALLOCATION_FAIL;
}
- char uri[CA_MAX_URI_LENGTH] = {0};
- size_t uriLen = sizeof(uri);
- snprintf(uri, uriLen - 1, COAPS_QUERY, deviceInfo->ip,
- CA_SECURE_PORT, OIC_RSRC_CRED_URI);
- uri[uriLen - 1] = '\0';
-
int payloadLen = strlen(credJson);
- CAMethod_t method = CA_POST;
- if (CA_STATUS_OK != CAGenerateToken(&gToken, CA_MAX_TOKEN_LEN))
- {
- OC_LOG(ERROR, TAG, "Error while generating token");
- return SP_RESULT_INTERNAL_ERROR;
- }
handler = &CredProvisioningHandler;
gStateManager |= SP_PROV_CRED_STARTED;
- CAResult_t result = sendCARequest(uri, credJson, payloadLen, gToken, method,
- deviceInfo->connType);
+
+ CAResult_t result = sendCARequest(CA_POST,
+ &deviceInfo->endpoint,
+ OC_SECURE,
+ OIC_RSRC_CRED_URI,
+ credJson, payloadLen);
OICFree(credJson);
if (CA_STATUS_OK != result)
{
return SP_RESULT_MEM_ALLOCATION_FAIL;
}
- char uri[CA_MAX_URI_LENGTH] = {0};
- size_t uriLen = sizeof(uri);
- snprintf(uri, uriLen - 1, COAPS_QUERY, selectedDeviceInfo->ip,
- CA_SECURE_PORT, OIC_RSRC_ACL_URI);
- uri[uriLen - 1] = '\0';
-
int payloadLen = strlen(aclString);
- CAMethod_t method = CA_POST;
- if (CA_STATUS_OK != CAGenerateToken(&gToken, CA_MAX_TOKEN_LEN))
- {
- OC_LOG(ERROR, TAG, "Error while generating token");
- OICFree(aclString);
- return SP_RESULT_INTERNAL_ERROR;
-
- }
handler = &ACLProvisioningHandler;
gStateManager |= SP_PROV_ACL_STARTED;
- CAResult_t result = sendCARequest(uri, aclString, payloadLen, gToken, method,
- selectedDeviceInfo->connType);
+ CAResult_t result = sendCARequest(CA_POST,
+ &selectedDeviceInfo->endpoint,
+ OC_SECURE,
+ OIC_RSRC_DOXM_URI,
+ aclString, payloadLen);
OICFree(aclString);
if (CA_STATUS_OK != result)
{
OC_LOG(ERROR, TAG, "Target device Info is NULL.");
return SP_RESULT_INVALID_PARAM;
}
- char uri[CA_MAX_URI_LENGTH] = {0};
- size_t uriLen = sizeof(uri);
- snprintf(uri, uriLen - 1, COAPS_QUERY, selectedDeviceInfo->ip,
- CA_SECURE_PORT, OIC_RSRC_PSTAT_URI);
- uri[uriLen - 1] = '\0';
uint16_t aclHash = 0; // value for beachhead version.
selectedDeviceInfo->pstat->commitHash = aclHash;
}
int payloadLen = strlen(payloadBuffer);
- CAMethod_t method = CA_PUT;
- if (CA_STATUS_OK != CAGenerateToken(&gToken, CA_MAX_TOKEN_LEN))
- {
- OC_LOG(ERROR, TAG, "Error while generating token");
- OICFree(payloadBuffer);
- return SP_RESULT_INTERNAL_ERROR;
- }
handler = &FinalizeProvisioningHandler;
gStateManager |= SP_UP_HASH_STARTED;
- CAResult_t result = sendCARequest(uri, payloadBuffer, payloadLen, gToken, method,
- selectedDeviceInfo->connType);
+
+ CAResult_t result = sendCARequest(CA_PUT,
+ &selectedDeviceInfo->endpoint,
+ OC_SECURE,
+ OIC_RSRC_PSTAT_URI,
+ payloadBuffer, payloadLen);
OICFree(payloadBuffer);
if (CA_STATUS_OK != result)
{
return SP_RESULT_TIMEOUT;
}
- CAAddress_t address = {};
- strncpy(address.IP.ipAddress, selectedDeviceInfo->ip, DEV_ADDR_SIZE_MAX);
- address.IP.ipAddress[DEV_ADDR_SIZE_MAX - 1] = '\0';
- address.IP.port = CA_SECURE_PORT;
+ CAEndpoint_t endpoint = {0};
+ strncpy(endpoint.addr, selectedDeviceInfo->endpoint.addr, MAX_ADDR_STR_SIZE_CA);
+ endpoint.addr[DEV_ADDR_SIZE_MAX - 1] = '\0';
+ endpoint.port = CA_SECURE_PORT;
- result = CACloseDtlsSession(&address, selectedDeviceInfo->connType);
+ result = CACloseDtlsSession(&endpoint);
if (CA_STATUS_OK != result)
{
OC_LOG_V(ERROR, TAG, "DTLS handshake failure.");
#ifdef __WITH_DTLS__
CAResult_t pskRet;
- OCServerRequest * request = (OCServerRequest *)ehRequest->requestHandle;
+ OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {};
//Generating OwnerPSK
OC_LOG (INFO, TAG, PCF("Doxm EntityHandle generating OwnerPSK"));
- pskRet = CAGenerateOwnerPSK(&request->addressInfo,
- request->connectivityType,
+ pskRet = CAGenerateOwnerPSK((CAEndpoint_t *)&request->devAddr,
(uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS),
newDoxm->owner.id, sizeof(newDoxm->owner.id),
gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
* @param requestInfo [IN] Information for the request.
* @return NONE
*/
-void SRMRequestHandler(const CARemoteEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
+void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
{
OC_LOG(INFO, TAG, PCF("Received request from remote device"));
memcpy(subjectId.id, endPoint->identity.id, sizeof(subjectId.id));
//Check the URI has the query and skip it before checking the permission
- char *uri = strstr(endPoint->resourceUri, "?");
+ char *uri = strstr(requestInfo->info.resourceUri, "?");
int position = 0;
if (uri)
{
- position = uri - endPoint->resourceUri;
+ position = uri - requestInfo->info.resourceUri;
}
if (position > MAX_URI_LENGTH)
{
if (position > 0)
{
char newUri[MAX_URI_LENGTH + 1];
- strncpy(newUri, endPoint->resourceUri, (position));
+ strncpy(newUri, requestInfo->info.resourceUri, (position));
newUri[position] = '\0';
//Skip query and pass the newUri.
- response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
- GetPermissionFromCAMethod_t(requestInfo->method));
-
+ response = CheckPermission(&g_policyEngineContext, &subjectId,
+ newUri,
+ GetPermissionFromCAMethod_t(requestInfo->method));
}
else
{
- //Pass endPoint->resourceUri if there is no query info.
- response = CheckPermission(&g_policyEngineContext, &subjectId, endPoint->resourceUri,
- GetPermissionFromCAMethod_t(requestInfo->method));
+ //Pass resourceUri if there is no query info.
+ response = CheckPermission(&g_policyEngineContext, &subjectId,
+ requestInfo->info.resourceUri,
+ GetPermissionFromCAMethod_t(requestInfo->method));
}
if (IsAccessGranted(response) && gRequestHandler)
{
* @param responseInfo [IN] Response information from the endpoint.
* @return NONE
*/
-void SRMResponseHandler(const CARemoteEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
+void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
{
OC_LOG(INFO, TAG, PCF("Received response from remote device"));
if (gResponseHandler)
* @param errorInfo [IN] Error information from the endpoint.
* @return NONE
*/
-void SRMErrorHandler(const CARemoteEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
+void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
{
OC_LOG(INFO, TAG, PCF("Received error from remote device"));
if (gErrorHandler)
using namespace std;
// Helper Methods
-void UTRequestHandler(const CARemoteEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
+void UTRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
{
EXPECT_TRUE(true) << "UTRequestHandler\n";
}
-void UTResponseHandler(const CARemoteEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
+void UTResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
{
EXPECT_TRUE(true) << "UTResponseHandler\n";
}
-void UTErrorHandler(const CARemoteEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
+void UTErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
{
EXPECT_TRUE(true) << "UTErrorHandler\n";
}
OCMethod method;
// 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
+ // The canonical form of the request uri associated with the call back
char * requestUri;
+ // Remote address complete
+ OCDevAddr * devAddr;
// Struct to hold TTL info for presence
#ifdef WITH_PRESENCE
OCPresence * presence;
AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
CAToken_t token, uint8_t tokenLength,
OCDoHandle *handle, OCMethod method,
- char * requestUri, char * resourceTypeName, OCConnectivityType conType, uint32_t ttl);
+ OCDevAddr *devAddr, char * requestUri,
+ char * resourceTypeName, uint32_t ttl);
/** @ingroup ocstack
*
uint8_t tokenLength;
// Resource handle
OCResource *resource;
- //TODO bundle it in Endpoint structure(address, uri, type, secured)
- /** Remote Endpoint address **/
- CAAddress_t addressInfo;
- /** Connectivity of the endpoint**/
- CATransportType_t connectivityType;
+ /** Remote Endpoint **/
+ OCDevAddr devAddr;
// Quality of service of the request
OCQualityOfService qos;
// number of times the server failed to reach the observer
* @param tokenLength Length of token.
* @param resHandle Resource handle.
* @param qos Quality of service of observation.
- * @param addressInfo Address of observer.
- * @param connectivityType Connection type.
+ * @param observer address
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
OCStackResult AddObserver (const char *resUri,
uint8_t tokenLength,
OCResource *resHandle,
OCQualityOfService qos,
- const CAAddress_t *addressInfo,
- CATransportType_t connectivityType);
+ const OCDevAddr *devAddr);
/**
* Delete observer with specified token from list of observers.
const char *filterValue,
char * out,
uint16_t *remaining,
- CATransportType_t connType);
+ CATransportAdapter_t adapter);
/**
* A helper function that Maps an @ref OCEntityHandlerResult type to an
OCStackResult observeResult;
uint8_t numResponses;
OCEHResponseHandler ehResponseHandler;
- /** Remote Endpoint address **/
- CAAddress_t addressInfo;
- /** Connectivity of the endpoint**/
- CATransportType_t connectivityType;
+ /** Remote endpoint address **/
+ OCDevAddr devAddr;
// token for the request
CAToken_t requestToken;
// token length the request
// The ID of CoAP pdu //Kept in
uint16_t coapID; //CoAP
uint8_t delayedResNeeded;
- uint8_t secured;
//////////////////////////////////////////////////////////
// An array of the received vendor specific header options
uint8_t numRcvdVendorSpecificHeaderOptions;
* @param tokenLength - request token length
* @param resourceUrl - URL of resource
* @param reqTotalSize - total size of the request
- * @param addressInfo - CA Address
- * @param connectivityType - connection type
+ * @param devAddr - OCDevAddr
*
* @return
* OCStackResult
*/
OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
- uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method,
+ uint8_t delayedResNeeded, uint8_t notificationFlag, OCMethod method,
uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
OCQualityOfService qos, char * query,
OCHeaderOption * rcvdVendorSpecificHeaderOptions,
char * reqJSONPayload, CAToken_t requestToken,
uint8_t tokenLength,
char * resourceUrl, size_t reqTotalSize,
- CAAddress_t *addressInfo, CATransportType_t connectivityType);
+ const OCDevAddr *devAddr);
/**
* Form the OCEntityHandlerRequest struct that is passed to a resource's entity handler
uint8_t numRcvdVendorSpecificHeaderOptions;
OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
- /** Remote Endpoint address **/
- //////////////////////////////////////////////////////////
- // TODO: bundle this up as endpoint
- CAAddress_t addressInfo;
- /** Connectivity of the endpoint**/
- CATransportType_t connectivityType;
+ /** Remote endpoint address **/
+ OCDevAddr devAddr;
//token for the observe request
CAToken_t requestToken;
// The ID of CoAP pdu
uint16_t coapID;
uint8_t delayedResNeeded;
- uint8_t secured;
- //////////////////////////////////////////////////////////
uint8_t reqMorePacket;
uint32_t reqPacketNum;
uint16_t reqPacketSize;
OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest);
-OCStackResult SendDirectStackResponse(const CARemoteEndpoint_t* endPoint, const uint16_t coapID,
+OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
const CAResponseResult_t responseResult, const CAMessageType_t type,
const uint8_t numOptions, const CAHeaderOption_t *options,
CAToken_t token, uint8_t tokenLength);
OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
+void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out);
+
+void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out);
+
#ifdef __cplusplus
}
#endif // __cplusplus
/**
* Initialize the OC Stack. Must be called prior to starting the stack.
*
+ * @param mode
+ * Host device is client, server, or client-server.
+ * @param serverFlags
+ * Default server transport flags.
+ * @param clientFlags
+ * Default client transport flags.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags);
+
+/**
+ * Initialize the OC Stack. Must be called prior to starting the stack.
+ *
* @param ipAddr
* IP Address of host device. Deprecated parameter.
* @param port
* should not be free'd by the consumer. A NULL handle is permitted
* in the event where the caller has no use for the return value.
* @param method @ref OCMethod to perform on the resource.
- * @param requiredUri URI of the resource to interact with.
- * @param referenceUri URI of the reference resource.
+ * @param requiredUri URI of the resource to interact with. (Address prefix
+ * is deprecated in favor of destination.)
+ * @param destination Complete description of destination.
* @param request JSON encoded request.
- * @param conType @ref OCConnectivityType type of connectivity indicating the
- * interface. Example: ::OC_WIFI, ::OC_ETHERNET, ::OC_ALL.
+ * @param connectivityType Modifier flags when destination is not given.
* @param qos Quality of service. Note that if this API is called on a uri with
* the well-known multicast IP address, the qos will be forced to
* ::OC_LOW_QOS
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
- const char *referenceUri, const char *request, OCConnectivityType conType,
- OCQualityOfService qos, OCCallbackData *cbData,
- OCHeaderOption * options, uint8_t numOptions);
-
+OCStackResult OCDoResource(OCDoHandle *handle,
+ OCMethod method,
+ const char *requestUri,
+ const OCDevAddr *destination,
+ const char *request,
+ OCConnectivityType connectivityType,
+ OCQualityOfService qos,
+ OCCallbackData *cbData,
+ OCHeaderOption *options,
+ uint8_t numOptions);
/**
* Cancel a request associated with a specific @ref OCDoResource invocation.
*
*/
OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
-
-//Utility methods
-
-/**
- * This method is used to retrieved the IPv4 address from OCDev address
- * data structure.
- *
- * @param ipAddr OCDevAddr address.
- * @param a first byte of IPv4 address.
- * @param b second byte of IPv4 address.
- * @param c third byte of IPv4 address.
- * @param d fourth byte of IPv4 address.
- * @return ::OC_STACK_OK on success, some other value upon failure.
- */
-int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
- uint8_t *c, uint8_t *d );
-
-/**
- * This method is used to retrieve the port number from OCDev address
- * data structure.
- *
- * @param ipAddr OCDevAddr address.
- * @param port Port number.
- * @return ::OC_STACK_OK on success, some other value upon failure.
- */
-int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port);
-
#ifdef __cplusplus
}
#endif // __cplusplus
#endif /* OCSTACK_H_ */
-
-
//-----------------------------------------------------------------------------
// Defines
//-----------------------------------------------------------------------------
-
-//TODO: May want to refactor this in upcoming sprints.
-//Don't want to expose to application layer that lower level stack is using CoAP.
-
-/// Authority + URI string to prefix well known queries
-#define OC_WELL_KNOWN_QUERY "224.0.1.187:5683/oic/res"
+#define OC_WELL_KNOWN_QUERY "/oic/res"
#define OC_MULTICAST_DISCOVERY_URI "/oic/res"
-#define OC_EXPLICIT_DEVICE_DISCOVERY_URI "224.0.1.187:5683/oic/d?rt=core.led"
-/// Multicast address and port string to prefix multicast queries
-#define OC_MULTICAST_PREFIX "224.0.1.187:5683"
-/// IP Multicast address to use for multicast requests
-#define OC_MULTICAST_IP "224.0.1.187"
-/// IP Multicast port to use for multicast requests
-#define OC_MULTICAST_PORT 5683
#ifdef WITH_PRESENCE
#define OC_DEFAULT_PRESENCE_TTL_SECONDS (60)
#define OC_DATA_MODEL_VERSION "sec.0.95"
//*******************
+// These provide backward compatibility - their use is deprecated
+#ifndef GOING_AWAY
+#define OC_MULTICAST_PREFIX "224.0.1.187:5683"
+#define OC_MULTICAST_IP "224.0.1.187:5683"
+#define OC_MULTICAST_PORT 5683
+#endif // GOING_AWAY
//-----------------------------------------------------------------------------
// Typedefs
//-----------------------------------------------------------------------------
+#define MAX_ADDR_STR_SIZE (40)
+#define MAX_IDENTITY_SIZE (32)
+
+/*
+ * These enums (OCTransportAdapter and OCTransportFlags) must
+ * be kept synchronized with OCConnectivityType (below) as well as
+ * CATransportAdapter and CATransportFlags (in CACommon.h).
+ */
+
+typedef enum
+{
+ OC_DEFAULT_ADAPTER = 0,
+
+ // value zero indicates discovery
+ OC_ADAPTER_IP = (1 << 0), // IPv4 and IPv6, including 6LoWPAN
+ OC_ADAPTER_GATT_BTLE = (1 << 1), // GATT over Bluetooth LE
+ OC_ADAPTER_RFCOMM_BTEDR = (1 << 2), // RFCOMM over Bluetooth EDR
+} OCTransportAdapter;
+
+// enum layout assumes some targets have 16-bit integer (e.g., Arduino)
+typedef enum
+{
+ OC_DEFAULT_FLAGS = 0,
+
+ // Insecure transport is the default (subject to change)
+ OC_FLAG_SECURE = (1 << 4), // secure the transport path
+
+ // IPv4 & IPv6 autoselection is the default
+ OC_IP_USE_V6 = (1 << 5), // IP adapter only
+ OC_IP_USE_V4 = (1 << 6), // IP adapter only
+
+ // Link-Local multicast is the default multicast scope for IPv6.
+ // These are placed here to correspond to the IPv6 multicast address bits.
+ OC_SCOPE_INTERFACE = 0x1, // IPv6 Interface-Local scope (loopback)
+ OC_SCOPE_LINK = 0x2, // IPv6 Link-Local scope (default)
+ OC_SCOPE_REALM = 0x3, // IPv6 Realm-Local scope
+ OC_SCOPE_ADMIN = 0x4, // IPv6 Admin-Local scope
+ OC_SCOPE_SITE = 0x5, // IPv6 Site-Local scope
+ OC_SCOPE_ORG = 0x8, // IPv6 Organization-Local scope
+ OC_SCOPE_GLOBAL = 0xE, // IPv6 Global scope
+} OCTransportFlags;
+
+#define OC_MASK_SCOPE (0x000F)
+#define OC_MASK_MODS (0x0FF0)
+
+/*
+ * endpoint identity
+ */
+typedef struct
+{
+ uint16_t id_length;
+ unsigned char id[MAX_IDENTITY_SIZE];
+} OCIdentity;
+
/**
* Data structure to encapsulate IPv4/IPv6/Contiki/lwIP device addresses.
+ *
+ * OCDevAddr must be the same as CAEndpoint (in CACommon.h).
*/
-typedef struct OCDevAddr
+typedef struct
{
- uint32_t size; ///< length of the address stored in addr field.
- uint8_t addr[DEV_ADDR_SIZE_MAX]; ///< device address.
+ OCTransportAdapter adapter; // adapter type
+ OCTransportFlags flags; // transport modifiers
+ char addr[MAX_ADDR_STR_SIZE]; // address for all adapters
+ uint32_t interface; // usually zero for default interface
+ uint16_t port; // for IP
+ OCIdentity identity; // secure node identity
} OCDevAddr;
+/*
+ * OCConnectivityType includes elements of both OCTransportAdapter
+ * and OCTransportFlags. It is defined conditionally because the
+ * smaller definition limits expandability on 32/64 bit integer machines,
+ * and the larger definition won't fit into an enum on 16-bit integer
+ * machines like Arduino.
+ *
+ * This structure must directly correspond to OCTransportAdapter
+ * and OCTransportFlags.
+ */
+typedef enum
+{
+ CT_DEFAULT = 0, // use when defaults are ok
+
+ #if defined (__UINT32_MAX__) && (__UINT32_MAX__ == 65535) // 16-bit int
+ CT_ADAPTER_IP = (1 << 10), // IPv4 and IPv6, including 6LoWPAN
+ CT_ADAPTER_GATT_BTLE = (1 << 11), // GATT over Bluetooth LE
+ CT_ADAPTER_RFCOMM_BTEDR = (1 << 12), // RFCOMM over Bluetooth EDR
+ #define CT_ADAPTER_SHIFT 10
+ #define CT_MASK_FLAGS 0x03FF
+ #define CT_MASK_ADAPTER 0xFC00
+ #else // assume 32-bit int
+ CT_ADAPTER_IP = (1 << 16), // IPv4 and IPv6, including 6LoWPAN
+ CT_ADAPTER_GATT_BTLE = (1 << 17), // GATT over Bluetooth LE
+ CT_ADAPTER_RFCOMM_BTEDR = (1 << 18), // RFCOMM over Bluetooth EDR
+ #define CT_ADAPTER_SHIFT 16
+ #define CT_MASK_FLAGS 0xFFFF
+ #define CT_MASK_ADAPTER 0xFFFF0000
+ #endif
+
+ // Insecure transport is the default (subject to change)
+ CT_FLAG_SECURE = (1 << 4), // secure the transport path
+
+ // IPv4 & IPv6 autoselection is the default
+ CT_IP_USE_V6 = (1 << 5), // IP adapter only
+ CT_IP_USE_V4 = (1 << 6), // IP adapter only
+
+ // Link-Local multicast is the default multicast scope for IPv6.
+ // These are placed here to correspond to the IPv6 address bits.
+ CT_SCOPE_INTERFACE = 0x1, // IPv6 Interface-Local scope (loopback)
+ CT_SCOPE_LINK = 0x2, // IPv6 Link-Local scope (default)
+ CT_SCOPE_REALM = 0x3, // IPv6 Realm-Local scope
+ CT_SCOPE_ADMIN = 0x4, // IPv6 Admin-Local scope
+ CT_SCOPE_SITE = 0x5, // IPv6 Site-Local scope
+ CT_SCOPE_ORG = 0x8, // IPv6 Organization-Local scope
+ CT_SCOPE_GLOBAL = 0xE, // IPv6 Global scope
+} OCConnectivityType;
+
/**
* OC Virtual resources supported by every OC device.
*/
} OCVirtualResources;
/**
- * Standard RESTful HTTP Methods.
+ * OCDoResource methods
*/
typedef enum
{
- OC_REST_NOMETHOD = 0,
- OC_REST_GET = (1 << 0), ///< Read
- OC_REST_PUT = (1 << 1), ///< Write
- OC_REST_POST = (1 << 2), ///< Update
- OC_REST_DELETE = (1 << 3), ///< Delete
+ OC_REST_NOMETHOD = 0,
+ OC_REST_GET = (1 << 0), ///< Read
+ OC_REST_PUT = (1 << 1), ///< Write
+ OC_REST_POST = (1 << 2), ///< Update
+ OC_REST_DELETE = (1 << 3), ///< Delete
/// Register observe request for most up date notifications ONLY.
- OC_REST_OBSERVE = (1 << 4),
+ OC_REST_OBSERVE = (1 << 4),
/// Register observe request for all notifications, including stale notifications.
- OC_REST_OBSERVE_ALL = (1 << 5),
+ OC_REST_OBSERVE_ALL = (1 << 5),
/// Deregister observation, intended for internal use
OC_REST_CANCEL_OBSERVE = (1 << 6),
#ifdef WITH_PRESENCE
/// Subscribe for all presence notifications of a particular resource.
- OC_REST_PRESENCE = (1 << 7)
+ OC_REST_PRESENCE = (1 << 7),
#endif
+ /// Allows OCDoResource caller to do discovery.
+ OC_REST_DISCOVER = (1 << 8)
} OCMethod;
/**
} OCTransportProtocolID;
/**
- * Adaptor types.
- */
-typedef enum
-{
- OC_IPV4 = 0,
- OC_IPV6,
- OC_EDR,
- OC_LE,
- OC_ALL // Multicast message: send over all the interfaces.
-} OCConnectivityType;
-
-/**
* Declares Stack Results & Errors.
*/
typedef enum
typedef struct
{
/// Address of remote server
- OCDevAddr * addr;
- /// Indicates adaptor type on which the response was received
- OCConnectivityType connType;
+ OCDevAddr devAddr;
+ OCDevAddr *addr; // backward compatibility (points to devAddr)
+ OCConnectivityType connType; // backward compatibility
/// the is the result of our stack, OCStackResult should contain coap/other error codes;
OCStackResult result;
/// If associated with observe, this will represent the sequence of notifications from server.
uint32_t sequenceNumber;
+ /// resourceURI
+ const char * resourceUri;
/// resJSONPayload is retrieved from the payload of the received request PDU
const char * resJSONPayload;
/// An array of the received vendor specific header options
static int TEST_CASE = 0;
static const char * UNICAST_DEVICE_DISCOVERY_QUERY = "coap://%s:6298/oic/d";
-static const char * UNICAST_PLATFORM_DISCOVERY_QUERY = "coap://%s:6298/oic/p";
-
static const char * MULTICAST_DEVICE_DISCOVERY_QUERY = "/oic/d";
+static const char * UNICAST_PLATFORM_DISCOVERY_QUERY = "coap://%s:6298/oic/p";
static const char * MULTICAST_PLATFORM_DISCOVERY_QUERY = "/oic/p";
static const char * UNICAST_RESOURCE_DISCOVERY_QUERY = "coap://%s:6298/oic/res";
static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
//The following variable determines the interface protocol (IPv4, IPv6, etc)
//to be used for sending unicast messages. Default set to IPv4.
-static OCConnectivityType OC_CONNTYPE = OC_IPV4;
-
+static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
static std::string putPayload = "{\"oic\":[{\"rep\":{\"power\":15,\"state\":true}}]}";
static std::string coapServerIP = "255.255.255.255";
static std::string coapServerPort = "5683";
OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
OCClientResponse * clientResponse)
{
- uint8_t remoteIpAddr[4];
- uint16_t remotePortNu;
-
if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
{
OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
{
OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
- remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
std::string connectionType = getConnectivityType (clientResponse->connType);
OC_LOG_V(INFO, TAG, "Discovered on %s", connectionType.c_str());
OC_LOG_V(INFO, TAG,
- "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
- clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
- remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+ "Device =============> Discovered %s @ %s:%d",
+ clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
parseClientResponse(clientResponse);
}
else
{
- ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
(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),
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
(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),
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
(qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
}
if (ret != OC_STACK_OK)
TEST_CASE = atoi(optarg);
break;
case 'c':
- // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
- // OC_CONNTYPE = OCConnectivityType(atoi(optarg));
- OC_CONNTYPE = OC_IPV4;
- OC_LOG(INFO, TAG, "IPv6 not currently supported, using IPv4.");
+ OC_CONNTYPE = CT_ADAPTER_IP;
break;
default:
PrintUsage();
{
return "";
}
- uint8_t a, b, c, d = 0;
- if (0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d))
- {
- return "";
- }
- char ipaddr[16] = {'\0'};
- // ostringstream not working correctly here, hence snprintf
- snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
- return std::string (ipaddr);
+ return std::string(clientResponse->devAddr.addr);
}
std::string getPortTBServer(OCClientResponse * clientResponse)
{
return "";
}
- uint16_t p = 0;
- if (0 != OCDevAddrToPort(clientResponse->addr, &p))
- {
- return "";
- }
std::ostringstream ss;
- ss << p;
+ ss << clientResponse->devAddr.port;
return ss.str();
}
std::string getConnectivityType (OCConnectivityType connType)
{
- switch (connType)
+ switch (connType & CT_MASK_ADAPTER)
{
- case OC_IPV4:
- return "IPv4";
-
- case OC_IPV6:
- return "IPv6";
+ case CT_ADAPTER_IP:
+ return "IP";
- case OC_LE:
- return "BLE";
+ case CT_ADAPTER_GATT_BTLE:
+ return "GATT";
- case OC_EDR:
- return "BT";
+ case CT_ADAPTER_RFCOMM_BTEDR:
+ return "RFCOMM";
default:
return "Incorrect connectivity";
static const char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oic/res";
static std::string putPayload = "{\"oic\":[{\"rep\":{\"power\":15,\"state\":true}}]}";
-//The following variable determines the interface protocol (IPv4, IPv6, etc)
-//to be used for sending unicast messages. Default set to IPv4.
-static OCConnectivityType OC_CONNTYPE = OC_IPV4;
+//The following variable determines the interface protocol (IP, etc)
+//to be used for sending unicast messages. Default set to IP.
+static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
int gQuitFlag = 0;
OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle,
OCClientResponse * clientResponse)
{
- uint8_t remoteIpAddr[4];
- uint16_t remotePortNu;
-
if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
{
OC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
if(clientResponse)
{
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
- remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
- OC_LOG_V(INFO, TAG,"PUT Response: %s \nFrom %d.%d.%d.%d:%d\n",
- clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
- remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+ OC_LOG_V(INFO, TAG,"PUT Response: %s \nFrom %s:%d\n",
+ clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
}
else
{
OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle,
OCClientResponse *clientResponse)
{
- uint8_t remoteIpAddr[4];
- uint16_t remotePortNu;
-
if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
{
OC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
if(clientResponse)
{
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
- remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
- OC_LOG_V(INFO, TAG,"POST Response: %s \nFrom %d.%d.%d.%d:%d\n",
- clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
- remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+ OC_LOG_V(INFO, TAG,"POST Response: %s \nFrom %s:%d\n",
+ clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
}
else
{
OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle,
OCClientResponse * clientResponse)
{
- uint8_t remoteIpAddr[4];
- uint16_t remotePortNu;
-
if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
{
OC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
if (clientResponse)
{
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, remoteIpAddr + 1,
- remoteIpAddr + 2, remoteIpAddr + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
- OC_LOG_V(INFO, TAG,"Get Response: %s \nFrom %d.%d.%d.%d:%d\n",
- clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
- remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+ OC_LOG_V(INFO, TAG,"Get Response: %s \nFrom %s:%d\n",
+ clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
if (clientResponse->rcvdVendorSpecificHeaderOptions
&& clientResponse->numRcvdVendorSpecificHeaderOptions)
OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
OCClientResponse * clientResponse)
{
- uint8_t remoteIpAddr[4];
- uint16_t remotePortNu;
if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
{
OC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
if (clientResponse)
{
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
- remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
OC_LOG_V(INFO, TAG,
- "Device Discovered %s \n @ %d.%d.%d.%d:%d\n",
- clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
- remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+ "Device Discovered %s \n @ %s:%d\n",
+ clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
collectUniqueResource(clientResponse);
}
}
else
{
- ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
OC_LOW_QOS, &cbData, NULL, 0);
}
return ret;
}
-
-
-const char * getIPAddr(const OCClientResponse * clientResponse)
+const char *getIPAddr(const OCClientResponse *clientResponse)
{
- uint8_t a, b, c, d;
- if(!clientResponse || 0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d))
+ if (!clientResponse)
{
return "";
}
- char * ipaddr = NULL;
- if((ipaddr = (char *) OICCalloc(1, MAX_IP_ADDR_ST_SZ)))
+ const OCDevAddr *devAddr = &clientResponse->devAddr;
+ char *ipaddr = (char *) OICCalloc(1, strlen(devAddr->addr));
+ if (ipaddr)
{
- snprintf(ipaddr, MAX_IP_ADDR_ST_SZ, "%d.%d.%d.%d", a,b,c,d);
+ snprintf(ipaddr, MAX_IP_ADDR_ST_SZ, "%s", devAddr->addr);
}
else
{
return ipaddr;
}
-const char * getPort(const OCClientResponse * clientResponse)
+const char *getPort(const OCClientResponse *clientResponse)
{
- uint16_t p = 0;
- if(!clientResponse || 0 != OCDevAddrToPort(clientResponse->addr, &p) )
+ if(!clientResponse)
{
return "";
}
- char * port = NULL;
- if((port = (char *) OICCalloc(1, MAX_PORT_ST_SZ)))
+ char *port = NULL;
+ if((port = (char *)OICCalloc(1, MAX_PORT_ST_SZ)))
{
- snprintf(port, MAX_PORT_ST_SZ, "%d", p);
+ snprintf(port, MAX_PORT_ST_SZ, "%d", clientResponse->devAddr.port);
}
else
{
printf("uri = %s\n", iter->uri);
printf("ip = %s\n", iter->ip);
printf("port = %s\n", iter->port);
- switch (iter->connType)
+ switch (iter->connType & CT_MASK_ADAPTER)
{
- case OC_IPV4:
- printf("connType = %s\n","IPv4");
- break;
- case OC_IPV6:
- // TODO: Allow IPv6 when support is added
- printf("IPv6 not currently supported, default to IPv4\n");
- //printf("connType = %s\n","IPv6");
+ case CT_ADAPTER_IP:
printf("connType = %s\n","IPv4");
break;
- case OC_LE:
+ case OC_ADAPTER_GATT_BTLE:
printf("connType = %s\n","BLE");
break;
- case OC_EDR:
+ case OC_ADAPTER_RFCOMM_BTEDR:
printf("connType = %s\n","BT");
break;
- case OC_ALL:
default:
printf("connType = %s\n","Invalid connType");
break;
TEST_CASE = atoi(optarg);
break;
case 'c':
- // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
- // OC_CONNTYPE = OCConnectivityType(atoi(optarg));
- OC_CONNTYPE = OC_IPV4;
- OC_LOG(INFO, TAG, "Using default IPv4, IPv6 not currently supported.");
+ OC_CONNTYPE = CT_ADAPTER_IP;
break;
default:
PrintUsage();
static std::string putPayload = "{\"state\":\"off\",\"power\":\"0\"}";
-//The following variable determines the interface protocol (IPv4, IPv6, etc)
-//to be used for sending unicast messages. Default set to IPv4.
-static OCConnectivityType OC_CONNTYPE = OC_IPV4;
+//The following variable determines the interface protocol (IP, etc)
+//to be used for sending unicast messages. Default set to IP.
+static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
// The handle for the observe registration
OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
OCClientResponse * clientResponse)
{
- uint8_t remoteIpAddr[4];
- uint16_t remotePortNu;
-
OC_LOG(INFO, TAG,
"Entering discoveryReqCB (Application Layer CB)");
OC_LOG_V(INFO, TAG, "StackResult: %s",
OC_LOG_V(INFO, TAG, "Callback Context recvd successfully");
}
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
- remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
OC_LOG_V(INFO, TAG,
"Device =============> Discovered %s @ %d.%d.%d.%d:%d",
- clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
- remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+ clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
if(TEST == TEST_UNKNOWN_RESOURCE_GET_DEFAULT || TEST == TEST_UNKNOWN_RESOURCE_GET_BATCH ||\
TEST == TEST_UNKNOWN_RESOURCE_GET_LINK_LIST)
OCStackResult ret;
OCCallbackData cbData;
std::ostringstream getQuery;
- getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" <<
- getPortTBServer(clientResponse) << "/SomeUnknownResource";
+ getQuery << "coap://" << clientResponse->devAddr.addr << ":" <<
+ clientResponse->devAddr.port << "/SomeUnknownResource";
cbData.cb = getReqCB;
cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
cbData.cd = NULL;
OCCallbackData cbData;
OCDoHandle handle;
std::ostringstream obsReg;
- obsReg << "coap://" << getIPAddrTBServer(clientResponse) << ":" <<
- getPortTBServer(clientResponse) <<
+ obsReg << "coap://" << clientResponse->devAddr.addr << ":" <<
+ clientResponse->devAddr.addr <<
getQueryStrForGetPut(clientResponse->resJSONPayload);
cbData.cb = getReqCB;
cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
OCCallbackData cbData;
//* Make a PUT query*/
std::ostringstream getQuery;
- getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" <<
- getPortTBServer(clientResponse) <<
+ getQuery << "coap://" << clientResponse->devAddr.addr << ":" <<
+ clientResponse->devAddr.port <<
"/a/room" << queryInterface[TEST].text;
cbData.cb = putReqCB;
cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
OCStackResult ret;
OCCallbackData cbData;
- uint8_t remoteIpAddr[4];
- uint16_t remotePortNu;
-
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
- remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
//* Make a GET query*/
std::ostringstream getQuery;
- getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" <<
- getPortTBServer(clientResponse) <<
+ getQuery << "coap://" << clientResponse->devAddr.addr << ":" <<
+ clientResponse->devAddr.port <<
"/a/room" << queryInterface[TEST].text;
std::cout << "Get Query: " << getQuery.str() << std::endl;
cbData.cb = discoveryReqCB;
cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
cbData.cd = NULL;
- ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_ALL,
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
OC_LOW_QOS,
&cbData, NULL, 0);
if (ret != OC_STACK_OK)
TEST = atoi(optarg);
break;
case 'c':
- // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
- // OC_CONNTYPE = OCConnectivityType(atoi(optarg));
- OC_CONNTYPE = OC_IPV4;
+ OC_CONNTYPE = CT_ADAPTER_IP;
break;
default:
PrintUsage();
return 0;
}
-std::string getIPAddrTBServer(OCClientResponse * clientResponse)
-{
- if (!clientResponse)
- {
- return "";
- }
- if (!clientResponse->addr)
- {
- return "";
- }
- uint8_t a, b, c, d = 0;
- if (0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d))
- {
- return "";
- }
-
- char ipaddr[16] = {'\0'};
- // ostringstream not working correctly here, hence snprintf
- snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
- return std::string (ipaddr);
-}
-
-std::string getPortTBServer(OCClientResponse * clientResponse)
-{
- if (!clientResponse)
- {
- return "";
- }
- if (!clientResponse->addr)
- {
- return "";
- }
- uint16_t p = 0;
- if (0 != OCDevAddrToPort(clientResponse->addr, &p))
- {
- return "";
- }
- std::ostringstream ss;
- ss << p;
- return ss.str();
-}
-
std::string getQueryStrForGetPut(const char * responsePayload)
{
static std::string coapServerPort = "5683";
static std::string coapServerResource = "/a/led";
-//The following variable determines the interface protocol (IPv4, IPv6, etc)
-//to be used for sending unicast messages. Default set to IPv4.
-static OCConnectivityType OC_CONNTYPE = OC_IPV4;
+//The following variable determines the interface protocol (IP, etc)
+//to be used for sending unicast messages. Default set to IP.
+static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
-
static int IPV4_ADDR_SIZE = 16;
void StripNewLineChar(char* str);
OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
OCClientResponse * clientResponse)
{
- uint8_t remoteIpAddr[4];
- uint16_t remotePortNu;
-
if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
{
OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
{
OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
- remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
OC_LOG_V(INFO, TAG,
- "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
- clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
- remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+ "Device =============> Discovered %s @ %s:%d",
+ clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
parseClientResponse(clientResponse);
}
else
{
- ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_ALL,
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
OC_LOW_QOS, &cbData, NULL, 0);
}
if (ret != OC_STACK_OK)
TEST_CASE = atoi(optarg);
break;
case 'c':
- // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
- // OC_CONNTYPE = OCConnectivityType(atoi(optarg));
- OC_CONNTYPE = OC_IPV4;
+ OC_CONNTYPE = CT_ADAPTER_IP;
break;
default:
PrintUsage();
return 0;
}
-std::string getIPAddrTBServer(OCClientResponse * clientResponse)
-{
- if(!clientResponse) return "";
- if(!clientResponse->addr) return "";
- uint8_t a, b, c, d = 0;
- if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
-
- char ipaddr[16] = {'\0'};
- // ostringstream not working correctly here, hence snprintf
- snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
- return std::string (ipaddr);
-}
-
-std::string getPortTBServer(OCClientResponse * clientResponse)
-{
- if(!clientResponse) return "";
- if(!clientResponse->addr) return "";
- uint16_t p = 0;
- if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
- std::ostringstream ss;
- ss << p;
- return ss.str();
-}
-
std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
{
return "/a/led";
void parseClientResponse(OCClientResponse * clientResponse)
{
- coapServerIP = getIPAddrTBServer(clientResponse);
- coapServerPort = getPortTBServer(clientResponse);
+ coapServerIP = clientResponse->devAddr.addr;
+ coapServerPort = clientResponse->devAddr.port;
coapServerResource = getQueryStrForGetPut(clientResponse);
}
OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
OCClientResponse * clientResponse)
{
- uint8_t remoteIpAddr[4];
- uint16_t remotePortNu;
-
OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
if (clientResponse)
{
OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
-
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
- remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
OC_LOG_V(INFO, TAG,
- "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
- clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
- remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+ "Device =============> Discovered %s @ %s:%d",
+ clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
ocConnType = clientResponse->connType;
int InitDiscovery()
{
OCStackResult ret;
+ OCMethod method;
OCCallbackData cbData;
char szQueryUri[MAX_URI_LENGTH] = { 0 };
OCConnectivityType discoveryReqConnType;
OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
return OC_STACK_INVALID_PARAM;
}
- discoveryReqConnType = OC_IPV4;
+ discoveryReqConnType = CT_ADAPTER_IP;
+ method = OC_REST_GET;
}
else
{
//Send discovery request on Wifi and Ethernet interface
- discoveryReqConnType = OC_ALL;
+ discoveryReqConnType = CT_DEFAULT;
strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
+ method = OC_REST_DISCOVER;
}
cbData.cb = discoveryReqCB;
(UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
szQueryUri);
- ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0,
+ ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
discoveryReqConnType, OC_LOW_QOS,
&cbData, NULL, 0);
if (ret != OC_STACK_OK)
return 0;
}
-std::string getIPAddrTBServer(OCClientResponse * clientResponse)
-{
- if(!clientResponse) return "";
- if(!clientResponse->addr) return "";
- uint8_t a, b, c, d = 0;
- if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
-
- char ipaddr[16] = {'\0'};
- // ostringstream not working correctly here, hence snprintf
- snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
- return std::string (ipaddr);
-}
-
-
std::string getPortTBServer(OCClientResponse * clientResponse)
{
if(!clientResponse) return "";
- if(!clientResponse->addr) return "";
- uint16_t p = 0;
- if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
std::ostringstream ss;
- ss << p;
+ ss << clientResponse->devAddr.port;
return ss.str();
}
}
cJSON_Delete(root);
- coapServerIP = getIPAddrTBServer(clientResponse);
+ coapServerIP = clientResponse->devAddr.addr;
if (port == -1)
{
coapServerPort = getPortTBServer(clientResponse);
AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
CAToken_t token, uint8_t tokenLength,
OCDoHandle *handle, OCMethod method,
- char * requestUri, char * resourceTypeName, OCConnectivityType conType, uint32_t ttl)
+ OCDevAddr *devAddr, char * requestUri,
+ char * resourceTypeName, uint32_t ttl)
{
if(!clientCB || !cbData || !handle || !requestUri || tokenLength > CA_MAX_TOKEN_LEN)
{
{
cbNode->TTL = ttl;
}
- cbNode->requestUri = requestUri;
- cbNode->conType = conType;
+ cbNode->requestUri = requestUri; // I own it now
+ cbNode->devAddr = devAddr; // I own it now
LL_APPEND(cbList, cbNode);
*clientCB = cbNode;
}
OICFree(token);
OICFree(*handle);
OICFree(requestUri);
+ OICFree(devAddr);
*handle = cbNode->handle;
}
{
// Amend the found or created node by adding a new resourceType to it.
return InsertResourceTypeFilter(cbNode,(char *)resourceTypeName);
+ // I own resourceTypName now.
}
else
{
static OCStackResult
-HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest,
- uint8_t filterOn, char *filterValue)
+HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest, uint8_t filterOn, char *filterValue)
{
if(!ehRequest)
{
char jsonbuffer[MAX_RESPONSE_LENGTH] = {};
size_t jsonbufferLength = 0;
uint16_t remaining = 0;
- char * ptr = NULL;
- OCResource * collResource = (OCResource *) ehRequest->resource;
+ char *ptr = NULL;
+ OCResource *collResource = (OCResource *)ehRequest->resource;
ptr = jsonbuffer;
remaining = MAX_RESPONSE_LENGTH;
ret = BuildRootResourceJSON(collResource, ptr, &remaining);
- if (ret == OC_STACK_OK && remaining >= (sizeof(OC_JSON_SEPARATOR) + 1))
+ if (ret == OC_STACK_OK && remaining >= (sizeof (OC_JSON_SEPARATOR) + 1))
{
ptr += strlen((char*)ptr);
*ptr = OC_JSON_SEPARATOR;
// Function will return error if not enough space in buffer.
ret = BuildVirtualResourceResponse(temp, filterOn, filterValue,
- (char*)ptr, &remaining, CA_IPV4 );
+ (char*)ptr, &remaining, CA_ADAPTER_IP);
if (ret != OC_STACK_OK)
{
break;
#include "utlist.h"
#include "pdu.h"
+
// Module Name
#define MOD_NAME PCF("ocobserve")
#endif
qos = DetermineObserverQoS(method, resourceObserver, qos);
- result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
+ result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
0, resPtr->sequenceNum, qos, resourceObserver->query,
NULL, NULL,
resourceObserver->token, resourceObserver->tokenLength,
resourceObserver->resUri, 0,
- &(resourceObserver->addressInfo), resourceObserver->connectivityType);
+ &resourceObserver->devAddr);
if(request)
{
//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,
+ result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
0, resPtr->sequenceNum, qos, resourceObserver->query,
NULL, NULL,
resourceObserver->token, resourceObserver->tokenLength,
resourceObserver->resUri, 0,
- &(resourceObserver->addressInfo), resourceObserver->connectivityType);
+ &resourceObserver->devAddr);
if(result == OC_STACK_OK)
{
qos = DetermineObserverQoS(OC_REST_GET, observer, qos);
- result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
+ result = AddServerRequest(&request, 0, 0, 1, OC_REST_GET,
0, resource->sequenceNum, qos, observer->query,
NULL, NULL, observer->token, observer->tokenLength,
observer->resUri, 0,
- &(observer->addressInfo), observer->connectivityType);
+ &observer->devAddr);
if(request)
{
uint8_t tokenLength,
OCResource *resHandle,
OCQualityOfService qos,
- const CAAddress_t *addressInfo,
- CATransportType_t connectivityType)
+ const OCDevAddr *devAddr)
{
// Check if resource exists and is observable.
if (!resHandle)
memcpy(obsNode->token, token, tokenLength);
}
obsNode->tokenLength = tokenLength;
- obsNode->addressInfo = *addressInfo;
- obsNode->connectivityType = connectivityType;
+
+ obsNode->devAddr = *devAddr;
obsNode->resource = resHandle;
+
LL_APPEND (serverObsList, obsNode);
+
return OC_STACK_OK;
}
}
/* This method will retrieve the port at which the secure resource is hosted */
-static OCStackResult GetSecurePortInfo(CATransportType_t connType, uint16_t *port)
+static OCStackResult GetSecurePortInfo(CATransportAdapter_t connType, uint16_t *port)
{
- CALocalConnectivity_t* info = NULL;
+ CAEndpoint_t* info = NULL;
uint32_t size = 0;
OCStackResult ret = OC_STACK_ERROR;
{
while (size--)
{
- if (info[size].isSecured && info[size].type == connType)
+ if ((info[size].flags & CA_SECURE) && info[size].adapter == connType)
{
- if (info[size].type == CA_IPV4)
+ if (info[size].adapter == CA_ADAPTER_IP)
{
- *port = info[size].addressInfo.IP.port;
+ *port = info[size].port;
ret = OC_STACK_OK;
break;
}
OCStackResult
BuildVirtualResourceResponse(const OCResource *resourcePtr, uint8_t filterOn,
const char *filterValue, char *out, uint16_t *remaining,
- CATransportType_t connType )
+ CATransportAdapter_t adapter)
{
if(!resourcePtr || !out || !remaining)
{
if (encodeRes)
{
// Add URIs
- cJSON_AddItemToObject (resObj, OC_RSRVD_HREF, cJSON_CreateString(resourcePtr->uri));
+ cJSON_AddItemToObject(resObj, OC_RSRVD_HREF, cJSON_CreateString(resourcePtr->uri));
// Add server instance id
- cJSON_AddItemToObject (resObj,
+ cJSON_AddItemToObject(resObj,
OC_RSRVD_SERVER_INSTANCE_ID,
cJSON_CreateString(OCGetServerInstanceIDString()));
cJSON_AddItemToObject (resObj, OC_RSRVD_PROPERTY, propObj = cJSON_CreateObject());
// Add resource types
- cJSON_AddItemToObject (propObj, OC_RSRVD_RESOURCE_TYPE, rtArray = cJSON_CreateArray());
+ cJSON_AddItemToObject(propObj, OC_RSRVD_RESOURCE_TYPE, rtArray = cJSON_CreateArray());
resourceTypePtr = resourcePtr->rsrcType;
while (resourceTypePtr)
{
- cJSON_AddItemToArray (rtArray,
+ cJSON_AddItemToArray(rtArray,
cJSON_CreateString(resourceTypePtr->resourcetypename));
resourceTypePtr = resourceTypePtr->next;
}
// Add interface types
- cJSON_AddItemToObject (propObj, OC_RSRVD_INTERFACE, rtArray = cJSON_CreateArray());
+ cJSON_AddItemToObject(propObj, OC_RSRVD_INTERFACE, rtArray = cJSON_CreateArray());
interfacePtr = resourcePtr->rsrcInterface;
while (interfacePtr)
{
- cJSON_AddItemToArray (rtArray, cJSON_CreateString(interfacePtr->name));
+ cJSON_AddItemToArray(rtArray, cJSON_CreateString(interfacePtr->name));
interfacePtr = interfacePtr->next;
}
//Add Policy
- cJSON_AddItemToObject (propObj, OC_RSRVD_POLICY, policyObj = cJSON_CreateObject());
+ cJSON_AddItemToObject(propObj, OC_RSRVD_POLICY, policyObj = cJSON_CreateObject());
if (policyObj)
{
// Policy Property Bitmap
// If resource is discoverable, set discoverability flag.
// Resources that are not discoverable will not have the flag.
- cJSON_AddNumberToObject (policyObj, OC_RSRVD_BITMAP,
+ cJSON_AddNumberToObject(policyObj, OC_RSRVD_BITMAP,
resourcePtr->resourceProperties & (OC_OBSERVABLE|OC_DISCOVERABLE));
// Set secure flag for secure resources
if (resourcePtr->resourceProperties & OC_SECURE)
{
- cJSON_AddNumberToObject (policyObj, OC_RSRVD_SECURE, OC_RESOURCE_SECURE);
+ cJSON_AddNumberToObject(policyObj, OC_RSRVD_SECURE, OC_RESOURCE_SECURE);
//Set the IP port also as secure resources are hosted on a different port
uint16_t port = 0;
- if (GetSecurePortInfo (connType, &port) == OC_STACK_OK)
+ if (GetSecurePortInfo(adapter, &port) == OC_STACK_OK)
{
- cJSON_AddNumberToObject (policyObj, OC_RSRVD_HOSTING_PORT, port);
+ cJSON_AddNumberToObject(policyObj, OC_RSRVD_HOSTING_PORT, port);
}
}
}
OC_LOG(INFO, TAG, PCF("Entering DetermineResourceHandling"));
+ const OCDevAddr *devAddr = &request->devAddr;
+
// Check if virtual resource
if (IsVirtualResource((const char*)request->resourceUrl))
{
*resource = headResource;
return OC_STACK_OK;
}
- if (NULL == request->resourceUrl || (strlen((const char*)(request->resourceUrl)) == 0))
+ if (strlen((const char*)(request->resourceUrl)) == 0)
{
// Resource URL not specified
*handling = OC_RESOURCE_NOT_SPECIFIED;
}
// secure resource will entertain only authorized requests
- if ((resourcePtr->resourceProperties & OC_SECURE) && (request->secured == 0))
+ if ((resourcePtr->resourceProperties & OC_SECURE) && ((devAddr->flags & OC_FLAG_SECURE) == 0))
{
OC_LOG(ERROR, TAG, PCF("Un-authorized request. Ignoring"));
return OC_STACK_RESOURCE_ERROR;
}
static OCStackResult
-HandleVirtualResource (OCServerRequest *request, OCResource* resource)
+HandleVirtualResource(OCServerRequest *request, OCResource *resource)
{
- if(!request || !resource)
+ if (!request || !resource)
{
return OC_STACK_INVALID_PARAM;
}
remaining--;
}
firstLoopDone = 1;
- result = BuildVirtualResourceResponse(resource, filterOn, filterValue,
- (char*)ptr, &remaining, request->connectivityType );
+ result = BuildVirtualResourceResponse(resource, filterOn,
+ filterValue, (char*)ptr, &remaining,
+ (CATransportAdapter_t)request->devAddr.adapter);
if (result != OC_STACK_OK)
{
(const char *)(request->query),
ehRequest.obsInfo.obsId, request->requestToken, request->tokenLength,
resource, request->qos,
- &request->addressInfo, request->connectivityType);
+ &request->devAddr);
if(result == OC_STACK_OK)
{
* OCStackResult
*/
OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
- uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method,
+ uint8_t delayedResNeeded, uint8_t notificationFlag, OCMethod method,
uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
OCQualityOfService qos, char * query,
OCHeaderOption * rcvdVendorSpecificHeaderOptions,
- char * reqJSONPayload, CAToken_t requestToken,
- uint8_t tokenLength,
- char * resourceUrl, size_t reqTotalSize,
- CAAddress_t *addressInfo, CATransportType_t connectivityType)
+ char * reqJSONPayload, CAToken_t requestToken, uint8_t tokenLength,
+ char * resourceUrl, size_t reqTotalSize, const OCDevAddr *devAddr)
{
OCServerRequest * serverRequest = NULL;
//null terminator as well.
serverRequest = (OCServerRequest *) OICCalloc(1, sizeof(OCServerRequest) +
(reqTotalSize ? reqTotalSize : 1) - 1);
+ VERIFY_NON_NULL(devAddr);
VERIFY_NON_NULL(serverRequest);
serverRequest->coapID = coapID;
serverRequest->delayedResNeeded = delayedResNeeded;
- serverRequest->secured = secured;
serverRequest->notificationFlag = notificationFlag;
serverRequest->method = method;
resourceUrl);
}
- if (addressInfo)
- {
- serverRequest->addressInfo = *addressInfo;
- }
- serverRequest->connectivityType = connectivityType;
+ serverRequest->devAddr = *devAddr;
*request = serverRequest;
OC_LOG(INFO, TAG, PCF("Server Request Added!!"));
OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
{
OCStackResult result = OC_STACK_ERROR;
- CARemoteEndpoint_t responseEndpoint = {};
+ CAEndpoint_t responseEndpoint = {};
CAResponseInfo_t responseInfo = {};
CAHeaderOption_t* optionsPointer = NULL;
OCServerRequest *serverRequest = (OCServerRequest *)ehResponse->requestHandle;
- // Copy the address
- responseEndpoint.resourceUri = (CAURI_t) serverRequest->resourceUrl;
- responseEndpoint.addressInfo = serverRequest->addressInfo;
- responseEndpoint.transportType = serverRequest->connectivityType;
- responseEndpoint.isSecured = serverRequest->secured;
+ CopyDevAddrToEndpoint(&serverRequest->devAddr, &responseEndpoint);
+ responseInfo.info.resourceUri = serverRequest->resourceUrl;
responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult);
if(serverRequest->notificationFlag && serverRequest->qos == OC_HIGH_QOS)
#ifdef WITH_PRESENCE
//TODO: Add other connectivity types to CAConnTypes[] when enabled
- CATransportType_t CAConnTypes[] = {CA_IPV4};
+ CATransportAdapter_t CAConnTypes[] = {CA_ADAPTER_IP};
const char * connTypes[] = {"ip transport"};
- int size = sizeof(CAConnTypes)/ sizeof(CATransportType_t);
- CATransportType_t connType = responseEndpoint.transportType;
+ int size = sizeof(CAConnTypes)/ sizeof(CATransportAdapter_t);
+ CATransportAdapter_t adapter = responseEndpoint.adapter;
CAResult_t caResult = CA_STATUS_FAILED;
result = OC_STACK_OK;
//Sending response on all n/w interfaces
for(int i = 0; i < size; i++ )
{
- responseEndpoint.transportType = (CATransportType_t)(connType & CAConnTypes[i]);
- if(responseEndpoint.transportType)
+ responseEndpoint.adapter = (CATransportAdapter_t)(adapter & CAConnTypes[i]);
+ if(responseEndpoint.adapter)
{
//The result is set to OC_STACK_OK only if CASendResponse succeeds in sending the
//response on all the n/w interfaces else it is set to OC_STACK_ERROR
{OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
TAG, PCF(#arg " is NULL")); return (retVal); } }
+#define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
+ TAG, PCF(#arg " is NULL")); return; } }
#define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
goto exit;} }
*/
static bool OCIsPacketTransferRequired(const char *request, const char *response, size_t size);
-/**
- * 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 query part of the URI.
- * @param resourceType The resource type to be populated; pass by reference.
- *
- * @return ::OC_STACK_OK on success, some other value upon failure.
- */
-static OCStackResult getResourceType(const char * query, char** resourceType);
-
/*
* Attempts to initialize every network interface that the CA Layer might have compiled in.
*
static uint32_t GetTicks(uint32_t afterMilliSeconds);
/**
- * This method is used to create the IPv4 dev_addr structure.
- * Builds a socket interface address using IP address and port number.
- * TODO: Remove in future. Temporary helper function.
- *
- * @param a IPv4 octet 0.
- * @param b IPv4 octet 1.
- * @param c IPv4 octet 2.
- * @param d IPv4 octet 3.
- * @param port Port number.
- * @param ipAddr - IPv4 address.
- * @return ::OC_STACK_OK on success, some other value upon failure.
- */
-static OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
- uint16_t port, OCDevAddr *ipAddr);
-
-/**
* Convert CAResponseResult_t to OCStackResult.
*
* @param caCode CAResponseResult_t code.
static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode);
/**
- * Convert OCConnectivityType to CATransportType_t.
+ * Convert OCTransportFlags_t to CATransportModifiers_t.
*
- * @param ocConType OCConnectivityType input.
- * @param caConType CATransportType_t output.
- * @return ::OC_STACK_OK on success, some other value upon failure.
+ * @param ocConType OCTransportFlags_t input.
+ * @return CATransportFlags
*/
-static OCStackResult OCToCATransportType(OCConnectivityType ocConType,
- CATransportType_t* caConType);
+static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
/**
- * Convert CATransportType_t to OCConnectivityType.
+ * Convert CATransportFlags_t to OCTransportModifiers_t.
*
- * @param caConType CATransportType_t input.
- * @param ocConType OCConnectivityType output.
- * @return ::OC_STACK_OK on success, some other value upon failure.
+ * @param caConType CATransportFlags_t input.
+ * @return OCTransportFlags
*/
-static OCStackResult CAToOCConnectivityType(CATransportType_t caConType,
- OCConnectivityType *ocConType);
-
-/**
- * Update response.addr appropriately from endPoint.addressInfo.
- *
- * @param address OCDevAddr output.
- * @param endPoint CARemoteEndpoint_t input.
- * @return ::OC_STACK_OK on success, some other value upon failure.
- */
-static OCStackResult UpdateResponseAddr(OCDevAddr *address, const CARemoteEndpoint_t* endPoint);
+static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
/**
* Handle response from presence request.
* @param responseInfo CA response info.
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
- const CAResponseInfo_t* responseInfo);
+static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
+ const CAResponseInfo_t *responseInfo);
/**
* This function will be called back by CA layer when a response is received.
* @param endPoint CA remote endpoint.
* @param responseInfo CA response info.
*/
-static void HandleCAResponses(const CARemoteEndpoint_t* endPoint,
+static void HandleCAResponses(const CAEndpoint_t* endPoint,
const CAResponseInfo_t* responseInfo);
/**
* @param endPoint CA remote endpoint.
* @param requestInfo CA request info.
*/
-static void HandleCARequests(const CARemoteEndpoint_t* endPoint,
+static void HandleCARequests(const CAEndpoint_t* endPoint,
const CARequestInfo_t* requestInfo);
/**
}
}
-OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
- uint16_t port, OCDevAddr *ipAddr)
+void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
{
- if (!ipAddr )
+ VERIFY_NON_NULL_NR(in, FATAL);
+ VERIFY_NON_NULL_NR(out, FATAL);
+
+ out->adapter = (OCTransportAdapter)in->adapter;
+ out->flags = CAToOCTransportFlags(in->flags);
+ strncpy(out->addr, in->addr, MAX_ADDR_STR_SIZE);
+ out->addr[MAX_ADDR_STR_SIZE - 1] = '\0';
+ out->port = in->port;
+}
+
+void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
+{
+ VERIFY_NON_NULL_NR(in, FATAL);
+ VERIFY_NON_NULL_NR(out, FATAL);
+
+ out->adapter = (CATransportAdapter_t)in->adapter;
+ out->flags = OCToCATransportFlags(in->flags);
+ strncpy(out->addr, in->addr, MAX_ADDR_STR_SIZE);
+ out->port = in->port;
+}
+
+static OCStackResult OCCreateEndpoint(OCDevAddr *devAddr, CAEndpoint_t **endpoint)
+{
+ VERIFY_NON_NULL(devAddr, FATAL, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
+
+ CAEndpoint_t *ep = (CAEndpoint_t *)OICMalloc(sizeof (CAEndpoint_t));
+ if (!ep)
{
- OC_LOG(FATAL, TAG, PCF("Invalid argument"));
- return OC_STACK_INVALID_PARAM;
+ return OC_STACK_NO_MEMORY;
}
- ipAddr->addr[0] = a;
- ipAddr->addr[1] = b;
- ipAddr->addr[2] = c;
- ipAddr->addr[3] = d;
- ipAddr->addr[4] = (uint8_t)port;
- ipAddr->addr[5] = (uint8_t)(port >> 8);
+ ep->adapter = (CATransportAdapter_t)devAddr->adapter;
+ ep->flags = OCToCATransportFlags(devAddr->flags);
+ strncpy(ep->addr, devAddr->addr, MAX_ADDR_STR_SIZE_CA);
+ ep->port = devAddr->port;
+
+ *endpoint = ep;
return OC_STACK_OK;
}
+static void OCDestroyEndpoint(CAEndpoint_t *endpoint)
+{
+ free(endpoint);
+}
+
+void FixUpClientResponse(OCClientResponse *cr)
+{
+ VERIFY_NON_NULL_NR(cr, FATAL);
+
+ cr->addr = &cr->devAddr;
+ cr->connType = (OCConnectivityType)
+ ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
+}
+
//-----------------------------------------------------------------------------
// Internal API function
//-----------------------------------------------------------------------------
return ret;
}
-OCStackResult OCToCATransportType(OCConnectivityType ocConType, CATransportType_t* caConType)
+CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
{
- OCStackResult ret = OC_STACK_OK;
+ CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
- switch(ocConType)
+ // supply default behavior
+ if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
{
- case OC_IPV4:
- *caConType = CA_IPV4;
- break;
- case OC_IPV6:
- *caConType = CA_IPV6;
- break;
- case OC_EDR:
- *caConType = CA_EDR;
- break;
- case OC_LE:
- *caConType = CA_LE;
- break;
- case OC_ALL:
- // Currently OC_ALL represents IPv4
- // Add other connectivity types as they are enabled in future
- *caConType = (CATransportType_t) (CA_IPV4);
- break;
- default:
- ret = OC_STACK_INVALID_PARAM;
- break;
+ caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
}
- return ret;
-}
-
-OCStackResult CAToOCConnectivityType(CATransportType_t caConType, OCConnectivityType *ocConType)
-{
- OCStackResult ret = OC_STACK_OK;
-
- switch(caConType)
+ if ((caFlags & OC_MASK_SCOPE) == 0)
{
- case CA_IPV4:
- *ocConType = OC_IPV4;
- break;
- case CA_IPV6:
- *ocConType = OC_IPV6;
- break;
- case CA_EDR:
- *ocConType = OC_EDR;
- break;
- case CA_LE:
- *ocConType = OC_LE;
- break;
- default:
- ret = OC_STACK_INVALID_PARAM;
- break;
+ caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
}
- return ret;
+ return caFlags;
}
-OCStackResult UpdateResponseAddr(OCDevAddr *address, const CARemoteEndpoint_t* endPoint)
+OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
{
- OCStackResult ret = OC_STACK_ERROR;
- char * tok = NULL;
- char * savePtr = NULL;
- char* cpAddress = OICStrdup(endPoint->addressInfo.IP.ipAddress);
- if(!cpAddress)
- {
- ret = OC_STACK_NO_MEMORY;
- goto exit;
- }
-
- // Grabs the first three numbers from the IPv4 address and replaces dots
- for(int i=0; i<4; i++)
- {
- tok = strtok_r(i==0 ? cpAddress : NULL, ".", &savePtr);
-
- if(!tok)
- {
- ret = OC_STACK_ERROR;
- goto exit;
- }
- address->addr[i] = atoi(tok);
- }
-
- address->addr[4] = (uint8_t)endPoint->addressInfo.IP.port;
- address->addr[5] = (uint8_t)(endPoint->addressInfo.IP.port >> 8);
- ret = OC_STACK_OK;
-
-exit:
- OICFree(cpAddress);
- return ret;
+ return (OCTransportFlags)caFlags;
}
static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
{
- if(trigger == OC_PRESENCE_TRIGGER_CREATE)
+ if (trigger == OC_PRESENCE_TRIGGER_CREATE)
{
return OC_RSRVD_TRIGGER_CREATE;
}
- else if(trigger == OC_PRESENCE_TRIGGER_CHANGE)
+ else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
{
return OC_RSRVD_TRIGGER_CHANGE;
}
}
}
+/**
+ * The cononical presence allows constructed URIs to be string compared.
+ *
+ * requestUri must be a char array of size CA_MAX_URI_LENGTH
+ */
+static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri, char *presenceUri)
+{
+ VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
+
+ const char *format;
+
+ if (endpoint->flags & CA_IPV6)
+ {
+ format = "coap://[%s]:%u%s";
+ }
+ else
+ {
+ format = "coap://%s:%u%s";
+ }
+
+ return snprintf(presenceUri, CA_MAX_URI_LENGTH, format, endpoint->addr,
+ endpoint->port, OC_PRESENCE_URI);
+}
+
void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge,
OCPresenceTrigger *presenceTrigger, char** resType)
{
cJSON_Delete(repObj);
}
-static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
- const CAResponseInfo_t* responseInfo)
+OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
+ const CAResponseInfo_t *responseInfo)
{
+ VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
+
OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
ClientCB * cbNode = NULL;
char *resourceTypeName = NULL;
- OCClientResponse response = {};
- OCDevAddr address = {};
+ OCClientResponse response;
OCStackResult result = OC_STACK_ERROR;
uint32_t maxAge = 0;
OCPresenceTrigger presenceTrigger = OC_PRESENCE_TRIGGER_CHANGE;
- char *fullUri = NULL;
- char *ipAddress = NULL;
+ int uriLen;
+ char presenceUri[CA_MAX_URI_LENGTH];
+
int presenceSubscribe = 0;
int multicastPresenceSubscribe = 0;
return OC_STACK_ERROR;
}
- fullUri = (char *) OICMalloc(MAX_URI_LENGTH);
-
- if(!fullUri)
- {
- OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for fullUri"));
- result = OC_STACK_NO_MEMORY;
- goto exit;
- }
-
- ipAddress = OICStrdup(endPoint->addressInfo.IP.ipAddress);
-
- if(!ipAddress)
+ uriLen = FormCanonicalPresenceUri(endpoint, OC_PRESENCE_URI, presenceUri);
+ if (uriLen < 0 || uriLen >= sizeof (presenceUri))
{
- OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for ipAddress"));
- result = OC_STACK_NO_MEMORY;
- goto exit;
+ return OC_STACK_INVALID_URI;
}
-
- snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
- OC_PRESENCE_URI);
-
- cbNode = GetClientCB(NULL, 0, NULL, fullUri);
-
- if(cbNode)
+ cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
+ if (cbNode)
{
presenceSubscribe = 1;
}
else
{
- snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", OC_MULTICAST_IP, OC_MULTICAST_PORT,
- endPoint->resourceUri);
- cbNode = GetClientCB(NULL, 0, NULL, fullUri);
- if(cbNode)
+ strncpy(presenceUri, responseInfo->info.resourceUri, CA_MAX_URI_LENGTH);
+ cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
+ if (cbNode)
{
multicastPresenceSubscribe = 1;
}
}
- if(!presenceSubscribe && !multicastPresenceSubscribe)
+ if (!presenceSubscribe && !multicastPresenceSubscribe)
{
- OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
+ OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
goto exit;
}
response.resJSONPayload = responseInfo->info.payload;
response.result = OC_STACK_OK;
- result = UpdateResponseAddr(&address, endPoint);
- if(result != OC_STACK_OK)
- {
- goto exit;
- }
-
- response.addr = &address;
-
- result = CAToOCConnectivityType(endPoint->transportType, &(response.connType));
- if(result != OC_STACK_OK)
- {
- OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
- goto exit;
- }
+ CopyEndpointToDevAddr(endpoint, &response.devAddr);
+ FixUpClientResponse(&response);
- if(responseInfo->info.payload)
+ if (responseInfo->info.payload)
{
parsePresencePayload(responseInfo->info.payload,
&(response.sequenceNumber),
&resourceTypeName);
}
- if(presenceSubscribe)
+ if (presenceSubscribe)
{
if(cbNode->sequenceNumber == response.sequenceNumber)
{
- if (cbNode->presence)
- {
- OC_LOG(INFO, TAG, PCF("No presence change. Updating TTL."));
-
- result = ResetPresenceTTL(cbNode, maxAge);
-
- if (result != OC_STACK_OK)
- {
- OC_LOG_V(ERROR, TAG, "ResetPresenceTTL failed with error: %u", result);
- }
- }
- else
- {
- OC_LOG(INFO, TAG, PCF("Not subscribed to presence."));
- }
-
+ 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 *) OICMalloc(sizeof(OCPresence));
+ cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
+
if(!(cbNode->presence))
{
OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
else
{
// This is the multicast case
-
OCMulticastNode* mcNode = NULL;
- mcNode = GetMCPresenceNode(fullUri);
+ mcNode = GetMCPresenceNode(presenceUri);
if(mcNode != NULL)
{
}
else
{
- char* uri = OICStrdup(fullUri);
- if(!uri)
+ char* uri = OICStrdup(presenceUri);
+ if (!uri)
{
- OC_LOG(ERROR, TAG,
+ OC_LOG(INFO, TAG,
PCF("No Memory for URI to store in the presence node"));
result = OC_STACK_NO_MEMORY;
goto exit;
}
+
result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
- if(result != OC_STACK_OK)
+ if(result == OC_STACK_NO_MEMORY)
{
- OC_LOG(ERROR, TAG,
- PCF("Unable to add Multicast Presence Node"));
+ OC_LOG(INFO, TAG,
+ PCF("No Memory for Multicast Presence Node"));
OICFree(uri);
goto exit;
}
+ // presence node now owns uri
}
// Ensure that a filter is actually applied.
}
exit:
-OICFree(fullUri);
-OICFree(ipAddress);
-OICFree(resourceTypeName);
-return result;
+ OICFree(resourceTypeName);
+ return result;
}
-void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
+void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
{
- OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
-
- if(NULL == endPoint)
- {
- OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
- return;
- }
-
- if(NULL == responseInfo)
- {
- OC_LOG(ERROR, TAG, PCF("responseInfo is NULL"));
- return;
- }
+ VERIFY_NON_NULL_NR(endPoint, FATAL);
+ VERIFY_NON_NULL_NR(responseInfo, FATAL);
+ VERIFY_NON_NULL_NR(responseInfo->info.resourceUri, FATAL);
- if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0)
+ if(strcmp(responseInfo->info.resourceUri, OC_PRESENCE_URI) == 0)
{
HandlePresenceResponse(endPoint, responseInfo);
return;
{
OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token"));
OC_LOG(INFO, TAG, PCF("Calling into application address space"));
- OCClientResponse response = {};
- OCDevAddr address = {};
- OCStackResult result = UpdateResponseAddr(&address, endPoint);
- if(result != OC_STACK_OK)
- {
- OC_LOG(ERROR, TAG, PCF("Error parsing IP address in UpdateResponseAddr"));
- return;
- }
- result = UpdateResponseAddr(&address, endPoint);
- if(result != OC_STACK_OK)
- {
- OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
- return;
- }
- response.addr = &address;
+ OCClientResponse response = {};
+ CopyEndpointToDevAddr(endPoint, &response.devAddr);
+ FixUpClientResponse(&response);
+ response.resourceUri = responseInfo->info.resourceUri;
response.result = CAToOCStackResult(responseInfo->result);
cbNode->callBack(cbNode->context,
{
OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found"));
OC_LOG(INFO, TAG, PCF("Calling into application address space"));
- OCClientResponse response = {};
- OCDevAddr address = {};
- OCStackResult result = UpdateResponseAddr(&address, endPoint);
- if(result != OC_STACK_OK)
- {
- OC_LOG(ERROR, TAG, PCF("Error parsing IP address in UpdateResponseAddr"));
- return;
- }
- response.addr = &address;
- // Populate the connectivity type. If this is a discovery response,
- // the resource that will be constructed from this response will make
- // further API calls from this interface.
- result = CAToOCConnectivityType(endPoint->transportType,
- &(response.connType));
- if(result != OC_STACK_OK)
- {
- OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint"));
- return;
- }
+ OCClientResponse response = {};
+ CopyEndpointToDevAddr(endPoint, &response.devAddr);
+ FixUpClientResponse(&response);
+ response.resourceUri = responseInfo->info.resourceUri;
response.result = CAToOCStackResult(responseInfo->result);
response.resJSONPayload = (const char*)responseInfo->info.payload;
* This function handles error response from CA
* code shall be added to handle the errors
*/
-void HandleCAErrorResponse(const CARemoteEndpoint_t* endPoint, const CAErrorInfo_t* errrorInfo)
+void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
{
OC_LOG(INFO, TAG, PCF("Enter HandleCAErrorResponse"));
* from the application entity handler. These responses have no payload and are usually ACKs,
* RESETs or some error conditions that were caught by the stack.
*/
-OCStackResult SendDirectStackResponse(const CARemoteEndpoint_t* endPoint, const uint16_t coapID,
+OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
const CAResponseResult_t responseResult, const CAMessageType_t type,
const uint8_t numOptions, const CAHeaderOption_t *options,
CAToken_t token, uint8_t tokenLength)
}
//This function will be called back by CA layer when a request is received
-void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
+void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
{
OC_LOG(INFO, TAG, PCF("Enter HandleCARequests"));
if(!endPoint)
OCServerProtocolRequest serverRequest = {};
- OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s\n"), (char*)endPoint->resourceUri);
+ OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s\n"), requestInfo->info.resourceUri);
char * newUri = NULL;
char * query = NULL;
- requestResult = getQueryFromUri(endPoint->resourceUri, &query, &newUri);
+ requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &newUri);
if (requestResult != OC_STACK_OK)
{
switch (requestInfo->method)
{
case CA_GET:
- {
- serverRequest.method = OC_REST_GET;
- break;
- }
+ serverRequest.method = OC_REST_GET;
+ break;
case CA_PUT:
- {
- serverRequest.method = OC_REST_PUT;
- break;
- }
+ serverRequest.method = OC_REST_PUT;
+ break;
case CA_POST:
- {
- serverRequest.method = OC_REST_POST;
- break;
- }
+ serverRequest.method = OC_REST_POST;
+ break;
case CA_DELETE:
- {
- serverRequest.method = OC_REST_DELETE;
- break;
- }
+ serverRequest.method = OC_REST_DELETE;
+ break;
default:
- {
- OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
- SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
+ OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported"));
+ SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
requestInfo->info.type, requestInfo->info.numOptions,
requestInfo->info.options, requestInfo->info.token,
requestInfo->info.tokenLength);
- return;
- }
+ return;
}
OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d",
{
serverRequest.qos = OC_LOW_QOS;
}
- // CA does not need the following 2 fields
+ // CA does not need the following field
// Are we sure CA does not need them? how is it responding to multicast
serverRequest.delayedResNeeded = 0;
- serverRequest.secured = endPoint->isSecured;
serverRequest.coapID = requestInfo->info.messageId;
// copy the address
- serverRequest.addressInfo = endPoint->addressInfo;
- serverRequest.connectivityType = endPoint->transportType;
+ CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
// copy vendor specific header options
uint8_t tempNum = (requestInfo->info.numOptions);
{
OC_LOG(INFO, TAG, PCF("This is a new Server Request"));
result = AddServerRequest(&request, protocolRequest->coapID,
- protocolRequest->delayedResNeeded, protocolRequest->secured, 0,
+ protocolRequest->delayedResNeeded, 0,
protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions,
protocolRequest->observationOption, protocolRequest->qos,
protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
protocolRequest->reqJSONPayload, protocolRequest->requestToken,
protocolRequest->tokenLength,
- protocolRequest->resourceUrl,protocolRequest->reqTotalSize,
- &protocolRequest->addressInfo, protocolRequest->connectivityType);
+ protocolRequest->resourceUrl, protocolRequest->reqTotalSize,
+ &protocolRequest->devAddr);
if (OC_STACK_OK != result)
{
OC_LOG(ERROR, TAG, PCF("Error adding server request"));
return result;
}
-bool ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
-{
- size_t index = 0;
- char *itr, *coap;
- uint8_t dotCount = 0;
-
- ipAddr[index] = 0;
- *port = 0;
- /* search for scheme */
- itr = ipAddrStr;
- if (!isdigit((char) *ipAddrStr))
- {
- coap = OC_COAP_SCHEME;
- while (*coap && tolower(*itr) == *coap)
- {
- coap++;
- itr++;
- }
- }
- ipAddrStr = itr;
-
- while (*ipAddrStr)
- {
- if (isdigit(*ipAddrStr))
- {
- ipAddr[index] *= 10;
- ipAddr[index] += *ipAddrStr - '0';
- }
- else if (*ipAddrStr == '.')
- {
- index++;
- dotCount++;
- ipAddr[index] = 0;
- }
- else
- {
- break;
- }
- ipAddrStr++;
- }
- if(*ipAddrStr == ':')
- {
- ipAddrStr++;
- while (*ipAddrStr){
- if (isdigit(*ipAddrStr))
- {
- *port *= 10;
- *port += *ipAddrStr - '0';
- }
- else
- {
- break;
- }
- ipAddrStr++;
- }
- }
-
- return (3 == dotCount);
-}
-
bool validatePlatformInfo(OCPlatformInfo info)
{
}
return true;
}
+
//-----------------------------------------------------------------------------
// Public APIs
//-----------------------------------------------------------------------------
OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
{
+ (void) ipAddr;
+ (void) port;
+
+ return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
+}
+
+OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
+{
if(stackState == OC_STACK_INITIALIZED)
{
OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \
return OC_STACK_OK;
}
- (void) ipAddr;
- (void) port;
OCStackResult result = OC_STACK_ERROR;
OC_LOG(INFO, TAG, PCF("Entering OCInit"));
}
myStackMode = mode;
+ caglobals.serverFlags = (CATransportFlags_t)serverFlags;
+ caglobals.clientFlags = (CATransportFlags_t)clientFlags;
+
defaultDeviceHandler = NULL;
defaultDeviceHandlerCallbackParameter = NULL;
OCSeedRandom();
// Free memory dynamically allocated for resources
deleteAllResources();
DeleteDeviceInfo();
- DeletePlatformInfo();
CATerminate();
// Remove all observers
DeleteObserverList();
return OC_STACK_OK;
}
-OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
- const char *referenceUri, const char *request, OCConnectivityType conType,
- OCQualityOfService qos, OCCallbackData *cbData,
- OCHeaderOption * options, uint8_t numOptions)
+/**
+ * A request uri consists of the following components in order:
+ * example
+ * optional prefix "coap://"
+ * optionally one of
+ * IPv6 address "[1234::5678]"
+ * IPv4 address "192.168.1.1"
+ * optional port ":5683"
+ * resource uri "/oc/core..."
+ *
+ * for PRESENCE requests, extract resource type.
+ */
+static OCStackResult ParseRequestUri(const char *fullUri,
+ OCTransportAdapter adapter,
+ OCTransportFlags flags,
+ OCDevAddr **devAddr,
+ char **resourceUri,
+ char **resourceType)
{
- OCStackResult result = OC_STACK_ERROR;
- ClientCB *clientCB = 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;
- uint8_t tokenLength = CA_MAX_TOKEN_LEN;
- OCDoHandle resHandle = NULL;
- CAInfo_t requestData ={};
- CARequestInfo_t requestInfo ={};
- CAGroupEndpoint_t grpEnd = {};
+ VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
- OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
+ OCStackResult result = OC_STACK_OK;
+ OCDevAddr *da = NULL;
+ char *colon = NULL;
+ char *end;
- // Validate input parameters
- VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
- VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
+ // provide defaults for all returned values
+ if (devAddr)
+ {
+ *devAddr = NULL;
+ }
+ if (resourceUri)
+ {
+ *resourceUri = NULL;
+ }
+ if (resourceType)
+ {
+ *resourceType = NULL;
+ }
- //TODO ("Need to form the final query by concatenating require and reference URI's");
- VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI);
+ // delimit url prefix, if any
+ const char *start = fullUri;
+ char *slash2 = strstr(start, "//");
+ if (slash2)
+ {
+ start = slash2 + 2;
+ }
+ char *slash = strchr(start, '/');
+ if (!slash)
+ {
+ return OC_STACK_INVALID_URI;
+ }
- uint16_t uriLen = strlen(requiredUri);
+ // processs url prefix, if any
+ size_t urlLen = slash - start;
+ if (urlLen && devAddr)
+ { // construct OCDevAddr
+ if (start[0] == '[')
+ { // ipv6 address
+ char *close = strchr(++start, ']');
+ if (!close || close > slash)
+ {
+ return OC_STACK_INVALID_URI;
+ }
+ end = close;
+ if (close[1] == ':')
+ {
+ colon = close + 1;
+ }
+ }
+ else
+ { // ipv4 address
+ end = slash;
+ colon = strchr(start, ':');
+ end = (colon && colon < slash) ? colon : slash;
+ }
+ size_t len = end - start;
+ if (len > MAX_ADDR_STR_SIZE)
+ {
+ return OC_STACK_INVALID_URI;
+ }
- // ToDo: We should also check if the requiredUri has a mutlicast address,
- // then qos has to be OC_Low_QOS
- switch (method)
- {
- case OC_REST_GET:
- case OC_REST_OBSERVE:
- case OC_REST_OBSERVE_ALL:
- case OC_REST_CANCEL_OBSERVE:
- requestInfo.method = CA_GET;
- break;
+ // port
+ uint16_t port = 0; // use standard multicast port
+ if (colon && colon < slash)
+ {
+ for (colon++; colon < slash; colon++)
+ {
+ char c = colon[0];
+ if (c < '0' || c > '9')
+ {
+ return OC_STACK_INVALID_URI;
+ }
+ port = 10 * port + c - '0';
+ }
+ }
- case OC_REST_PUT:
- requestInfo.method = CA_PUT;
- break;
+ da = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
+ if (!da)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+ strncpy(da->addr, start, len);
+ da->port = port;
+ da->adapter = adapter;
+ da->flags = flags;
+ if (!strncmp(fullUri, "coaps:", 6))
+ {
+ da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
+ }
+ *devAddr = da;
+ }
- case OC_REST_POST:
- requestInfo.method = CA_POST;
- break;
+ // process resource uri, if any
+ if (slash)
+ { // request uri and query
+ size_t ulen = strlen(slash); // resource uri length
+ size_t tlen = 0; // resource type length
+ char *type = NULL;
- case OC_REST_DELETE:
- requestInfo.method = CA_DELETE;
- break;
+ static const char *strPresence = "/oc/presence?rt=";
+ static const size_t lenPresence = 15; // = strlen(presence);
+ if (!strncmp(slash, strPresence, lenPresence))
+ {
+ type = slash + lenPresence;
+ tlen = ulen - lenPresence;
+ }
+ // resource uri
+ if (resourceUri)
+ {
+ *resourceUri = (char *)OICMalloc(ulen + 1);
+ if (!*resourceUri)
+ {
+ result = OC_STACK_NO_MEMORY;
+ goto error;
+ }
+ strcpy(*resourceUri, slash);
+ }
+ // resource type
+ if (type && resourceType)
+ {
+ *resourceType = (char *)OICMalloc(tlen + 1);
+ if (!*resourceType)
+ {
+ result = OC_STACK_NO_MEMORY;
+ goto error;
+ }
+ strncpy(*resourceType, type, tlen);
+ }
+ }
+
+ return OC_STACK_OK;
+
+error:
+ // free all returned values
+ if (devAddr)
+ {
+ OICFree(*devAddr);
+ }
+ if (resourceUri)
+ {
+ OICFree(*resourceUri);
+ }
+ if (resourceType)
+ {
+ OICFree(*resourceType);
+ }
+ return result;
+}
+
+static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
+ char *resourceUri, char **requestUri)
+{
+ char uri[CA_MAX_URI_LENGTH];
- #ifdef WITH_PRESENCE
- case OC_REST_PRESENCE:
- // Replacing method type with GET because "presence"
- // is a stack layer only implementation.
- requestInfo.method = CA_GET;
- break;
- #endif
+ FormCanonicalPresenceUri(endpoint, resourceUri, uri);
- default:
- result = OC_STACK_INVALID_METHOD;
- goto exit;
+ *requestUri = (char *)OICMalloc(strlen(uri) + 1);
+ if (!*requestUri)
+ {
+ return OC_STACK_NO_MEMORY;
}
- if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK)
+ strcpy(*requestUri, uri);
+ return OC_STACK_OK;
+}
+
+/**
+ * Discover or Perform requests on a specified resource
+ */
+OCStackResult OCDoResource(OCDoHandle *handle,
+ OCMethod method,
+ const char *requestUri,
+ const OCDevAddr *destination,
+ const char *request,
+ OCConnectivityType connectivityType,
+ OCQualityOfService qos,
+ OCCallbackData *cbData,
+ OCHeaderOption *options,
+ uint8_t numOptions)
+{
+ OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
+
+ // Validate input parameters
+ VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
+ VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
+ VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
+
+ OCStackResult result = OC_STACK_ERROR;
+ CAResult_t caResult;
+ CAToken_t token = NULL;
+ uint8_t tokenLength = CA_MAX_TOKEN_LEN;
+ ClientCB *clientCB = NULL;
+ OCDoHandle resHandle = NULL;
+ CAEndpoint_t *endpoint = NULL;
+ OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
+ uint32_t ttl = 0;
+ OCTransportAdapter adapter;
+ OCTransportFlags flags;
+ // the request contents are put here
+ CARequestInfo_t requestInfo = { CA_GET };
+ // requestUri will be parsed into the following three variables
+ OCDevAddr *devAddr = NULL;
+ char *resourceUri = NULL;
+ char *resourceType = NULL;
+
+ // To track if memory is allocated for additional header options
+ uint8_t hdrOptionMemAlloc = 0;
+
+ // This validation is broken, but doesn't cause harm
+ size_t uriLen = strlen(requestUri );
+ if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
{
goto exit;
}
- if((request) && (strlen(request) > MAX_REQUEST_LENGTH))
+ if ((request) && (strlen(request) > MAX_REQUEST_LENGTH))
{
result = OC_STACK_INVALID_PARAM;
goto exit;
}
-#ifdef WITH_PRESENCE
- if(method == OC_REST_PRESENCE)
- {
- result = getQueryFromUri(requiredUri, &query, &newUri);
+ /*
+ * Support original behavior with address on resourceUri argument.
+ */
+ adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
+ flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
- if(result != OC_STACK_OK)
- {
- OC_LOG_V(ERROR, TAG, "Invalid Param from getQueryFromUri: %d, URI is %s",
- result, requiredUri);
- goto exit;
- }
+ result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
+ if (result != OC_STACK_OK)
+ {
+ OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
+ goto exit;
+ }
- if(query)
- {
- result = getResourceType((char *) query, &resourceType);
- OICFree(query);
- if(resourceType)
- {
- OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType);
- }
- else
- {
- OC_LOG(DEBUG, TAG, PCF("Resource type is NULL."));
- }
- }
- else
- {
- OC_LOG(DEBUG, TAG, PCF("Query string is NULL."));
- }
- if(result != OC_STACK_OK)
+ switch (method)
+ {
+ case OC_REST_GET:
+ case OC_REST_OBSERVE:
+ case OC_REST_OBSERVE_ALL:
+ case OC_REST_CANCEL_OBSERVE:
+ requestInfo.method = CA_GET;
+ break;
+ case OC_REST_PUT:
+ requestInfo.method = CA_PUT;
+ break;
+ case OC_REST_POST:
+ requestInfo.method = CA_POST;
+ break;
+ case OC_REST_DELETE:
+ requestInfo.method = CA_DELETE;
+ break;
+ case OC_REST_DISCOVER:
+ qos = OC_LOW_QOS;
+ if (!destination && !devAddr)
{
- goto exit;
+ destination = &tmpDevAddr;
}
+ // CA_DISCOVER will become GET and isMulticast
+ requestInfo.method = CA_GET;
+ requestInfo.isMulticast = true;
+ break;
+ #ifdef WITH_PRESENCE
+ case OC_REST_PRESENCE:
+ // Replacing method type with GET because "presence"
+ // is a stack layer only implementation.
+ requestInfo.method = CA_GET;
+ break;
+ #endif
+ default:
+ result = OC_STACK_INVALID_METHOD;
+ goto exit;
}
-#endif // WITH_PRESENCE
- requestUri = (char *) OICMalloc(uriLen + 1);
- if(requestUri)
+ if (!devAddr && !destination)
{
- OICStrcpy(requestUri, uriLen + 1, newUri);
+ OC_LOG_V(DEBUG, TAG, "no devAddr and no destination");
+ result = OC_STACK_INVALID_PARAM;
+ goto exit;
}
- else
+
+ /* If not original behavior, use destination argument */
+ if (destination && !devAddr)
{
- result = OC_STACK_NO_MEMORY;
- goto exit;
+ devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
+ if (!devAddr)
+ {
+ result = OC_STACK_NO_MEMORY;
+ goto exit;
+ }
+ *devAddr = *destination;
}
resHandle = GenerateInvocationHandle();
- if(!resHandle)
+ if (!resHandle)
{
result = OC_STACK_NO_MEMORY;
goto exit;
}
- // create token
caResult = CAGenerateToken(&token, tokenLength);
if (caResult != CA_STATUS_OK)
{
OC_LOG(ERROR, TAG, PCF("CAGenerateToken error"));
- CADestroyToken(token);
- result = CAResultToOCResult (caResult);
goto exit;
}
- requestData.type = qualityOfServiceToMessageType(qos);
-
- requestData.token = token;
- requestData.tokenLength = tokenLength;
-
+ // fill in request data
+ requestInfo.info.type = qualityOfServiceToMessageType(qos);
+ requestInfo.info.token = token;
+ requestInfo.info.tokenLength = tokenLength;
+ requestInfo.info.resourceUri = resourceUri;
+ requestInfo.info.payload = (char *)request;
if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
{
- result = CreateObserveHeaderOption (&(requestData.options), options,
- numOptions, OC_OBSERVE_REGISTER);
+ result = CreateObserveHeaderOption (&(requestInfo.info.options),
+ options, numOptions, OC_OBSERVE_REGISTER);
if (result != OC_STACK_OK)
{
- CADestroyToken(token);
goto exit;
}
- requestData.numOptions = numOptions + 1;
+ hdrOptionMemAlloc = 1;
+ requestInfo.info.numOptions = numOptions + 1;
}
else
{
- requestData.options = (CAHeaderOption_t*)options;
- requestData.numOptions = numOptions;
+ requestInfo.info.options = (CAHeaderOption_t*)options;
+ requestInfo.info.numOptions = numOptions;
}
- requestData.payload = (char *)request;
-
- requestInfo.info = requestData;
-
- CATransportType_t caConType;
-
- result = OCToCATransportType((OCConnectivityType) conType, &caConType);
+ // create remote endpoint
+ result = OCCreateEndpoint(devAddr, &endpoint);
if (result != OC_STACK_OK)
{
- OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type"));
+ OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
goto exit;
}
- // send request
- if(conType == OC_ALL)
- {
- grpEnd.transportType = caConType;
-
- grpEnd.resourceUri = (CAURI_t) OICMalloc(uriLen + 1);
- if(!grpEnd.resourceUri)
- {
- result = OC_STACK_NO_MEMORY;
- CADestroyToken(token);
- goto exit;
- }
- OICStrcpy(grpEnd.resourceUri, uriLen +1, requiredUri);
-
- caResult = CASendRequestToAll(&grpEnd, &requestInfo);
- }
- else
+ // prepare for response
+ #ifdef WITH_PRESENCE
+ if (method == OC_REST_PRESENCE)
{
- caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint);
-
- if (caResult != CA_STATUS_OK)
+ char *presenceUri = NULL;
+ result = OCPreparePresence(endpoint, resourceUri, &presenceUri);
+ if (OC_STACK_OK != result)
{
- OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
- result = CAResultToOCResult (caResult);
- CADestroyToken(token);
goto exit;
}
-
- caResult = CASendRequest(endpoint, &requestInfo);
+ OICFree(resourceUri);
+ resourceUri = presenceUri;
}
+ #endif
- if (caResult != CA_STATUS_OK)
+ ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
+ result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
+ method, devAddr, resourceUri, resourceType, ttl);
+ if (OC_STACK_OK != result)
{
- OC_LOG(ERROR, TAG, PCF("CASendRequest"));
- result = CAResultToOCResult (caResult);
- CADestroyToken(token);
goto exit;
}
- result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle, method,
- requestUri, resourceType, conType,
- GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND));
- if(result != OC_STACK_OK)
+ devAddr = NULL; // Client CB list entry now owns it
+ resourceUri = NULL; // Client CB list entry now owns it
+ resourceType = NULL; // Client CB list entry now owns it
+
+ // send request
+ caResult = CASendRequest(endpoint, &requestInfo);
+ if (caResult != CA_STATUS_OK)
{
- result = OC_STACK_NO_MEMORY;
+ OC_LOG(ERROR, TAG, PCF("CASendRequest"));
+ result = OC_STACK_COMM_ERROR;
goto exit;
}
- if(handle)
+ if (handle)
{
*handle = resHandle;
}
exit:
- if(newUri != requiredUri)
- {
- OICFree(newUri);
- }
if (result != OC_STACK_OK)
{
- OC_LOG_V(ERROR, TAG, PCF("OCDoResource error no %d"), result);
+ OC_LOG(ERROR, TAG, PCF("OCDoResource error"));
FindAndDeleteClientCB(clientCB);
+ CADestroyToken(token);
+ if (handle)
+ {
+ *handle = NULL;
+ }
OICFree(resHandle);
- OICFree(requestUri);
- OICFree(resourceType);
}
- CADestroyRemoteEndpoint(endpoint);
- OICFree(grpEnd.resourceUri);
-
- if (requestData.options && requestData.numOptions > 0)
+ OICFree(devAddr);
+ OICFree(resourceUri);
+ OICFree(resourceType);
+ OICFree(endpoint);
+ if (hdrOptionMemAlloc)
{
- if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
- {
- OICFree(requestData.options);
- }
+ OICFree(requestInfo.info.options);
}
return result;
}
* Remove the callback associated on client side.
*/
OCStackResult ret = OC_STACK_OK;
- CARemoteEndpoint_t* endpoint = NULL;
+ CAEndpoint_t* endpoint = NULL;
CAResult_t caResult;
CAInfo_t requestData = {};
CARequestInfo_t requestInfo = {};
OC_LOG(INFO, TAG, PCF("Entering OCCancel"));
ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
+ if (!clientCB)
+ {
+ OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
+ goto Error;
+ }
- if(clientCB)
+ switch (clientCB->method)
{
- switch (clientCB->method)
- {
- case OC_REST_OBSERVE:
- case OC_REST_OBSERVE_ALL:
- if(qos == OC_HIGH_QOS)
- {
- requestData.type = qualityOfServiceToMessageType(qos);
- requestData.token = clientCB->token;
- requestData.tokenLength = clientCB->tokenLength;
+ case OC_REST_OBSERVE:
+ case OC_REST_OBSERVE_ALL:
+ OC_LOG(INFO, TAG, PCF("Canceling observation"));
+ if (qos != OC_HIGH_QOS)
+ {
+ FindAndDeleteClientCB(clientCB);
+ break;
+ }
- if (CreateObserveHeaderOption (&(requestData.options),
- options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
- {
- return OC_STACK_ERROR;
- }
- requestData.numOptions = numOptions + 1;
- requestInfo.method = CA_GET;
- requestInfo.info = requestData;
+ requestData.type = qualityOfServiceToMessageType(qos);
+ requestData.token = clientCB->token;
+ requestData.tokenLength = clientCB->tokenLength;
+ if (CreateObserveHeaderOption (&(requestData.options),
+ options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
+ {
+ return OC_STACK_ERROR;
+ }
+ requestData.numOptions = numOptions + 1;
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
- CATransportType_t caConType;
- ret = OCToCATransportType(clientCB->conType, &caConType);
- if(ret != OC_STACK_OK)
- {
- goto Error;
- }
+ ret = OCCreateEndpoint(clientCB->devAddr, &endpoint);
+ if (ret != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
+ goto Error;
+ }
- caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri,
- caConType, &endpoint);
- if (caResult != CA_STATUS_OK)
- {
- OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
- ret = OC_STACK_ERROR;
- goto Error;
- }
+ // send request
+ caResult = CASendRequest(endpoint, &requestInfo);
+ if (caResult != CA_STATUS_OK)
+ {
+ OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
+ ret = OC_STACK_ERROR;
+ }
+ ret = CAResultToOCResult (caResult);
+ break;
- // send request
- caResult = CASendRequest(endpoint, &requestInfo);
- if (caResult != CA_STATUS_OK)
- {
- OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
- ret = OC_STACK_ERROR;
- }
- ret = CAResultToOCResult (caResult);
- }
- else
- {
- FindAndDeleteClientCB(clientCB);
- }
- break;
+ #ifdef WITH_PRESENCE
+ case OC_REST_PRESENCE:
+ FindAndDeleteClientCB(clientCB);
+ break;
+ #endif
- #ifdef WITH_PRESENCE
- case OC_REST_PRESENCE:
- FindAndDeleteClientCB(clientCB);
- break;
- #endif
- default:
- ret = OC_STACK_INVALID_METHOD;
- break;
- }
- }
- else
- {
- OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?"));
+ default:
+ ret = OC_STACK_INVALID_METHOD;
+ break;
}
- Error:
- CADestroyRemoteEndpoint(endpoint);
+Error:
+ OCDestroyEndpoint(endpoint);
if (requestData.numOptions > 0)
{
OICFree(requestData.options);
}
#ifdef WITH_PRESENCE
+
OCStackResult OCProcessPresence()
{
OCStackResult result = OC_STACK_OK;
- uint8_t ipAddr[4] = { 0 };
- uint16_t port = 0;
- OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
+ // the following line floods the log with messages that are irrelevant
+ // to most purposes. Uncomment as needed.
+ //OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
ClientCB* cbNode = NULL;
- OCDevAddr dst = {};
- OCClientResponse clientResponse ={};
+ OCClientResponse clientResponse;
OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
LL_FOREACH(cbList, cbNode)
{
- if(OC_REST_PRESENCE == cbNode->method)
+ if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
{
- if(cbNode->presence)
- {
- uint32_t now = GetTicks(0);
- OC_LOG_V(DEBUG, TAG, "this TTL level %d",
- cbNode->presence->TTLlevel);
- OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
+ continue;
+ }
+ uint32_t now = GetTicks(0);
+ OC_LOG_V(DEBUG, TAG, "this TTL level %d",
+ cbNode->presence->TTLlevel);
+ OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
- if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
- {
- goto exit;
- }
+ if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
+ {
+ goto exit;
+ }
- 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_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"));
- if (ParseIPv4Address(cbNode->requestUri, ipAddr, &port))
- {
- OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
- &dst);
-
- clientResponse.sequenceNumber = 0;
- clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
- clientResponse.addr = (OCDevAddr *) &dst;
- clientResponse.resJSONPayload = NULL;
-
- // 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",
- cbNode->presence->TTLlevel);
- }
- else
- {
- result = OC_STACK_INVALID_IP;
- goto exit;
- }
+ if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
+ {
+ OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
- cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
- if (cbResult == OC_STACK_DELETE_TRANSACTION)
- {
- FindAndDeleteClientCB(cbNode);
- }
- }
+ clientResponse.sequenceNumber = 0;
+ clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
+ clientResponse.devAddr = *cbNode->devAddr;
+ FixUpClientResponse(&clientResponse);
+ clientResponse.resJSONPayload = NULL;
- if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
- {
- CAResult_t caResult = CA_STATUS_OK;
- CARemoteEndpoint_t* endpoint = NULL;
- CAInfo_t requestData ={};
- CARequestInfo_t requestInfo = {};
+ // 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",
+ cbNode->presence->TTLlevel);
+
+ cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
+ if (cbResult == OC_STACK_DELETE_TRANSACTION)
+ {
+ FindAndDeleteClientCB(cbNode);
+ }
+ }
- OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
+ if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
+ {
+ continue;
+ }
+ CAResult_t caResult = CA_STATUS_OK;
+ CAEndpoint_t* endpoint = NULL;
+ CAInfo_t requestData ={};
+ CARequestInfo_t requestInfo = {};
- CATransportType_t caConType;
- result = OCToCATransportType(cbNode->conType, &caConType);
- caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, caConType,
- &endpoint);
- if (caResult != CA_STATUS_OK || result != OC_STACK_OK)
- {
- OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error"));
- goto exit;
- }
+ OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
- requestData.type = CA_MSG_NONCONFIRM;
- requestData.token = cbNode->token;
- requestData.tokenLength = cbNode->tokenLength;
- requestInfo.method = CA_GET;
- requestInfo.info = requestData;
+ result = OCCreateEndpoint(cbNode->devAddr, &endpoint);
+ if (result != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, PCF("CACreateEndpoint error"));
+ goto exit;
+ }
- caResult = CASendRequest(endpoint, &requestInfo);
- CADestroyRemoteEndpoint(endpoint);
+ requestData.type = CA_MSG_NONCONFIRM;
+ requestData.token = cbNode->token;
+ requestData.tokenLength = cbNode->tokenLength;
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
- if (caResult != CA_STATUS_OK)
- {
- OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
- goto exit;
- }
+ caResult = CASendRequest(endpoint, &requestInfo);
+ OCDestroyEndpoint(endpoint);
- cbNode->presence->TTLlevel++;
- OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
- cbNode->presence->TTLlevel);
- }
- }
+ if (caResult != CA_STATUS_OK)
+ {
+ OC_LOG(ERROR, TAG, PCF("CASendRequest error"));
+ goto exit;
}
+
+ cbNode->presence->TTLlevel++;
+ OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
}
exit:
if (result != OC_STACK_OK)
{
- OC_LOG_V(ERROR, TAG, PCF("OCProcessPresence error no %d"), result);
+ OC_LOG(ERROR, TAG, PCF("OCProcessPresence error"));
}
return result;
}
{
presenceState = OC_PRESENCE_INITIALIZED;
- CAAddress_t addressInfo;
- OICStrcpy(addressInfo.IP.ipAddress, sizeof(addressInfo.IP.ipAddress),
- OC_MULTICAST_IP);
- addressInfo.IP.port = OC_MULTICAST_PORT;
+ OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
+ OICStrcpy(devAddr.addr, sizeof(devAddr.addr), OC_MULTICAST_IP);
+ devAddr.port = OC_MULTICAST_PORT;
CAToken_t caToken = NULL;
CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
return OC_STACK_ERROR;
}
- CATransportType_t connType;
- OCToCATransportType(OC_ALL, &connType );
AddObserver(OC_PRESENCE_URI, NULL, 0, caToken, tokenLength,
- (OCResource *)presenceResource.handle, OC_LOW_QOS,
- &addressInfo, connType);
+ (OCResource *)presenceResource.handle, OC_LOW_QOS, &devAddr);
CADestroyToken(caToken);
}
return result;
}
-OCStackResult getResourceType(const char * query, char** resourceType)
-{
- if(!query)
- {
- return OC_STACK_INVALID_PARAM;
- }
-
- OCStackResult result = OC_STACK_ERROR;
-
- if(strncmp(query, "rt=", 3) == 0)
- {
- *resourceType = OICStrdup(&query[3]);
- if(!*resourceType)
- {
- result = OC_STACK_NO_MEMORY;
- }
- else
- {
- result = OC_STACK_OK;
- }
- }
-
- return result;
-}
-
/*
* This function splits the uri using the '?' delimiter.
* "uriWithoutQuery" is the block of characters between the beginning
}
OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
}
- else
- {
- return OC_STACK_INVALID_PARAM;
- }
-
if (queryLen)
{
*query = (char *) OICCalloc(queryLen + 1, 1);
return sidStr;
}
-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, PCF("Invalid argument"));
- return OC_STACK_INVALID_PARAM;
- }
-
- *a = ipAddr->addr[0];
- *b = ipAddr->addr[1];
- *c = ipAddr->addr[2];
- *d = ipAddr->addr[3];
-
- return OC_STACK_OK;
-}
-
-int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
-{
- if ( !ipAddr || !port )
- {
- OC_LOG(FATAL, TAG, PCF("Invalid argument"));
- return OC_STACK_INVALID_PARAM;
- }
-
- *port = (ipAddr->addr[5]<< 8) | ipAddr->addr[4];
-
- return OC_STACK_OK;
-}
-
CAResult_t OCSelectNetwork()
{
CAResult_t retResult = CA_STATUS_FAILED;
CAResult_t caResult = CA_STATUS_OK;
- CATransportType_t connTypes[] = {
- CA_IPV4,
- CA_EDR,
- CA_LE};
+ CATransportAdapter_t connTypes[] = {
+ CA_ADAPTER_IP,
+ CA_ADAPTER_RFCOMM_BTEDR,
+ CA_ADAPTER_GATT_BTLE};
int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
for(int i = 0; i<numConnTypes; i++)
cbdata.cd = NULL;
cbdata.context = (void*)DEFAULT_CONTEXT_VALUE;
-// TODO: Selecting OC_IPV4.
-// It is temporary change as OC_ALL is not working currently. Remove this code and use OC_ALL
-// once it is functioning.
-
return OCDoResource(handle, OC_REST_PUT, targetUri,
- NULL, (char *) action, OC_IPV4, OC_NA_QOS, &cbdata, NULL, 0);
+ NULL, (char *) action, CT_ADAPTER_IP, OC_NA_QOS, &cbdata, NULL, 0);
}
OCStackResult DoAction(OCResource* resource, OCActionSet* actionset,
// This is a function called back when a device is discovered
OCStackApplicationResult applicationDiscoverCB(
OCClientResponse * clientResponse) {
- uint8_t remoteIpAddr[4];
- uint16_t remotePortNu;
OC_LOG(INFO, TAG, "Entering applicationDiscoverCB (Application Layer CB)");
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
- remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
- OC_LOG_V(INFO, TAG, "Device =============> Discovered %s @ %d.%d.%d.%d:%d",clientResponse->resJSONPayload,remoteIpAddr[0], remoteIpAddr[1], remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
+ OC_LOG_V(INFO, TAG, "Device =============> Discovered %s @ %s:%d",
+ clientResponse->resJSONPayload,
+ clientResponse->devAddr.addr,
+ clientResponse->devAddr.port);
//return OC_STACK_DELETE_TRANSACTION;
return OC_STACK_KEEP_TRANSACTION;
}
szQueryUri,
0,
0,
- OC_IPV4,
+ CT_ADAPTER_IP,
OC_LOW_QOS,
&cbData,
NULL,
szQueryUri,
0,
0,
- OC_IPV4,
+ CT_ADAPTER_IP,
OC_LOW_QOS,
&cbData,
NULL,
std::string platformDiscoveryURI = "/oic/p";
std::string deviceDiscoveryURI = "/oic/d";
- OCConnectivityType connectivityType = OC_IPV4;
+ OCConnectivityType connectivityType = CT_ADAPTER_IP;
if(argc == 2)
{
{
if(optionSelected == 0)
{
- connectivityType = OC_IPV4;
- }
- else if(optionSelected == 1)
- {
- // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
- //connectivityType = OC_IPV6;
- connectivityType = OC_IPV4;
- std::cout << "IPv6 not currently supported. Using default IPv4" << std::endl;
+ connectivityType = CT_ADAPTER_IP;
}
else
{
- std::cout << "Invalid connectivity type selected. Using default IPv4"
+ std::cout << "Invalid connectivity type selected. Using default IP"
<< std::endl;
}
}
else
{
- std::cout << "Invalid connectivity type selected. Using default IPv4" << std::endl;
+ std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
}
}
catch(std::exception&)
{
- std::cout << "Invalid input argument. Using IPv4 as connectivity type" << std::endl;
+ std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
}
}
else
{
- std::cout << "Usage devicediscoveryclient <connectivityType(0|1)>" << std::endl;
- std::cout << "connectivityType: Default IPv4" << std::endl;
- std::cout << "connectivityType 0: IPv4" << std::endl;
- std::cout << "connectivityType 1: IPv6 (not currently supported)" << std::endl;
+ std::cout << "Usage devicediscoveryclient 0" << std::endl;
+ std::cout << "connectivityType: Default IP" << std::endl;
+ std::cout << "connectivityType 0: IP" << std::endl;
}
// Create PlatformConfig object
PlatformConfig cfg {
std::cout << "Fridge Client has started " <<std::endl;
FindCallback f (std::bind(&ClientFridge::foundDevice, this, PH::_1));
OCStackResult result = OCPlatform::findResource(
- "", requestURI.str(), OC_ALL, f);
+ "", requestURI.str(), CT_DEFAULT, f);
if(OC_STACK_OK != result)
{
int main(int argc, char* argv[])
{
- OCConnectivityType connectivityType = OC_IPV4;
+ OCConnectivityType connectivityType = CT_ADAPTER_IP;
if(argc == 2)
{
try
{
if(optionSelected == 0)
{
- connectivityType = OC_IPV4;
- }
- else if(optionSelected == 1)
- {
- // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
- //connectivityType = OC_IPV6;
- connectivityType = OC_IPV4;
- std::cout << "IPv6 not currently supported. Using default IPv4" << std::endl;
+ connectivityType = CT_ADAPTER_IP;
}
else
{
- std::cout << "Invalid connectivity type selected. Using default IPv4"
+ std::cout << "Invalid connectivity type selected. Using default IP"
<< std::endl;
}
}
else
{
- std::cout << "Invalid connectivity type selected. Using default IPv4" << std::endl;
+ std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
}
}
catch(std::exception&)
{
- std::cout << "Invalid input argument. Using IPv4 as connectivity type" << std::endl;
+ std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
}
}
else
{
- std::cout << "Usage: fridgeclient <ConnectivityType(0|1)>\n";
- std::cout << "connectivityType: Default IPv4" << std::endl;
- std::cout << "connectivityType 0: IPv4" << std::endl;
- std::cout << "connectivityType 1: IPv6 (not currently supported)" << std::endl;
+ std::cout << "Usage: fridgeclient 0\n";
+ std::cout << "connectivityType: Default IP" << std::endl;
+ std::cout << "connectivityType 0: IP" << std::endl;
}
PlatformConfig cfg
std::ostringstream requestURI;
+ OCConnectivityType connectivityType = CT_DEFAULT;
+
+ if(argc == 2)
+ {
+ try
+ {
+ std::size_t inputValLen;
+ int optionSelected = std::stoi(argv[1], &inputValLen);
+
+ if(inputValLen == strlen(argv[1]))
+ {
+ if(optionSelected == 0)
+ {
+ connectivityType = CT_ADAPTER_IP;
+ }
+ else
+ {
+ std::cout << "Invalid connectivity type selected. Using default IP"
+ << std::endl;
+ }
+ }
+ else
+ {
+ std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
+ }
+ }
+ catch(std::exception& e)
+ {
+ std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
+ }
+ }
+ else
+ {
+ std::cout<<"Usage: garageclient 0\n";
+ std::cout<<"ConnectivityType: Default IP\n";
+ std::cout<<"ConnectivityType 0: IP\n";
+ }
+
// Create PlatformConfig object
PlatformConfig cfg {
OC::ServiceType::InProc,
requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.garage";
OCPlatform::findResource("", requestURI.str(),
- OC_ALL, &foundResource);
+ connectivityType, &foundResource);
std::cout<< "Finding Resource... " <<std::endl;
string resourceTypeName = "a.collection";
OCPlatform::findResource("", requestURI.str(),
- OC_ALL, &foundResource);
+ CT_DEFAULT, &foundResource);
//Non-intensive block until foundResource callback is called by OCPlatform
//and onGet gets resource.
{
ostringstream requestURI;
+ OCConnectivityType connectivityType = CT_DEFAULT;
+
+ if(argc == 2)
+ {
+ try
+ {
+ std::size_t inputValLen;
+ int optionSelected = stoi(argv[1], &inputValLen);
+
+ if(inputValLen == strlen(argv[1]))
+ {
+ if(optionSelected == 0)
+ {
+ connectivityType = CT_ADAPTER_IP;
+ }
+ else
+ {
+ std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
+ }
+ }
+ else
+ {
+ std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
+ }
+ }
+ catch(exception& e)
+ {
+ std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
+ }
+ }
+ else
+ {
+ std::cout<<"Usage: groupclient 0\n";
+ std::cout<<"ConnectivityType: Default \n";
+ std::cout<<"ConnectivityType 0: IP\n";
+ }
+
PlatformConfig config
{ OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.light";
OCPlatform::findResource("", requestURI.str(),
- OC_ALL, &foundResource);
+ connectivityType, &foundResource);
OCPlatform::bindInterfaceToResource(resourceHandle, GROUP_INTERFACE);
OCPlatform::bindInterfaceToResource(resourceHandle, DEFAULT_INTERFACE);
std::mutex resourceLock;
static int TEST_CASE = 0;
-static OCConnectivityType connectivityType = OC_IPV4;
+static OCConnectivityType connectivityType = CT_ADAPTER_IP;
/**
* List of methods that can be inititated from the client
{
if(optionSelected == 0)
{
- connectivityType = OC_IPV4;
- }
- else if(optionSelected == 1)
- {
- // TODO: re-enable IPv4/IPv6 command line selection when IPv6
- // is supported
- //connectivityType = OC_IPV6;
- connectivityType = OC_IPV4;
- std::cout << "IPv6 not currently supported. Using default IPv4"
- << std::endl;
+ connectivityType = CT_ADAPTER_IP;
}
else
{
- std::cout << "Invalid connectivity type selected. Using default IPv4"
+ std::cout << "Invalid connectivity type selected. Using default IP"
<< std::endl;
}
}
else
{
- std::cout << "Invalid connectivity type selected. Using default IPv4"
+ std::cout << "Invalid connectivity type selected. Using default IP"
<< std::endl;
}
break;
}
catch(std::exception& )
{
- std::cout << "Invalid input argument. Using IPv4 as connectivity type"
+ std::cout << "Invalid input argument. Using IP as connectivity type"
<< std::endl;
}
requestURI << OC_MULTICAST_DISCOVERY_URI;
result = OCPlatform::findResource("", requestURI.str(),
- OC_ALL, &foundResource);
+ CT_DEFAULT, &foundResource);
if(result == OC_STACK_OK)
{
std::cout << "Finding Resource... " << std::endl;
}
catch(std::exception& e)
{
- std::cerr << "Exception in foundResource: "<< e.what() <<std::endl;
//log(e.what());
}
}
std::ostringstream requestURI;
+ OCConnectivityType connectivityType = CT_DEFAULT;
+ if(argc == 2)
+ {
+ try
+ {
+ std::size_t inputValLen;
+ int optionSelected = std::stoi(argv[1], &inputValLen);
+
+ if(inputValLen == strlen(argv[1]))
+ {
+ if(optionSelected == 0)
+ {
+ connectivityType = CT_ADAPTER_IP;
+ }
+ else
+ {
+ std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
+ }
+ }
+ else
+ {
+ std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
+ }
+ }
+ catch(std::exception& e)
+ {
+ std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
+ }
+ }
+ else
+ {
+ std::cout << "Usage roomclient 0" << std::endl;
+ std::cout<<"connectivityType: Default" << std::endl;
+ std::cout << "connectivityType 0: IP" << std::endl;
+ }
// Create PlatformConfig object
PlatformConfig cfg {
// Find all resources
requestURI << OC_MULTICAST_DISCOVERY_URI;
- OCPlatform::findResource("", requestURI.str(), OC_ALL, &foundResource);
+ OCPlatform::findResource("", requestURI.str(), connectivityType, &foundResource);
std::cout<< "Finding Resource... " <<std::endl;
// A condition variable will free the mutex it is given, then do a non-
printUsage();
if (argc == 1)
{
- std::cout << "<===Setting ObserveType to Observe and ConnectivityType to IPv4===>\n\n";
+ std::cout << "<===Setting ObserveType to Observe and ConnectivityType to IP===>\n\n";
}
else if (argc == 2)
{
requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.light";
OCPlatform::findResource("", requestURI.str(),
- OC_ALL, &foundResource);
+ CT_DEFAULT, &foundResource);
std::cout<< "Finding Resource... " <<std::endl;
// Find resource is done twice so that we discover the original resources a second time.
// These resources will have the same uniqueidentifier (yet be different objects), so that
// we can verify/show the duplicate-checking code in foundResource(above);
OCPlatform::findResource("", requestURI.str(),
- OC_ALL, &foundResource);
+ CT_DEFAULT, &foundResource);
std::cout<< "Finding Resource for second time..." << std::endl;
// A condition variable will free the mutex it is given, then do a non-
void PrintUsage()
{
std::cout << std::endl;
- std::cout << "Usage : simpleclientHQ <ObserveType>" << std::endl;
+ std::cout << "Usage : simpleclientHQ <ObserveType> <ConnectivityType>" << std::endl;
std::cout << " ObserveType : 1 - Observe" << std::endl;
std::cout << " ObserveType : 2 - ObserveAll" << std::endl;
+ std::cout << " ConnectivityType: Default IP" << std::endl;
+ std::cout << " ConnectivityType : 0 - IP"<< std::endl;
}
int main(int argc, char* argv[]) {
std::ostringstream requestURI;
+ OCConnectivityType connectivityType = CT_DEFAULT;
try
{
if (argc == 1)
{
OBSERVE_TYPE_TO_USE = ObserveType::Observe;
}
- else if (argc == 2)
+ else if (argc ==2 || argc==3)
{
int value = std::stoi(argv[1]);
if (value == 1)
- {
OBSERVE_TYPE_TO_USE = ObserveType::Observe;
- }
else if (value == 2)
- {
OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll;
- }
else
- {
OBSERVE_TYPE_TO_USE = ObserveType::Observe;
+
+ if(argc == 3)
+ {
+ std::size_t inputValLen;
+ int optionSelected = std::stoi(argv[2], &inputValLen);
+
+ if(inputValLen == strlen(argv[2]))
+ {
+ if(optionSelected == 0)
+ {
+ connectivityType = CT_ADAPTER_IP;
+ }
+ else
+ {
+ std::cout << "Invalid connectivity type selected. Using default IP"
+ << std::endl;
+ }
+ }
+ else
+ {
+ std::cout << "Invalid connectivity type selected. Using default IP"
+ << std::endl;
+ }
}
}
else
return -1;
}
}
- catch(std::exception&)
+ catch(std::exception& e)
{
- std::cout << "Invalid input argument. Using Observe as observe type" << std::endl;
+ std::cout << "Invalid input argument." << std::endl;
}
+
// Create PlatformConfig object
PlatformConfig cfg {
OC::ServiceType::InProc,
requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.light";
OCPlatform::findResource("", requestURI.str(),
- OC_ALL, &foundResource, OC::QualityOfService::LowQos);
+ connectivityType, &foundResource, OC::QualityOfService::LowQos);
std::cout<< "Finding Resource... " <<std::endl;
// Find resource is done twice so that we discover the original resources a second time.
// These resources will have the same uniqueidentifier (yet be different objects), so that
// we can verify/show the duplicate-checking code in foundResource(above);
OCPlatform::findResource("", requestURI.str(),
- OC_ALL, &foundResource, OC::QualityOfService::LowQos);
+ connectivityType, &foundResource, OC::QualityOfService::LowQos);
std::cout<< "Finding Resource for second time... " <<std::endl;
// A condition variable will free the mutex it is given, then do a non-
std::cout<<"Starting Client find:"<<std::endl;
FindCallback f (std::bind(&ClientWorker::foundResource, this, std::placeholders::_1));
std::cout<<"result:" <<
- OCPlatform::findResource("", requestURI.str(), OC_ALL, f)
+ OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, f)
<< std::endl;
std::cout<<"Finding Resource..."<<std::endl;
int main(int argc, char* argv[])
{
- OCConnectivityType connectivityType = OC_IPV4;
+ OCConnectivityType connectivityType = CT_ADAPTER_IP;
if(argc == 2)
{
{
if(optionSelected == 0)
{
- connectivityType = OC_IPV4;
- }
- else if(optionSelected == 1)
- {
- // TODO: re-enable IPv4/IPv6 command line selection when IPv6 is supported
- // connectivityType = OC_IPV6;
- connectivityType = OC_IPV4;
- std::cout << "IPv6 not currently supported. Using default IPv4" << std::endl;
+ connectivityType = CT_ADAPTER_IP;
}
else
{
- std::cout << "Invalid connectivity type selected. Using default IPv4"
- << std::endl;
+ std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
}
}
else
{
- std::cout << "Invalid connectivity type selected. Using default IPv4" << std::endl;
+ std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
}
}
catch(std::exception& )
{
- std::cout << "Invalid input argument. Using IPv4 as connectivity type" << std::endl;
+ std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
}
}
else
{
- std::cout<< "Usage simpleclientserver <ConnectivityType(0|1)>" << std::endl;
- std::cout<< " ConnectivityType: Default IPv4" << std::endl;
- std::cout << " ConnectivityType : 0 - IPv4" << std::endl;
- std::cout << " ConnectivityType : 1 - IPv6 (not currently supported)" << std::endl;
+ std::cout<< "Usage simpleclientserver 0>" << std::endl;
+ std::cout<< " ConnectivityType: Default IP" << std::endl;
+ std::cout << " ConnectivityType : 0 - IP" << std::endl;
}
PlatformConfig cfg {
{
std::cout << "in client1\n";
std::cout<<"result1:" << OCPlatform::findResource("", requestURI.str(),
- OC_ALL, foundResource1)<< std::endl;
+ CT_DEFAULT, foundResource1)<< std::endl;
// A condition variable will free the mutex it is given, then do a non-
// intensive block until 'notify' is called on it. In this case, since we
std::cout << "in client2\n";
std::cout<<"result2:" << OCPlatform::findResource("",
requestURI.str(),
- OC_ALL, foundResource2)<< std::endl;
+ CT_DEFAULT, foundResource2)<< std::endl;
// A condition variable will free the mutex it is given, then do a non-
// intensive block until 'notify' is called on it. In this case, since we
{}
virtual OCStackResult ListenForResource(const std::string& serviceUrl,
- const std::string& resourceType, OCConnectivityType connectivityType,
+ const std::string& resourceType,
+ OCConnectivityType connectivityType,
FindCallback& callback,
QualityOfService QoS) = 0;
virtual OCStackResult ListenForDevice(const std::string& serviceUrl,
- const std::string& deviceURI, OCConnectivityType connectivityType,
+ const std::string& deviceURI,
+ OCConnectivityType connectivityType,
FindDeviceCallback& callback,
QualityOfService QoS) = 0;
- virtual OCStackResult GetResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType,
+ virtual OCStackResult GetResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const QueryParamsMap& queryParams,
const HeaderOptions& headerOptions,
GetCallback& callback, QualityOfService QoS)=0;
- virtual OCStackResult PutResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType,
+ virtual OCStackResult PutResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const OCRepresentation& rep, const QueryParamsMap& queryParams,
const HeaderOptions& headerOptions,
PutCallback& callback, QualityOfService QoS) = 0;
- virtual OCStackResult PostResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType,
+ virtual OCStackResult PostResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const OCRepresentation& rep, const QueryParamsMap& queryParams,
const HeaderOptions& headerOptions,
PostCallback& callback, QualityOfService QoS) = 0;
- virtual OCStackResult DeleteResource(const std::string& host, const std::string& uri,
- OCConnectivityType connectivityType, const HeaderOptions& headerOptions,
+ virtual OCStackResult DeleteResource(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
+ const HeaderOptions& headerOptions,
DeleteCallback& callback, QualityOfService QoS) = 0;
- virtual OCStackResult ObserveResource(ObserveType observeType, OCDoHandle* handle,
- const std::string& host, const std::string& uri,
- OCConnectivityType connectivityType, const QueryParamsMap& queryParams,
+ virtual OCStackResult ObserveResource(
+ ObserveType observeType, OCDoHandle* handle,
+ const OCDevAddr& devAddr,
+ const std::string& uri,
+ const QueryParamsMap& queryParams,
const HeaderOptions& headerOptions, ObserveCallback& callback,
QualityOfService QoS)=0;
- virtual OCStackResult CancelObserveResource(OCDoHandle handle, const std::string& host,
- const std::string& uri, const HeaderOptions& headerOptions, QualityOfService QoS)=0;
+ virtual OCStackResult CancelObserveResource(
+ OCDoHandle handle,
+ const std::string& host,
+ const std::string& uri,
+ const HeaderOptions& headerOptions,
+ QualityOfService QoS)=0;
- virtual OCStackResult SubscribePresence(OCDoHandle* handle, const std::string& host,
- const std::string& resourceType, OCConnectivityType connectivityType,
+ virtual OCStackResult SubscribePresence(OCDoHandle* handle,
+ const std::string& host,
+ const std::string& resourceType,
+ OCConnectivityType connectivityType,
SubscribeCallback& presenceHandler)=0;
virtual OCStackResult UnsubscribePresence(OCDoHandle handle) =0;
virtual ~InProcClientWrapper();
virtual OCStackResult ListenForResource(const std::string& serviceUrl,
- const std::string& resourceType, OCConnectivityType connectivityType,
+ const std::string& resourceType, OCConnectivityType transportFlags,
FindCallback& callback, QualityOfService QoS);
virtual OCStackResult ListenForDevice(const std::string& serviceUrl,
- const std::string& deviceURI, OCConnectivityType connectivityType,
+ const std::string& deviceURI, OCConnectivityType transportFlags,
FindDeviceCallback& callback, QualityOfService QoS);
- virtual OCStackResult GetResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType,
+ virtual OCStackResult GetResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
GetCallback& callback, QualityOfService QoS);
- virtual OCStackResult PutResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType,
+ virtual OCStackResult PutResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const OCRepresentation& attributes, const QueryParamsMap& queryParams,
const HeaderOptions& headerOptions, PutCallback& callback, QualityOfService QoS);
- virtual OCStackResult PostResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType,
+ virtual OCStackResult PostResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const OCRepresentation& attributes, const QueryParamsMap& queryParams,
const HeaderOptions& headerOptions, PostCallback& callback, QualityOfService QoS);
- virtual OCStackResult DeleteResource(const std::string& host, const std::string& uri,
- OCConnectivityType connectivityType, const HeaderOptions& headerOptions,
+ virtual OCStackResult DeleteResource(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
+ const HeaderOptions& headerOptions,
DeleteCallback& callback, QualityOfService QoS);
- virtual OCStackResult ObserveResource(ObserveType observeType, OCDoHandle* handle,
- const std::string& host, const std::string& uri, OCConnectivityType connectivityType,
+ virtual OCStackResult ObserveResource(
+ ObserveType observeType, OCDoHandle* handle,
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
ObserveCallback& callback, QualityOfService QoS);
- virtual OCStackResult CancelObserveResource(OCDoHandle handle, const std::string& host,
- const std::string& uri, const HeaderOptions& headerOptions, QualityOfService QoS);
-
- virtual OCStackResult SubscribePresence(OCDoHandle* handle, const std::string& host,
- const std::string& resourceType, OCConnectivityType connectivityType,
+ virtual OCStackResult CancelObserveResource(
+ OCDoHandle handle,
+ const std::string& host,
+ const std::string& uri,
+ const HeaderOptions& headerOptions, QualityOfService QoS);
+
+ virtual OCStackResult SubscribePresence(
+ OCDoHandle *handle,
+ const std::string& host,
+ const std::string& resourceType,
+ OCConnectivityType transportFlags,
SubscribeCallback& presenceHandler);
virtual OCStackResult UnsubscribePresence(OCDoHandle handle);
* Data structure to provide the configuration.
* ServiceType: indicate InProc or OutOfProc
* ModeType : indicate whether we want to do server, client or both
- * ipAddress : ip address of server.
- * if you specify 0.0.0.0 : it listens on any interface.
- * port : port of server.
- * : if you specify 0 : next available random port is used.
- * : if you specify 5683 : client discovery can work even if they don't specify port.
+ * ServerConnectivity : default flags for server
+ * ClientConnectivity : default flags for client
* QoS : Quality of Service : CONFIRMABLE or NON CONFIRMABLE.
*/
struct PlatformConfig
{
ServiceType serviceType;
ModeType mode;
- std::string ipAddress;
- uint16_t port;
-
+ OCConnectivityType serverConnectivity;
+ OCConnectivityType clientConnectivity;
+ std::string ipAddress; // not used
+ uint16_t port; // not used
QualityOfService QoS;
public:
PlatformConfig()
: serviceType(ServiceType::InProc),
mode(ModeType::Both),
+ serverConnectivity(CT_DEFAULT),
+ clientConnectivity(CT_DEFAULT),
ipAddress("0.0.0.0"),
port(0),
QoS(QualityOfService::NaQos)
{}
PlatformConfig(const ServiceType serviceType_,
const ModeType mode_,
+ OCConnectivityType serverConnectivity_,
+ OCConnectivityType clientConnectivity_,
+ const QualityOfService QoS_)
+ : serviceType(serviceType_),
+ mode(mode_),
+ serverConnectivity(serverConnectivity_),
+ clientConnectivity(clientConnectivity_),
+ ipAddress(""),
+ port(0),
+ QoS(QoS_)
+ {}
+ // for backward compatibility
+ PlatformConfig(const ServiceType serviceType_,
+ const ModeType mode_,
const std::string& ipAddress_,
const uint16_t port_,
const QualityOfService QoS_)
: serviceType(serviceType_),
mode(mode_),
+ serverConnectivity(CT_DEFAULT),
+ clientConnectivity(CT_DEFAULT),
ipAddress(ipAddress_),
port(port_),
QoS(QoS_)
* @param interfaces - a collection of interfaces that the resource supports/implements
* @return OCResource::Ptr - a shared pointer to the new resource object
*/
- OCResource::Ptr constructResourceObject(const std::string& host, const std::string& uri,
+ OCResource::Ptr constructResourceObject(const std::string& host,
+ const std::string& uri,
OCConnectivityType connectivityType, bool isObservable,
const std::vector<std::string>& resourceTypes,
const std::vector<std::string>& interfaces);
/**
* Function to get the connectivity type of this resource
- * @return uint8_t connectivity type
+ * @return enum connectivity type (flags and adapter)
*/
OCConnectivityType connectivityType() const;
std::weak_ptr<IClientWrapper> m_clientWrapper;
std::string m_uri;
OCResourceIdentifier m_resourceId;
- std::string m_host;
- OCConnectivityType m_connectivityType;
+ OCDevAddr m_devAddr;
bool m_isObservable;
bool m_isCollection;
std::vector<std::string> m_resourceTypes;
HeaderOptions m_headerOptions;
private:
- OCResource(std::weak_ptr<IClientWrapper> clientWrapper, const std::string& host,
- const std::string& uri, const std::string& serverId,
- OCConnectivityType m_connectivityType, bool observable,
- const std::vector<std::string>& resourceTypes,
- const std::vector<std::string>& interfaces);
+ OCResource(std::weak_ptr<IClientWrapper> clientWrapper,
+ const OCDevAddr& devAddr, const std::string& uri,
+ const std::string& serverId, bool observable,
+ const std::vector<std::string>& resourceTypes,
+ const std::vector<std::string>& interfaces);
+
+ OCResource(std::weak_ptr<IClientWrapper> clientWrapper,
+ const std::string& host, const std::string& uri,
+ const std::string& serverId,
+ OCConnectivityType connectivityType, bool observable,
+ const std::vector<std::string>& resourceTypes,
+ const std::vector<std::string>& interfaces);
};
} // namespace OC
private:
enum class OCSecureType
{
- IPv4Secure,
- IPv4
+ NotSecure,
+ Secure
};
class ListenResourceContainer
OCSecureType secureType() const
{
- return m_props.m_policy.m_secure?OCSecureType::IPv4Secure :OCSecureType::IPv4;
+ return m_props.m_policy.m_secure ? OCSecureType::Secure : OCSecureType::NotSecure;
}
int port() const
ar(resources);
}
public:
- ListenOCContainer(std::weak_ptr<IClientWrapper> cw, const OCDevAddr& address,
- OCConnectivityType connectivityType, std::stringstream& json):
- m_clientWrapper(cw), m_address(address), m_connectivityType(connectivityType)
+ ListenOCContainer(std::weak_ptr<IClientWrapper> cw,
+ const OCDevAddr& devAddr, std::stringstream& json)
+ : m_clientWrapper(cw), m_devAddr(devAddr)
{
LoadFromJson(json);
}
}
private:
- std::string ConvertOCAddrToString(OCSecureType sec, int secureport)
- {
- uint16_t port;
- std::ostringstream os;
-
- if(sec== OCSecureType::IPv4)
- {
- os<<"coap://";
- }
- else if(sec == OCSecureType::IPv4Secure)
- {
- os<<"coaps://";
- }
- else
- {
- oclog() << "ConvertOCAddrToString(): invalid SecureType"<<std::flush;
- throw ResourceInitException(false, false, false, false, false, true);
- }
-
- uint8_t a;
- uint8_t b;
- uint8_t c;
- uint8_t d;
- if(OCDevAddrToIPv4Addr(&m_address, &a, &b, &c, &d) != 0)
- {
- oclog() << "ConvertOCAddrToString(): Invalid Ip"
- << std::flush;
- throw ResourceInitException(false, false, false, false, false, true);
- }
-
- os<<static_cast<int>(a)<<"."<<static_cast<int>(b)
- <<"."<<static_cast<int>(c)<<"."<<static_cast<int>(d);
-
- if(sec == OCSecureType::IPv4Secure && secureport>0 && secureport<=65535)
- {
- port = static_cast<uint16_t>(secureport);
- }
- else if(sec == OCSecureType::IPv4 && 0==OCDevAddrToPort(&m_address, &port))
- {
- // nothing to do, this is a successful case
- }
- else
- {
- oclog() << "ConvertOCAddrToString() : Invalid Port"
- <<std::flush;
- throw ResourceInitException(false, false, false, false, true, false);
- }
-
- os <<":"<< static_cast<int>(port);
-
- return os.str();
- }
-
void LoadFromJson(std::stringstream& json)
{
cereal::JSONInputArchive archive(json);
if(res.loaded())
{
m_resources.push_back(std::shared_ptr<OCResource>(
- new OCResource(m_clientWrapper,
- ConvertOCAddrToString(res.secureType(),res.port()),
- res.m_uri, res.m_serverId, m_connectivityType, res.observable(),
+ new OCResource(m_clientWrapper, m_devAddr,
+ res.m_uri, res.m_serverId, res.observable(),
res.resourceTypes(), res.interfaces())));
}
}
std::vector<std::shared_ptr<OC::OCResource>> m_resources;
std::weak_ptr<IClientWrapper> m_clientWrapper;
- OCDevAddr m_address;
- OCConnectivityType m_connectivityType;
+ const OCDevAddr& m_devAddr;
};
}
-
{}
virtual OCStackResult ListenForResource(const std::string& serviceUrl,
- const std::string& resourceType, OCConnectivityType connectivityType,
+ const std::string& resourceType,
+ OCConnectivityType connectivityType,
FindCallback& callback, QualityOfService QoS)
{return OC_STACK_NOTIMPL;}
virtual OCStackResult ListenForDevice(const std::string& serviceUrl,
- const std::string& deviceURI, OCConnectivityType connectivityType,
+ const std::string& deviceURI,
+ OCConnectivityType connectivityType,
FindDeviceCallback& callback, QualityOfService QoS)
{return OC_STACK_NOTIMPL;}
QualityOfService QoS)
{return OC_STACK_NOTIMPL;}
- virtual OCStackResult GetResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType,
+ virtual OCStackResult GetResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
GetCallback& callback, QualityOfService QoS)
{return OC_STACK_NOTIMPL;}
- virtual OCStackResult PutResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType,
+ virtual OCStackResult PutResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const OCRepresentation& attributes, const QueryParamsMap& queryParams,
const HeaderOptions& headerOptions, PutCallback& callback,
QualityOfService QoS)
{return OC_STACK_NOTIMPL;}
- virtual OCStackResult PostResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType,
+ virtual OCStackResult PostResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const OCRepresentation& attributes, const QueryParamsMap& queryParams,
const HeaderOptions& headerOptions, PostCallback& callback, QualityOfService QoS)
{return OC_STACK_NOTIMPL;}
- virtual OCStackResult DeleteResource(const std::string& host, const std::string& uri,
- OCConnectivityType connectivityType, const HeaderOptions& headerOptions,
+ virtual OCStackResult DeleteResource(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
+ const HeaderOptions& headerOptions,
DeleteCallback& callback, QualityOfService QoS)
{return OC_STACK_NOTIMPL;}
- virtual OCStackResult ObserveResource(ObserveType observeType, OCDoHandle* handle,
- const std::string& host, const std::string& uri, OCConnectivityType connectivityType,
+ virtual OCStackResult ObserveResource(
+ ObserveType observeType, OCDoHandle* handle,
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
- ObserveCallback& callback, QualityOfService QoS){return OC_STACK_NOTIMPL;}
- virtual OCStackResult CancelObserveResource(OCDoHandle handle, const std::string& host,
+ ObserveCallback& callback, QualityOfService QoS)
+ {return OC_STACK_NOTIMPL;}
+
+ virtual OCStackResult CancelObserveResource(
+ OCDoHandle handle,
+ const std::string& host,
const std::string& uri,
- const HeaderOptions& headerOptions, QualityOfService QoS){return OC_STACK_NOTIMPL;}
- virtual OCStackResult SubscribePresence(OCDoHandle* handle, const std::string& host,
- const std::string& resourceType, OCConnectivityType connectivityType,
+ const HeaderOptions& headerOptions, QualityOfService QoS)
+ {return OC_STACK_NOTIMPL;}
+
+ virtual OCStackResult SubscribePresence(
+ OCDoHandle* handle,
+ const std::string& host,
+ const std::string& resourceType,
+ OCConnectivityType connectivityType,
SubscribeCallback& presenceHandler)
- {return OC_STACK_NOTIMPL;}
- virtual OCStackResult UnsubscribePresence(OCDoHandle handle){return OC_STACK_NOTIMPL;}
+ {return OC_STACK_NOTIMPL;}
- virtual OCStackResult GetDefaultQos(QualityOfService& QoS){return OC_STACK_NOTIMPL;}
+ virtual OCStackResult UnsubscribePresence(OCDoHandle handle)
+ {return OC_STACK_NOTIMPL;}
+
+ virtual OCStackResult GetDefaultQos(QualityOfService& QoS)
+ {return OC_STACK_NOTIMPL;}
};
}
if(m_cfg.mode == ModeType::Client)
{
- OCStackResult result = OCInit(m_cfg.ipAddress.c_str(), m_cfg.port, OC_CLIENT);
+ OCTransportFlags serverFlags =
+ static_cast<OCTransportFlags>(m_cfg.serverConnectivity & CT_MASK_FLAGS);
+ OCTransportFlags clientFlags =
+ static_cast<OCTransportFlags>(m_cfg.clientConnectivity & CT_MASK_FLAGS);
+ OCStackResult result = OCInit1(OC_CLIENT, serverFlags, clientFlags);
if(OC_STACK_OK != result)
{
try
{
- ListenOCContainer container(clientWrapper, *clientResponse->addr,
- clientResponse->connType, requestStream);
+ ListenOCContainer container(clientWrapper, clientResponse->devAddr,
+ requestStream);
// loop to ensure valid construction of all resources
for(auto resource : container.Resources())
{
return OC_STACK_KEEP_TRANSACTION;
}
- OCStackResult InProcClientWrapper::ListenForResource(const std::string& serviceUrl,
- const std::string& resourceType, OCConnectivityType connectivityType,
- FindCallback& callback, QualityOfService QoS)
+ OCStackResult InProcClientWrapper::ListenForResource(
+ const std::string& serviceUrl, // unused
+ const std::string& resourceType,
+ OCConnectivityType connectivityType,
+ FindCallback& callback, QualityOfService QoS)
{
if(!callback)
{
if(cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
- result = OCDoResource(nullptr, OC_REST_GET,
+ result = OCDoResource(nullptr, OC_REST_DISCOVER,
resourceType.c_str(),
nullptr, nullptr, connectivityType,
static_cast<OCQualityOfService>(QoS),
return OC_STACK_KEEP_TRANSACTION;
}
- OCStackResult InProcClientWrapper::ListenForDevice(const std::string& serviceUrl,
- const std::string& deviceURI, OCConnectivityType connectivityType,
- FindDeviceCallback& callback, QualityOfService QoS)
+ OCStackResult InProcClientWrapper::ListenForDevice(
+ const std::string& serviceUrl, // unused
+ const std::string& deviceURI,
+ OCConnectivityType connectivityType,
+ FindDeviceCallback& callback,
+ QualityOfService QoS)
{
if(!callback)
{
if(cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
- result = OCDoResource(nullptr, OC_REST_GET,
+ result = OCDoResource(nullptr, OC_REST_DISCOVER,
deviceURI.c_str(),
nullptr, nullptr, connectivityType,
static_cast<OCQualityOfService>(QoS),
return OC_STACK_DELETE_TRANSACTION;
}
- OCStackResult InProcClientWrapper::GetResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType,
+ OCStackResult InProcClientWrapper::GetResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& resourceUri,
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
GetCallback& callback, QualityOfService QoS)
{
[](void* c){delete static_cast<ClientCallbackContext::GetContext*>(c);}
);
+ std::string uri = assembleSetResourceUri(resourceUri, queryParams);
+
auto cLock = m_csdkLock.lock();
if(cLock)
{
- std::ostringstream os;
- os << host << assembleSetResourceUri(uri, queryParams).c_str();
-
std::lock_guard<std::recursive_mutex> lock(*cLock);
OCHeaderOption options[MAX_HEADER_OPTIONS];
- result = OCDoResource(nullptr, OC_REST_GET, os.str().c_str(),
- nullptr, nullptr, connectivityType,
+ result = OCDoResource(nullptr, OC_REST_GET,
+ uri.c_str(),
+ &devAddr, nullptr,
+ CT_DEFAULT,
static_cast<OCQualityOfService>(QoS),
&cbdata,
assembleHeaderOptions(options, headerOptions),
return ocInfo.getJSONRepresentation(OCInfoFormat::IncludeOC);
}
- OCStackResult InProcClientWrapper::PostResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType, const OCRepresentation& rep,
+ OCStackResult InProcClientWrapper::PostResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
+ const OCRepresentation& rep,
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
PostCallback& callback, QualityOfService QoS)
{
[](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
);
- // TODO: in the future the cstack should be combining these two strings!
- ostringstream os;
- os << host << assembleSetResourceUri(uri, queryParams).c_str();
- // TODO: end of above
+ std::string url = assembleSetResourceUri(uri, queryParams);
auto cLock = m_csdkLock.lock();
OCHeaderOption options[MAX_HEADER_OPTIONS];
result = OCDoResource(nullptr, OC_REST_POST,
- os.str().c_str(), nullptr,
- assembleSetResourcePayload(rep).c_str(), connectivityType,
+ url.c_str(), &devAddr,
+ assembleSetResourcePayload(rep).c_str(),
+ CT_DEFAULT,
static_cast<OCQualityOfService>(QoS),
&cbdata,
assembleHeaderOptions(options, headerOptions),
return result;
}
- OCStackResult InProcClientWrapper::PutResourceRepresentation(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType, const OCRepresentation& rep,
+ OCStackResult InProcClientWrapper::PutResourceRepresentation(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
+ const OCRepresentation& rep,
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
PutCallback& callback, QualityOfService QoS)
{
[](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
);
- // TODO: in the future the cstack should be combining these two strings!
- ostringstream os;
- os << host << assembleSetResourceUri(uri, queryParams).c_str();
- // TODO: end of above
+ std::string url = assembleSetResourceUri(uri, queryParams).c_str();
auto cLock = m_csdkLock.lock();
OCHeaderOption options[MAX_HEADER_OPTIONS];
result = OCDoResource(&handle, OC_REST_PUT,
- os.str().c_str(), nullptr,
- assembleSetResourcePayload(rep).c_str(), connectivityType,
+ url.c_str(), &devAddr,
+ assembleSetResourcePayload(rep).c_str(),
+ CT_DEFAULT,
static_cast<OCQualityOfService>(QoS),
&cbdata,
assembleHeaderOptions(options, headerOptions),
return OC_STACK_DELETE_TRANSACTION;
}
- OCStackResult InProcClientWrapper::DeleteResource(const std::string& host,
- const std::string& uri, OCConnectivityType connectivityType,
+ OCStackResult InProcClientWrapper::DeleteResource(
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const HeaderOptions& headerOptions, DeleteCallback& callback, QualityOfService QoS)
{
if(!callback)
[](void* c){delete static_cast<ClientCallbackContext::DeleteContext*>(c);}
);
- ostringstream os;
- os << host << uri;
-
auto cLock = m_csdkLock.lock();
if(cLock)
std::lock_guard<std::recursive_mutex> lock(*cLock);
result = OCDoResource(nullptr, OC_REST_DELETE,
- os.str().c_str(), nullptr,
- nullptr, connectivityType,
+ uri.c_str(), &devAddr,
+ nullptr,
+ CT_DEFAULT,
static_cast<OCQualityOfService>(m_cfg.QoS),
&cbdata,
assembleHeaderOptions(options, headerOptions),
}
OCStackResult InProcClientWrapper::ObserveResource(ObserveType observeType, OCDoHandle* handle,
- const std::string& host, const std::string& uri, OCConnectivityType connectivityType,
+ const OCDevAddr& devAddr,
+ const std::string& uri,
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
ObserveCallback& callback, QualityOfService QoS)
{
method = OC_REST_OBSERVE_ALL;
}
+ std::string url = assembleSetResourceUri(uri, queryParams).c_str();
+
auto cLock = m_csdkLock.lock();
if(cLock)
{
- std::ostringstream os;
- os << host << assembleSetResourceUri(uri, queryParams).c_str();
-
std::lock_guard<std::recursive_mutex> lock(*cLock);
OCHeaderOption options[MAX_HEADER_OPTIONS];
result = OCDoResource(handle, method,
- os.str().c_str(), nullptr,
- nullptr, connectivityType,
+ url.c_str(), &devAddr,
+ nullptr,
+ CT_DEFAULT,
static_cast<OCQualityOfService>(QoS),
&cbdata,
assembleHeaderOptions(options, headerOptions),
return result;
}
- OCStackResult InProcClientWrapper::CancelObserveResource(OCDoHandle handle,
- const std::string& host, const std::string& uri, const HeaderOptions& headerOptions,
- QualityOfService QoS)
+ OCStackResult InProcClientWrapper::CancelObserveResource(
+ OCDoHandle handle,
+ const std::string& host, // unused
+ const std::string& uri, // unused
+ const HeaderOptions& headerOptions,
+ QualityOfService QoS)
{
OCStackResult result;
auto cLock = m_csdkLock.lock();
OCStackApplicationResult subscribePresenceCallback(void* ctx, OCDoHandle handle,
OCClientResponse* clientResponse)
{
- ostringstream os;
- uint16_t port;
- uint8_t a;
- uint8_t b;
- uint8_t c;
- uint8_t d;
+ ClientCallbackContext::SubscribePresenceContext* context =
+ static_cast<ClientCallbackContext::SubscribePresenceContext*>(ctx);
- if(OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) == 0 &&
- OCDevAddrToPort(clientResponse->addr, &port) == 0)
- {
- os<<static_cast<int>(a)<<"."<<static_cast<int>(b)<<"."<<static_cast<int>(c)
- <<"."<<static_cast<int>(d)<<":"<<static_cast<int>(port);
+ /*
+ * This a hack while we rethink presence subscription.
+ */
+ std::string url = clientResponse->devAddr.addr;
- ClientCallbackContext::SubscribePresenceContext* context =
- static_cast<ClientCallbackContext::SubscribePresenceContext*>(ctx);
+ std::thread exec(context->callback, clientResponse->result,
+ clientResponse->sequenceNumber, url);
- std::thread exec(context->callback, clientResponse->result,
- clientResponse->sequenceNumber, os.str());
+ exec.detach();
- exec.detach();
- }
- else
- {
- oclog() << "subscribePresenceCallback(): OCDevAddrToIPv4Addr() or OCDevAddrToPort() "
- <<"failed"<< std::flush;
- }
return OC_STACK_KEEP_TRANSACTION;
}
auto cLock = m_csdkLock.lock();
std::ostringstream os;
- os << host << OC_PRESENCE_URI;
+ os << host << "/oc/presence";
if(!resourceType.empty())
{
return OC_STACK_ERROR;
}
- return OCDoResource(handle, OC_REST_PRESENCE, os.str().c_str(), nullptr, nullptr,
- connectivityType, OC_LOW_QOS, &cbdata, NULL, 0);
+ return OCDoResource(handle, OC_REST_PRESENCE,
+ os.str().c_str(), nullptr,
+ nullptr, connectivityType,
+ OC_LOW_QOS, &cbdata, NULL, 0);
}
OCStackResult InProcClientWrapper::UnsubscribePresence(OCDoHandle handle)
else
{
throw InitializeException(OC::InitException::NOT_CONFIGURED_AS_SERVER,
- OC_STACK_INVALID_PARAM);
+ OC_STACK_INVALID_PARAM);
}
- OCStackResult result = OCInit(cfg.ipAddress.c_str(), cfg.port, initType);
+ OCTransportFlags serverFlags =
+ static_cast<OCTransportFlags>(cfg.serverConnectivity & CT_MASK_FLAGS);
+ OCTransportFlags clientFlags =
+ static_cast<OCTransportFlags>(cfg.clientConnectivity & CT_MASK_FLAGS);
+ OCStackResult result = OCInit1(initType, serverFlags, clientFlags);
if(OC_STACK_OK != result)
{
const std::vector<std::string>& resourceTypes,
const std::vector<std::string>& interfaces)
{
- return OCPlatform_impl::Instance().constructResourceObject(host, uri, connectivityType,
+ return OCPlatform_impl::Instance().constructResourceObject(host,
+ uri, connectivityType,
isObservable,
resourceTypes, interfaces);
}
OCStackResult findResource(const std::string& host,
- const std::string& resourceName,
- OCConnectivityType connectivityType,
- FindCallback resourceHandler)
+ const std::string& resourceName,
+ OCConnectivityType connectivityType,
+ FindCallback resourceHandler)
{
return OCPlatform_impl::Instance().findResource(host, resourceName,
- connectivityType, resourceHandler);
+ connectivityType, resourceHandler);
}
OCStackResult findResource(const std::string& host,
- const std::string& resourceName,
- OCConnectivityType connectivityType,
- FindCallback resourceHandler, QualityOfService QoS)
+ const std::string& resourceName,
+ OCConnectivityType connectivityType,
+ FindCallback resourceHandler,
+ QualityOfService QoS)
{
- return OCPlatform_impl::Instance().findResource(host, resourceName, connectivityType,
- resourceHandler, QoS);
+ return OCPlatform_impl::Instance().findResource(host, resourceName,
+ connectivityType, resourceHandler, QoS);
}
OCStackResult getDeviceInfo(const std::string& host,
- const std::string& deviceURI,
- OCConnectivityType connectivityType,
- FindDeviceCallback deviceInfoHandler)
+ const std::string& deviceURI,
+ OCConnectivityType connectivityType,
+ FindDeviceCallback deviceInfoHandler)
{
return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI,
connectivityType, deviceInfoHandler);
}
OCStackResult getDeviceInfo(const std::string& host,
- const std::string& deviceURI,
- OCConnectivityType connectivityType,
- FindDeviceCallback deviceInfoHandler,
- QualityOfService QoS)
+ const std::string& deviceURI,
+ OCConnectivityType connectivityType,
+ FindDeviceCallback deviceInfoHandler,
+ QualityOfService QoS)
{
return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI, connectivityType,
deviceInfoHandler, QoS);
OCStackResult OCPlatform_impl::findResource(const std::string& host,
const std::string& resourceName,
OCConnectivityType connectivityType,
- FindCallback resourceHandler, QualityOfService QoS)
+ FindCallback resourceHandler,
+ QualityOfService QoS)
{
-
return checked_guard(m_client, &IClientWrapper::ListenForResource,
host, resourceName, connectivityType, resourceHandler, QoS);
}
using OC::result_guard;
using OC::checked_guard;
-OCResource::OCResource(std::weak_ptr<IClientWrapper> clientWrapper, const std::string& host,
- const std::string& uri, const std::string& serverId,
- OCConnectivityType connectivityType, bool observable,
- const std::vector<std::string>& resourceTypes,
- const std::vector<std::string>& interfaces)
- : m_clientWrapper(clientWrapper), m_uri(uri), m_resourceId(serverId, m_uri),
- m_host(host),
- m_connectivityType(connectivityType),
- m_isObservable(observable),
- m_isCollection(false), m_resourceTypes(resourceTypes), m_interfaces(interfaces),
+OCResource::OCResource(std::weak_ptr<IClientWrapper> clientWrapper,
+ const OCDevAddr& devAddr, const std::string& uri,
+ const std::string& serverId, bool observable,
+ const std::vector<std::string>& resourceTypes,
+ const std::vector<std::string>& interfaces)
+ : m_clientWrapper(clientWrapper), m_uri(uri),
+ m_resourceId(serverId, m_uri), m_devAddr(devAddr),
+ m_isObservable(observable), m_isCollection(false),
+ m_resourceTypes(resourceTypes), m_interfaces(interfaces),
m_observeHandle(nullptr)
{
m_isCollection = std::find(m_interfaces.begin(), m_interfaces.end(), LINK_INTERFACE)
}
}
+OCResource::OCResource(std::weak_ptr<IClientWrapper> clientWrapper,
+ const std::string& host, const std::string& uri,
+ const std::string& serverId,
+ OCConnectivityType connectivityType, bool observable,
+ const std::vector<std::string>& resourceTypes,
+ const std::vector<std::string>& interfaces)
+ : m_clientWrapper(clientWrapper), m_uri(uri),
+ m_resourceId(serverId, m_uri),
+ m_devAddr{ OC_DEFAULT_ADAPTER },
+ m_isObservable(observable), m_isCollection(false),
+ m_resourceTypes(resourceTypes), m_interfaces(interfaces),
+ m_observeHandle(nullptr)
+{
+ m_isCollection = std::find(m_interfaces.begin(), m_interfaces.end(), LINK_INTERFACE)
+ != m_interfaces.end();
+
+ if (m_uri.empty() ||
+ resourceTypes.empty() ||
+ interfaces.empty()||
+ m_clientWrapper.expired())
+ {
+ throw ResourceInitException(m_uri.empty(), resourceTypes.empty(),
+ interfaces.empty(), m_clientWrapper.expired(), false, false);
+ }
+
+ // construct the devAddr from the pieces we have
+ m_devAddr.adapter = static_cast<OCTransportAdapter>(connectivityType >> CT_ADAPTER_SHIFT);
+ m_devAddr.flags = static_cast<OCTransportFlags>(connectivityType & CT_MASK_FLAGS);
+ size_t len = host.length();
+ if (len >= MAX_ADDR_STR_SIZE)
+ {
+ throw std::length_error("host address is too long.");
+ }
+ host.copy(m_devAddr.addr, len);
+ m_devAddr.addr[len] = '\0';
+}
+
OCResource::~OCResource()
{
}
OCStackResult OCResource::get(const QueryParamsMap& queryParametersMap,
GetCallback attributeHandler, QualityOfService QoS)
{
- return checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetResourceRepresentation,
- m_host, m_uri, m_connectivityType, queryParametersMap, m_headerOptions,
- attributeHandler, QoS);
+ return checked_guard(m_clientWrapper.lock(),
+ &IClientWrapper::GetResourceRepresentation,
+ m_devAddr, m_uri,
+ queryParametersMap, m_headerOptions,
+ attributeHandler, QoS);
}
OCStackResult OCResource::get(const QueryParamsMap& queryParametersMap,
QualityOfService QoS)
{
return checked_guard(m_clientWrapper.lock(), &IClientWrapper::PutResourceRepresentation,
- m_host, m_uri, m_connectivityType, rep, queryParametersMap,
+ m_devAddr, m_uri, rep, queryParametersMap,
m_headerOptions, attributeHandler, QoS);
}
QualityOfService QoS)
{
return checked_guard(m_clientWrapper.lock(), &IClientWrapper::PostResourceRepresentation,
- m_host, m_uri, m_connectivityType, rep, queryParametersMap,
+ m_devAddr, m_uri, rep, queryParametersMap,
m_headerOptions, attributeHandler, QoS);
}
OCStackResult OCResource::deleteResource(DeleteCallback deleteHandler, QualityOfService QoS)
{
return checked_guard(m_clientWrapper.lock(), &IClientWrapper::DeleteResource,
- m_host, m_uri, m_connectivityType, m_headerOptions, deleteHandler, QoS);
+ m_devAddr, m_uri, m_headerOptions, deleteHandler, QoS);
}
OCStackResult OCResource::deleteResource(DeleteCallback deleteHandler)
}
return checked_guard(m_clientWrapper.lock(), &IClientWrapper::ObserveResource,
- observeType, &m_observeHandle, m_host,
- m_uri, m_connectivityType, queryParametersMap, m_headerOptions,
+ observeType, &m_observeHandle, m_devAddr,
+ m_uri, queryParametersMap, m_headerOptions,
observeHandler, QoS);
}
OCStackResult result = checked_guard(m_clientWrapper.lock(),
&IClientWrapper::CancelObserveResource,
- m_observeHandle, m_host, m_uri, m_headerOptions, QoS);
+ m_observeHandle, "", m_uri, m_headerOptions, QoS);
if(result == OC_STACK_OK)
{
std::string OCResource::host() const
{
- return m_host;
+ return std::string(m_devAddr.addr);
}
std::string OCResource::uri() const
OCConnectivityType OCResource::connectivityType() const
{
- return m_connectivityType;
+ return static_cast<OCConnectivityType>(
+ (m_devAddr.adapter << CT_ADAPTER_SHIFT) | (m_devAddr.flags & CT_MASK_FLAGS));
}
bool OCResource::isObservable() const
return m_isObservable;
}
-
OCResourceIdentifier OCResource::uniqueIdentifier() const
{
return m_resourceId;
std::ostream& operator <<(std::ostream& os, const OCResourceIdentifier& ri)
{
-
os << ri.m_representation<<ri.m_resourceUri;
return os;
std::ostringstream requestURI;
requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
EXPECT_EQ(OC_STACK_OK, OCPlatform::findResource("", requestURI.str(),
- OC_IPV4, &foundResource));
+ CT_DEFAULT, &foundResource));
}
TEST(FindResourceTest, FindResourceNullResourceURI)
{
EXPECT_ANY_THROW(OCPlatform::findResource("", nullptr,
- OC_IPV4, &foundResource));
+ CT_DEFAULT, &foundResource));
}
TEST(FindResourceTest, FindResourceNullResourceURI1)
std::ostringstream requestURI;
requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
EXPECT_ANY_THROW(OCPlatform::findResource(nullptr, requestURI.str(),
- OC_IPV4, &foundResource));
+ CT_DEFAULT, &foundResource));
}
TEST(FindResourceTest, FindResourceNullHost)
std::ostringstream requestURI;
requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
EXPECT_ANY_THROW(OCPlatform::findResource(nullptr, requestURI.str(),
- OC_IPV4, &foundResource));
+ CT_DEFAULT, &foundResource));
}
TEST(FindResourceTest, FindResourceNullresourceHandler)
std::ostringstream requestURI;
requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
EXPECT_THROW(OCPlatform::findResource("", requestURI.str(),
- OC_IPV4, NULL), OC::OCException);
+ CT_DEFAULT, NULL), OC::OCException);
}
TEST(FindResourceTest, DISABLED_FindResourceWithLowQoS)
std::ostringstream requestURI;
requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
EXPECT_EQ(OC_STACK_OK,
- OCPlatform::findResource("", requestURI.str(), OC_IPV4, &foundResource,
+ OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, &foundResource,
OC::QualityOfService::LowQos));
}
std::ostringstream requestURI;
requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
EXPECT_EQ(OC_STACK_OK,
- OCPlatform::findResource("", requestURI.str(), OC_IPV4, &foundResource,
+ OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, &foundResource,
OC::QualityOfService::MidQos));
}
std::ostringstream requestURI;
requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
EXPECT_EQ(OC_STACK_OK,
- OCPlatform::findResource("", requestURI.str(), OC_IPV4, &foundResource,
+ OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, &foundResource,
OC::QualityOfService::HighQos));
}
std::ostringstream requestURI;
requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light";
EXPECT_EQ(OC_STACK_OK,
- OCPlatform::findResource("", requestURI.str(), OC_IPV4, &foundResource,
+ OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, &foundResource,
OC::QualityOfService::NaQos));
}
std::ostringstream requestURI;
requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
EXPECT_EQ(OC_STACK_OK,
- OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, &receivedDeviceInfo));
+ OCPlatform::getDeviceInfo("", requestURI.str(), CT_DEFAULT, &receivedDeviceInfo));
}
TEST(GetDeviceInfoTest, GetDeviceInfoNullDeviceURI)
PlatformConfig cfg;
OCPlatform::Configure(cfg);
EXPECT_ANY_THROW(
- OCPlatform::getDeviceInfo("", nullptr, OC_IPV4, &receivedDeviceInfo));
+ OCPlatform::getDeviceInfo("", nullptr, CT_DEFAULT, &receivedDeviceInfo));
}
TEST(GetDeviceInfoTest, GetDeviceInfoWithNullDeviceInfoHandler)
std::ostringstream requestURI;
requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
EXPECT_THROW(
- OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, NULL),
+ OCPlatform::getDeviceInfo("", requestURI.str(), CT_DEFAULT, NULL),
OC::OCException);
}
std::ostringstream requestURI;
requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
EXPECT_EQ(OC_STACK_OK,
- OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, &receivedDeviceInfo,
+ OCPlatform::getDeviceInfo("", requestURI.str(), CT_DEFAULT, &receivedDeviceInfo,
OC::QualityOfService::LowQos));
}
std::ostringstream requestURI;
requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
EXPECT_EQ(OC_STACK_OK,
- OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, &receivedDeviceInfo,
+ OCPlatform::getDeviceInfo("", requestURI.str(), CT_DEFAULT, &receivedDeviceInfo,
OC::QualityOfService::MidQos));
}
std::ostringstream requestURI;
requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
EXPECT_EQ(OC_STACK_OK,
- OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, &receivedDeviceInfo,
+ OCPlatform::getDeviceInfo("", requestURI.str(), CT_DEFAULT, &receivedDeviceInfo,
OC::QualityOfService::HighQos));
}
std::ostringstream requestURI;
requestURI << OC_MULTICAST_PREFIX << deviceDiscoveryURI;
EXPECT_EQ(OC_STACK_OK,
- OCPlatform::getDeviceInfo("", requestURI.str(), OC_IPV4, &receivedDeviceInfo,
+ OCPlatform::getDeviceInfo("", requestURI.str(), CT_DEFAULT, &receivedDeviceInfo,
OC::QualityOfService::NaQos));
}
OCPlatform::OCPresenceHandle presenceHandle = nullptr;
EXPECT_EQ(OC_STACK_OK, OCPlatform::subscribePresence(presenceHandle, hostAddress,
- OC_IPV4, &presenceHandler));
+ CT_DEFAULT, &presenceHandler));
}
TEST(SubscribePresenceTest, SubscribePresenceWithNullHost)
OCPlatform::OCPresenceHandle presenceHandle = nullptr;
EXPECT_ANY_THROW(OCPlatform::subscribePresence(presenceHandle, nullptr,
- OC_IPV4, &presenceHandler));
+ CT_DEFAULT, &presenceHandler));
}
TEST(SubscribePresenceTest, SubscribePresenceWithNullPresenceHandler)
OCPlatform::OCPresenceHandle presenceHandle = nullptr;
EXPECT_ANY_THROW(OCPlatform::subscribePresence(presenceHandle, nullptr,
- OC_IPV4, NULL));
+ CT_DEFAULT, NULL));
}
TEST(SubscribePresenceTest, DISABLED_SubscribePresenceWithResourceType)
OCPlatform::OCPresenceHandle presenceHandle = nullptr;
EXPECT_EQ(OC_STACK_OK, OCPlatform::subscribePresence(presenceHandle,
- OC_MULTICAST_IP, "core.light", OC_IPV4, &presenceHandler));
+ OC_MULTICAST_IP, "core.light", CT_DEFAULT, &presenceHandler));
}
TEST(SubscribePresenceTest, SubscribePresenceWithNullResourceType)
OCPlatform::OCPresenceHandle presenceHandle = nullptr;
EXPECT_ANY_THROW(OCPlatform::subscribePresence(presenceHandle,
- OC_MULTICAST_IP, nullptr, OC_IPV4, &presenceHandler));
+ OC_MULTICAST_IP, nullptr, CT_DEFAULT, &presenceHandler));
}
TEST(SubscribePresenceTest, DISABLED_UnsubscribePresenceWithValidHandleAndRT)
OCPlatform::OCPresenceHandle presenceHandle = nullptr;
EXPECT_EQ(OC_STACK_OK, OCPlatform::subscribePresence(presenceHandle,
- OC_MULTICAST_IP, "core.light", OC_IPV4, &presenceHandler));
+ OC_MULTICAST_IP, "core.light", CT_DEFAULT, &presenceHandler));
EXPECT_EQ(OC_STACK_OK, OCPlatform::unsubscribePresence(presenceHandle));
}
OCPlatform::OCPresenceHandle presenceHandle = nullptr;
EXPECT_EQ(OC_STACK_OK, OCPlatform::subscribePresence(presenceHandle,
- OC_MULTICAST_IP, OC_IPV4, &presenceHandler));
+ OC_MULTICAST_IP, CT_DEFAULT, &presenceHandler));
EXPECT_EQ(OC_STACK_OK, OCPlatform::unsubscribePresence(presenceHandle));
}
OCServerRequest request;
request.method = OC_REST_GET;
strncpy(request.query, query, sizeof(query));
- request.connectivityType = CA_IPV4;
- strncpy(request.addressInfo.IP.ipAddress, address, sizeof(query));
- request.addressInfo.IP.port = 5364;
- request.qos = OC_LOW_QOS;
+ request.devAddr.flags = OC_DEFAULT_FLAGS;
+ request.devAddr.adapter = OC_DEFAULT_ADAPTER;
+ strncpy(request.devAddr.addr, address, sizeof(query));
+ request.devAddr.port = 5364;
+ request.qos = OC_LOW_QOS;
request.coapID = 0;
request.delayedResNeeded = 0;
- request.secured = 0;
OCRequestHandle handle = static_cast<OCRequestHandle>(&request);
EXPECT_EQ(NULL, response.getRequestHandle());
//Helper method
OCResource::Ptr ConstructResourceObject(std::string host, std::string uri)
{
- OCConnectivityType connectivityType = OC_IPV4;
+ OCConnectivityType connectivityType = CT_DEFAULT;
std::vector<std::string> types = {"intel.rpost"};
std::vector<std::string> ifaces = {DEFAULT_INTERFACE};
{
OCResource::Ptr resource = ConstructResourceObject("coap://192.168.1.2:5000", "/resource");
EXPECT_TRUE(resource != NULL);
- EXPECT_TRUE(resource->connectivityType() == OC_IPV4);
+ EXPECT_TRUE(resource->connectivityType() == CT_DEFAULT);
}
//IsObservable Test
#include "ocstack.h"
#include "logger.h"
-//#define OC_TRANSPORT OC_ALL
-#define OC_TRANSPORT OC_IPV4
+//#define OC_TRANSPORT CT_DEFAULT
+#define OC_TRANSPORT CT_ADAPTER_IP
#ifdef __cplusplus
extern "C" {
cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
cbData.cd = NULL;
- result = OCDoResource(&handle, OC_REST_GET, queryUri, OIC_COORDINATING_FLAG, 0,
+ result = OCDoResource(&handle, OC_REST_GET, queryUri, NULL, 0,
OC_TRANSPORT, OC_LOW_QOS, &cbData, NULL, 0);
if (result != OC_STACK_OK)
{
OCStackApplicationResult requestPresenceCB(void *context, OCDoHandle handle,
OCClientResponse *clientResponse)
{
- uint8_t remoteIpAddress[4];
- uint16_t remotePortNumber;
char address[OIC_STRING_MAX_VALUE] = { '\0' };
if (context == (void *) DEFAULT_CONTEXT_VALUE)
}
if (clientResponse)
{
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddress,
- remoteIpAddress + 1, remoteIpAddress + 2, remoteIpAddress + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNumber);
OC_LOG_V(DEBUG, HOSTING_TAG, "\tStackResult: %s", getResultString(clientResponse->result));
OC_LOG_V(DEBUG, HOSTING_TAG, "\tStackResult: %d", clientResponse->result);
OC_LOG_V(DEBUG, HOSTING_TAG,
- "\tPresence Device =============> Presence %s @ %d.%d.%d.%d:%d",
- clientResponse->resJSONPayload, remoteIpAddress[0], remoteIpAddress[1],
- remoteIpAddress[2], remoteIpAddress[3], remotePortNumber);
-
- snprintf(address, sizeof(address), "%d.%d.%d.%d:%d", remoteIpAddress[0], remoteIpAddress[1],
- remoteIpAddress[2], remoteIpAddress[3], remotePortNumber);
+ "\tPresence Device =============> Presence %s @ %s:%d",
+ clientResponse->resJSONPayload,
+ clientResponse->devAddr.addr,
+ clientResponse->devAddr.port);
+
+ snprintf(address, sizeof(address), "%s:%d",
+ clientResponse->devAddr.addr,
+ clientResponse->devAddr.port);
if (clientResponse->result == OC_STACK_OK)
{
requestCoordinateeCandidateDiscovery(address);
MirrorResourceList *retList = createMirrorResourceList();
- uint8_t remoteIpAddr[4];
- uint16_t remotePortNum;
-
- OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
- remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
- OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNum);
-
char sourceaddr[OIC_STRING_MAX_VALUE] = {'\0'};
- snprintf(sourceaddr, sizeof(sourceaddr), "%d.%d.%d.%d:%d", remoteIpAddr[0], remoteIpAddr[1],
- remoteIpAddr[2], remoteIpAddr[3], remotePortNum);
+ snprintf(sourceaddr, sizeof(sourceaddr), "%s:%d",
+ clientResponse->devAddr.addr,
+ clientResponse->devAddr.port);
OC_LOG_V(DEBUG, HOSTING_TAG, "Host Device =============> Discovered %s @ %s",
clientResponse->resJSONPayload, sourceaddr);
OCStackResult nmfindResource(const std::string &host , const std::string &resourceName)
{
- return OCPlatform::findResource(host , resourceName , OC_ALL, &foundResource);
+ return OCPlatform::findResource(host , resourceName , CT_DEFAULT, &foundResource);
}
void getRepresentation(std::shared_ptr< OCResource > resource)
std::cout.setf(std::ios::boolalpha);
// Find all resources
requestURI << OC_MULTICAST_DISCOVERY_URI << "?rt=core.fan";
- OCPlatform::findResource("", requestURI.str(), OC_ALL, &foundResourceFan);
+ OCPlatform::findResource("", requestURI.str(), CT_DEFAULT, &foundResourceFan);
std::cout << "Finding Resource... " << std::endl;
while (true)
{
case OC_STACK_OK:
requestURI << "coap://" << hostAddress << "/oc/core?rt=SSManager.Sensor";
- ret = OC::OCPlatform::findResource("", requestURI.str(), OC_ALL,
+ ret = OC::OCPlatform::findResource("", requestURI.str(), CT_DEFAULT,
std::bind(&CResourceFinder::onResourceFound, this, std::placeholders::_1));
if (ret != OC_STACK_OK)
std::ostringstream multicastPresenceURI;
multicastPresenceURI << "coap://" << OC_MULTICAST_PREFIX;
- ret = OC::OCPlatform::findResource("", requestURI.str(), OC_ALL,
+ ret = OC::OCPlatform::findResource("", requestURI.str(), CT_DEFAULT,
std::bind(&CResourceFinder::onResourceFound, this, std::placeholders::_1));
if (ret != OC_STACK_OK)
SSM_CLEANUP_ASSERT(SSM_E_FAIL);
ret = OC::OCPlatform::subscribePresence(m_multicastPresenceHandle, multicastPresenceURI.str(),
- "SSManager.Sensor", OC_ALL, std::bind(&CResourceFinder::presenceHandler, this,
+ "SSManager.Sensor", CT_DEFAULT, std::bind(&CResourceFinder::presenceHandler, this,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
if (ret != OC_STACK_OK)
m_mapResourcePresenceHandles.end())
{
ret = OC::OCPlatform::subscribePresence(presenceHandle, ((ISSMResource *)pMessage[1])->ip,
- "SSManager.Sensor", OC_ALL, std::bind(&CResourceFinder::presenceHandler, this,
+ "SSManager.Sensor", CT_DEFAULT, std::bind(&CResourceFinder::presenceHandler, this,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
if (ret != OC_STACK_OK)
OCPlatform::findResource("",
query,
- OC_ALL,
+ CT_DEFAULT,
&foundResource);
// OCPlatform::findResource("",
OCPlatform::findResource("",
query,
- OC_ALL,
+ CT_DEFAULT,
&foundResource);
// OCPlatform::findResource("",
// query,
cout << query.str() << endl;
result = OCPlatform::findResource("",
query.str(),
- OC_ALL,
+ CT_DEFAULT,
onFindResource);
result = OCPlatform::findResource("",
"coap://224.0.1.187/oc/core?rt=core.musicplayer",
- OC_ALL,
+ CT_DEFAULT,
onFindResource);
if (OC_STACK_OK == result)
query << OC_MULTICAST_DISCOVERY_URI << "?rt=core.speaker";
result = OCPlatform::findResource("",
query.str(),
- OC_ALL,
+ CT_DEFAULT,
onFindResource);
if (OC_STACK_OK == result)
OCPlatform::findResource("",
query,
- OC_ALL,
+ CT_DEFAULT,
std::function < void(std::shared_ptr < OCResource > resource)
> (std::bind(&GroupManager::onFoundResource, this, std::placeholders::_1,
waitsec)));
result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
// resourceType,
resourceTypes.front(),
- OC_ALL,
+ CT_DEFAULT,
std::function<
void(OCStackResult result, const unsigned int nonce,
const std::string& hostAddress) >(
query.append(collectionResourceTypes.at(i));
OCPlatform::findResource("", query,
- OC_ALL,
+ CT_DEFAULT,
std::bind(&GroupSynchronization::onFindGroup, this,
std::placeholders::_1));
}
OCResource::Ptr groupSyncResource =
OCPlatform::constructResourceObject(host, uri,
- OC_ALL, false,
+ CT_DEFAULT, false,
resourceTypes, resourceInterface);
// OCResource::Ptr groupSyncResource = OCPlatform::constructResourceObject(host, uri,
OCResource::Ptr groupSyncResource;
groupSyncResource = OCPlatform::constructResourceObject(host, uri,
- OC_ALL, false,
+ CT_DEFAULT, false,
resourceTypes, resourceInterface);
// groupSyncResource = OCPlatform::constructResourceObject(host, uri,
// OC_WIFI, false, resourceTypes, resourceInterface);
resourceRequest = request;
OCPlatform::findResource("", resourceName,
- OC_ALL,
+ CT_DEFAULT,
std::bind(&GroupSynchronization::onFindResource, this,
std::placeholders::_1));
std::string host = getHostFromURI(oit->getUri());
- tempResource = OCPlatform::constructResourceObject(host, uri, OC_IPV4, true,
+ tempResource = OCPlatform::constructResourceObject(host, uri, CT_ADAPTER_IP, true,
oit->getResourceTypes(), m_if);
p_resources.push_back(tempResource);