1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //=============================================================================
24 //=============================================================================
25 #define _POSIX_C_SOURCE 200112L
28 #include "ocstackconfig.h"
29 #include "occlientcb.h"
30 #include "ocobserve.h"
41 //=============================================================================
43 //=============================================================================
44 #define TAG PCF("OCCoAP")
45 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
46 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
47 #define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg); goto exit;} }
49 //=============================================================================
51 //=============================================================================
52 #define COAP_BLOCK_FILL_VALUE (0xFF)
54 //=============================================================================
56 //=============================================================================
58 static uint8_t coapWKIpAddr[] = { 224, 0, 1, 187 };
59 static coap_context_t *gCoAPCtx = NULL;
61 //=============================================================================
63 //=============================================================================
65 //generate a coap token
66 void OCGenerateCoAPToken(OCCoAPToken * token)
70 token->tokenLength = MAX_TOKEN_LENGTH;
71 OCFillRandomMem((uint8_t*)token->token, token->tokenLength);
75 //This function is called back by libcoap when ack or rst are received
76 static void HandleCoAPAckRst(struct coap_context_t * ctx, uint8_t msgType,
77 const coap_queue_t * sentQueue){
81 coap_pdu_t * sentPdu = sentQueue->pdu;
82 OCStackResult result = OC_STACK_ERROR;
83 uint32_t observationOption = OC_OBSERVE_NO_OPTION;
84 // {{0}} to eliminate warning for known compiler bug 53119
85 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119
86 OCCoAPToken sentToken = {{0}};
88 result = ParseCoAPPdu(sentPdu, NULL, NULL, &observationOption, NULL, NULL, NULL,
89 NULL, NULL, NULL, NULL, NULL);
90 VERIFY_SUCCESS(result, OC_STACK_OK);
92 // fill OCCoAPToken structure
93 RetrieveOCCoAPToken(sentPdu, &sentToken);
95 if(msgType == COAP_MESSAGE_RST)
97 if(myStackMode != OC_CLIENT)
99 result = OCStackFeedBack(&sentToken, OC_OBSERVER_NOT_INTERESTED);
100 if(result == OC_STACK_OK)
103 "Received RST, removing all queues associated with Token %d bytes",
104 sentToken.tokenLength);
105 OC_LOG_BUFFER(INFO, TAG, sentToken.token, sentToken.tokenLength);
106 coap_cancel_all_messages(ctx, &sentQueue->remote, sentToken.token,
107 sentToken.tokenLength);
111 else if(observationOption != OC_OBSERVE_NO_OPTION && msgType == COAP_MESSAGE_ACK)
113 OC_LOG_V(DEBUG, TAG, "Received ACK, for Token %d bytes",sentToken.tokenLength);
114 OC_LOG_BUFFER(INFO, TAG, sentToken.token, sentToken.tokenLength);
115 // now the observer is still interested
116 if(myStackMode != OC_CLIENT)
118 OCStackFeedBack(&sentToken, OC_OBSERVER_STILL_INTERESTED);
125 //This function is called back by libcoap when a request is received
126 static void HandleCoAPRequests(struct coap_context_t *ctx,
127 const coap_queue_t * rcvdRequest)
131 OCServerProtocolRequest protocolRequest = {(OCMethod)0};
132 coap_block_t rcvdBlock1;
133 coap_block_t rcvdBlock2;
134 memset(&rcvdBlock1, COAP_BLOCK_FILL_VALUE, sizeof(coap_block_t));
135 memset(&rcvdBlock2, COAP_BLOCK_FILL_VALUE, sizeof(coap_block_t));
136 uint16_t rcvdSize1 = 0;
137 coap_pdu_t * rcvdPdu = rcvdRequest->pdu;
138 coap_pdu_t * sendPdu = NULL;
139 coap_send_flags_t sendFlag;
140 OCStackResult result = OC_STACK_ERROR;
141 OCStackResult requestResult = OC_STACK_ERROR;
143 if(myStackMode == OC_CLIENT)
145 //TODO: should the client be responding to requests?
149 protocolRequest.observationOption = OC_OBSERVE_NO_OPTION;
150 protocolRequest.qos = (rcvdPdu->hdr->type == COAP_MESSAGE_CON) ?
151 OC_HIGH_QOS : OC_LOW_QOS;
152 protocolRequest.coapID = rcvdPdu->hdr->id;
153 protocolRequest.delayedResNeeded = rcvdRequest->delayedResNeeded;
154 protocolRequest.secured = rcvdRequest->secure;
156 // fill OCCoAPToken structure
157 RetrieveOCCoAPToken(rcvdPdu, &protocolRequest.requestToken);
158 OC_LOG_V(INFO, TAG, " Token received %d bytes",
159 protocolRequest.requestToken.tokenLength);
160 OC_LOG_BUFFER(INFO, TAG, protocolRequest.requestToken.token,
161 protocolRequest.requestToken.tokenLength);
164 memcpy(&protocolRequest.requesterAddr, (OCDevAddr *) &rcvdRequest->remote,
167 // Retrieve Uri and Query from received coap pdu
168 result = ParseCoAPPdu(rcvdPdu, protocolRequest.resourceUrl,
169 protocolRequest.query,
170 &(protocolRequest.observationOption), NULL,
171 &(protocolRequest.numRcvdVendorSpecificHeaderOptions),
172 protocolRequest.rcvdVendorSpecificHeaderOptions,
173 &rcvdBlock1, &rcvdBlock2, &rcvdSize1, NULL,
174 protocolRequest.reqJSONPayload);
175 VERIFY_SUCCESS(result, OC_STACK_OK);
177 switch (rcvdPdu->hdr->code)
179 case COAP_REQUEST_GET:
181 protocolRequest.method = OC_REST_GET;
184 case COAP_REQUEST_POST:
186 protocolRequest.method = OC_REST_POST;
189 case COAP_REQUEST_DELETE:
191 protocolRequest.method = OC_REST_DELETE;
194 case COAP_REQUEST_PUT:
196 protocolRequest.method = OC_REST_PUT;
201 OC_LOG_V(ERROR, TAG, "Received CoAP method %d not supported",
207 if(rcvdBlock1.szx != 7)
209 protocolRequest.reqPacketSize = 1 << (rcvdBlock1.szx + 4);
210 protocolRequest.reqMorePacket = rcvdBlock1.m;
211 protocolRequest.reqPacketNum = rcvdBlock1.num;
215 // No block1 received
216 rcvdSize1 = strlen((const char *)protocolRequest.reqJSONPayload)+1;
217 protocolRequest.reqTotalSize = rcvdSize1;
220 if(rcvdBlock2.szx != 7)
222 protocolRequest.resPacketSize = 1 << (rcvdBlock2.szx + 4);
223 protocolRequest.resPacketNum = rcvdBlock2.num;
226 requestResult = HandleStackRequests(&protocolRequest);
228 if(requestResult == OC_STACK_VIRTUAL_DO_NOT_HANDLE ||
229 requestResult == OC_STACK_OK ||
230 requestResult == OC_STACK_RESOURCE_CREATED ||
231 requestResult == OC_STACK_RESOURCE_DELETED)
235 else if(requestResult == OC_STACK_NO_MEMORY ||
236 requestResult == OC_STACK_ERROR ||
237 requestResult == OC_STACK_NOTIMPL ||
238 requestResult == OC_STACK_NO_RESOURCE ||
239 requestResult == OC_STACK_RESOURCE_ERROR)
241 // TODO: should we send an error also when we receive a non-secured request to a secure resource?
242 // TODO: should we consider some sort of error response
243 OC_LOG(DEBUG, TAG, PCF("We should send some sort of error message"));
244 // generate the pdu, if the request was CON, then the response is ACK, otherwire NON
245 sendPdu = GenerateCoAPPdu((rcvdPdu->hdr->type == COAP_MESSAGE_CON)? COAP_MESSAGE_ACK : COAP_MESSAGE_NON,
246 OCToCoAPResponseCode(requestResult), rcvdPdu->hdr->id,
247 &protocolRequest.requestToken, NULL, NULL);
248 VERIFY_NON_NULL(sendPdu);
249 coap_show_pdu(sendPdu);
250 sendFlag = (coap_send_flags_t)(rcvdRequest->secure ? SEND_SECURE_PORT : 0);
251 if(SendCoAPPdu(gCoAPCtx, (coap_address_t*) &(rcvdRequest->remote), sendPdu,
254 OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu"));
258 else if(requestResult == OC_STACK_SLOW_RESOURCE)
260 if(rcvdPdu->hdr->type == COAP_MESSAGE_CON)
262 // generate the pdu, if the request was CON, then the response is ACK, otherwire NON
263 sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0, rcvdPdu->hdr->id,
265 VERIFY_NON_NULL(sendPdu);
266 coap_show_pdu(sendPdu);
268 sendFlag = (coap_send_flags_t)(rcvdRequest->secure ? SEND_SECURE_PORT : 0);
269 if(SendCoAPPdu(gCoAPCtx, (coap_address_t*) &(rcvdRequest->remote), sendPdu,
272 OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu"));
284 uint32_t GetTime(float afterSeconds)
288 return now + (uint32_t)(afterSeconds * COAP_TICKS_PER_SECOND);
291 //This function is called back by libcoap when a response is received
292 static void HandleCoAPResponses(struct coap_context_t *ctx,
293 const coap_queue_t * rcvdResponse) {
294 OCResponse * response = NULL;
295 OCCoAPToken rcvdToken;
296 OCClientResponse clientResponse = {0};
297 ClientCB * cbNode = NULL;
298 unsigned char bufRes[MAX_RESPONSE_LENGTH] = {0};
299 uint32_t sequenceNumber = OC_OBSERVE_NO_OPTION;
301 OCStackResult result = OC_STACK_ERROR;
302 coap_pdu_t * sendPdu = NULL;
303 coap_pdu_t * recvPdu = NULL;
304 unsigned char rcvdUri[MAX_URI_LENGTH] = { 0 };
305 uint8_t isObserveNotification = 0;
307 char * resourceTypeName = NULL;
308 uint8_t remoteIpAddr[4];
309 uint16_t remotePortNu;
310 unsigned char fullUri[MAX_URI_LENGTH] = { 0 };
311 uint8_t isPresenceNotification = 0;
312 uint8_t isMulticastPresence = 0;
314 uint32_t higherBound;
317 coap_block_t rcvdBlock1 = {COAP_BLOCK_FILL_VALUE};
318 coap_block_t rcvdBlock2 = {COAP_BLOCK_FILL_VALUE};
319 uint16_t rcvdSize2 = 0;
321 VERIFY_NON_NULL(ctx);
322 VERIFY_NON_NULL(rcvdResponse);
323 recvPdu = rcvdResponse->pdu;
325 result = ParseCoAPPdu(recvPdu, rcvdUri, NULL, &sequenceNumber, &maxAge,
326 &clientResponse.numRcvdVendorSpecificHeaderOptions,
327 clientResponse.rcvdVendorSpecificHeaderOptions,
328 &rcvdBlock1, &rcvdBlock2, NULL, &rcvdSize2, bufRes);
330 VERIFY_SUCCESS(result, OC_STACK_OK);
332 OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u", sequenceNumber);
333 OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", maxAge);
334 OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes);
336 if(sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER)
338 isObserveNotification = 1;
339 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
343 if(!strcmp((char *)rcvdUri, (char *)OC_PRESENCE_URI)){
346 isPresenceNotification = 1;
347 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
348 tok = strtok_r((char *)bufRes, "[:]}", &tokSavePtr);
349 bufRes[strlen((char *)bufRes)] = ':';
350 tok = strtok_r(NULL, "[:]}", &tokSavePtr);
351 bufRes[strlen((char *)bufRes)] = ':';
352 VERIFY_NON_NULL(tok);
353 sequenceNumber = (uint32_t )atol(tok);
354 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", sequenceNumber);
355 tok = strtok_r(NULL, "[:]}", &tokSavePtr);
356 VERIFY_NON_NULL(tok);
357 maxAge = (uint32_t )atol(tok);
358 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", maxAge);
359 tok = strtok_r(NULL, "[:]}", &tokSavePtr);
361 bufRes[strlen((char *)bufRes)] = ':';
362 resourceTypeName = (char *)OCMalloc(strlen(tok));
363 if(!resourceTypeName)
367 strcpy(resourceTypeName, tok);
368 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
371 bufRes[strlen((char *)bufRes)] = ']';
375 // fill OCCoAPToken structure
376 RetrieveOCCoAPToken(recvPdu, &rcvdToken);
377 OC_LOG_V(INFO, TAG,"Received a pdu with Token", rcvdToken.tokenLength);
378 OC_LOG_BUFFER(INFO, TAG, rcvdToken.token, rcvdToken.tokenLength);
380 // fill OCClientResponse structure
381 result = FormOCClientResponse(&clientResponse, CoAPToOCResponseCode(recvPdu->hdr->code),
382 (OCDevAddr *) &(rcvdResponse->remote), sequenceNumber, bufRes);
383 VERIFY_SUCCESS(result, OC_STACK_OK);
385 cbNode = GetClientCB(&rcvdToken, NULL, NULL);
388 // Check if the application subscribed for presence
391 // get the address of the remote
392 OCDevAddrToIPv4Addr((OCDevAddr *) &(rcvdResponse->remote), remoteIpAddr,
393 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
394 OCDevAddrToPort((OCDevAddr *) &(rcvdResponse->remote), &remotePortNu);
395 sprintf((char *)fullUri, "coap://%d.%d.%d.%d:%d%s",
396 remoteIpAddr[0],remoteIpAddr[1],remoteIpAddr[2],remoteIpAddr[3],
397 remotePortNu,rcvdUri);
398 cbNode = GetClientCB(NULL, NULL, fullUri);
401 // Check if application subscribed for multicast presence
404 sprintf((char *)fullUri, "%s%s", OC_MULTICAST_IP, rcvdUri);
405 cbNode = GetClientCB(NULL, NULL, fullUri);
406 isMulticastPresence = 1;
407 isPresenceNotification = 0;
411 // fill OCResponse structure
412 result = FormOCResponse(&response, cbNode, maxAge, &clientResponse);
413 VERIFY_SUCCESS(result, OC_STACK_OK);
417 if(!isObserveNotification)
420 if(!isPresenceNotification)
423 OC_LOG(INFO, TAG, PCF("Received a regular response"));
424 if(recvPdu->hdr->type == COAP_MESSAGE_CON)
426 sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0,
427 recvPdu->hdr->id, NULL, NULL, NULL);
428 VERIFY_NON_NULL(sendPdu);
429 result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote,
431 (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
437 if(isObserveNotification)
439 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
440 if(recvPdu->hdr->type == COAP_MESSAGE_CON)
442 sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0,
443 recvPdu->hdr->id, NULL, NULL, NULL);
444 VERIFY_NON_NULL(sendPdu);
445 result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote,
447 (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
449 //TODO: check the standard for methods to detect wrap around condition
450 if(cbNode->method == OC_REST_OBSERVE &&
451 (clientResponse.sequenceNumber <= cbNode->sequenceNumber ||
452 (clientResponse.sequenceNumber > cbNode->sequenceNumber &&
453 clientResponse.sequenceNumber == (MAX_SEQUENCE_NUMBER))))
455 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
456 Ignoring Incoming:%d Against Current:%d.",
457 clientResponse.sequenceNumber, cbNode->sequenceNumber);
460 if(clientResponse.sequenceNumber > cbNode->sequenceNumber){
461 cbNode->sequenceNumber = clientResponse.sequenceNumber;
467 if(isPresenceNotification)
469 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
470 if(!cbNode->presence)
472 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
473 VERIFY_NON_NULL(cbNode->presence);
474 cbNode->presence->timeOut = NULL;
475 cbNode->presence->timeOut = (uint32_t *)
476 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
477 if(!(cbNode->presence->timeOut)){
478 OCFree(cbNode->presence);
484 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
485 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
488 OCFree(cbNode->presence->timeOut);
489 OCFree(cbNode->presence);
490 cbNode->presence = NULL;
495 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
496 cbNode->presence->TTL = maxAge;
497 for(int index = 0; index < PresenceTimeOutSize; index++)
499 lowerBound = GetTime(((float)(PresenceTimeOut[index])
500 /(float)100)*(float)cbNode->presence->TTL);
501 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
502 /(float)100)*(float)cbNode->presence->TTL);
503 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
504 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
505 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
506 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d", cbNode->presence->timeOut[index]);
508 cbNode->presence->TTLlevel = 0;
509 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
510 if(cbNode->sequenceNumber == clientResponse.sequenceNumber)
512 OC_LOG(INFO, TAG, PCF("===============No presence change"));
515 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
516 cbNode->sequenceNumber = clientResponse.sequenceNumber;;
519 // Ensure that a filter is actually applied.
520 if(resourceTypeName && response->cbNode->filterResourceType)
522 if(!findResourceType(response->cbNode->filterResourceType, resourceTypeName))
528 else if(isMulticastPresence)
530 // Check if the same nonce for a given host
531 OCMulticastNode* mcNode = NULL;
532 unsigned char senderUri[MAX_URI_LENGTH] = { 0 };
533 sprintf((char *)senderUri, "%d.%d.%d.%d:%d",
534 remoteIpAddr[0],remoteIpAddr[1],remoteIpAddr[2],remoteIpAddr[3],
536 mcNode = GetMCPresenceNode(senderUri);
540 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
541 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
544 OCFree(cbNode->presence->timeOut);
545 OCFree(cbNode->presence);
546 cbNode->presence = NULL;
549 else if(mcNode != NULL)
551 if(mcNode->nonce == clientResponse.sequenceNumber)
553 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
556 mcNode->nonce = clientResponse.sequenceNumber;
560 uint32_t uriLen = strlen((char*)senderUri);
561 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
564 memcpy(uri, senderUri, (uriLen + 1));
569 PCF("===============No Memory for URI to store in the presence node"));
572 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
573 clientResponse.sequenceNumber);
574 if(result == OC_STACK_NO_MEMORY)
577 PCF("===============No Memory for Multicast Presence Node"));
582 // Ensure that a filter is actually applied.
583 if(resourceTypeName && response->cbNode->filterResourceType)
585 if(!findResourceType(response->cbNode->filterResourceType, resourceTypeName))
593 HandleStackResponses(response);
595 else if(!cbNode && isObserveNotification)
597 OC_LOG(INFO, TAG, PCF("Received an observe notification, but I do not have callback \
598 ------------ sending RESET"));
599 sendPdu = GenerateCoAPPdu(COAP_MESSAGE_RST, 0,
600 recvPdu->hdr->id, NULL, NULL, NULL);
601 VERIFY_NON_NULL(sendPdu);
602 result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote, sendPdu,
603 (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
604 VERIFY_SUCCESS(result, OC_STACK_OK);
607 else if(!cbNode && isPresenceNotification)
609 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
610 ------------ ignoring"));
615 OC_LOG(INFO, TAG, PCF("Received a response, but I do not have callback. \
616 ------------ sending RESET"));
617 sendPdu = GenerateCoAPPdu(COAP_MESSAGE_RST, 0,
618 recvPdu->hdr->id, NULL, NULL, NULL);
619 VERIFY_NON_NULL(sendPdu);
620 result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote, sendPdu,
621 (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
622 VERIFY_SUCCESS(result, OC_STACK_OK);
625 OCFree(resourceTypeName);
629 //=============================================================================
631 //=============================================================================
634 * Initialize the CoAP client or server with its IPv4 address and CoAP port
637 * IP Address of host device
639 * Port of host device
641 * Host device is client, server, or client-server
647 OCStackResult OCInitCoAP(const char *address, uint16_t port, OCMode mode) {
649 OCStackResult ret = OC_STACK_ERROR;
651 TODO ("Below should go away and be replaced by OC_LOG");
652 coap_log_t log_level = (coap_log_t)(LOG_DEBUG + 1);
654 uint8_t ipAddr[4] = { 0 };
655 uint16_t parsedPort = 0;
657 OC_LOG(INFO, TAG, PCF("Entering OCInitCoAP"));
659 coap_set_log_level(log_level);
663 if (!ParseIPv4Address((unsigned char *) address, ipAddr, &parsedPort))
665 ret = OC_STACK_ERROR;
669 OC_LOG_V(INFO, TAG, "Parsed IP Address %d.%d.%d.%d",
670 ipAddr[0],ipAddr[1],ipAddr[2],ipAddr[3]);
673 gCoAPCtx = coap_new_context(ipAddr, port);
674 VERIFY_NON_NULL(gCoAPCtx);
676 // To allow presence notification work we need to init socket gCoAPCtx->sockfd_wellknown
677 // for servers as well as clients
678 OCBuildIPv4Address(coapWKIpAddr[0], coapWKIpAddr[1], coapWKIpAddr[2],
679 coapWKIpAddr[3], COAP_DEFAULT_PORT, &mcastAddr);
681 coap_join_wellknown_group(gCoAPCtx,
682 (coap_address_t* )&mcastAddr), 0);
684 coap_register_request_handler(gCoAPCtx, HandleCoAPRequests);
685 coap_register_response_handler(gCoAPCtx, HandleCoAPResponses);
686 coap_register_ack_rst_handler(gCoAPCtx, HandleCoAPAckRst);
691 if (ret != OC_STACK_OK)
699 * Discover OC resources
701 * @param method - method to perform on the resource
702 * @param qos - Quality of Service the request will be sent on
703 * @param token - token which will added to the request
704 * @param Uri - URI of the resource to interact with
705 * @param payload - the request payload to be added to the request before sending
706 * by the stack when discovery or resource interaction is complete
707 * @param options - The address of an array containing the vendor specific
708 * header options to be sent with the request
713 OCStackResult OCDoCoAPResource(OCMethod method, OCQualityOfService qos, OCCoAPToken * token,
714 const char *Uri, const char *payload, OCHeaderOption * options, uint8_t numOptions)
717 OCStackResult ret = OC_STACK_ERROR;
718 coap_pdu_t *pdu = NULL;
721 uint8_t ipAddr[4] = { 0 };
723 coap_list_t *optList = NULL;
726 uint32_t observeOption;
727 coap_send_flags_t flag = (coap_send_flags_t)0;
729 OC_LOG(INFO, TAG, PCF("Entering OCDoCoAPResource"));
732 OC_LOG_V(INFO, TAG, "URI = %s", Uri);
733 VERIFY_SUCCESS(coap_split_uri((unsigned char * )Uri, strlen(Uri), &uri), OC_STACK_OK);
735 // Generate the destination address
736 if (uri.host.length && ParseIPv4Address(uri.host.s, ipAddr, &port)) {
737 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], uri.port,
743 VERIFY_SUCCESS(FormOptionList(&optList, NULL, NULL, NULL,
744 (uint16_t*)&uri.port, uri.path.length, uri.path.s, uri.query.length,
745 uri.query.s, options, numOptions), OC_STACK_OK);
747 //TODO : Investigate the scenario where there will be no uri for OCDoCoAPResource
748 flag = (coap_send_flags_t) (uri.secure ? SEND_SECURE_PORT : 0);
749 OC_LOG_V(DEBUG, TAG, "uri.host.s %s", uri.host.s);
750 OC_LOG_V(DEBUG, TAG, "uri.path.s %s", uri.path.s);
751 OC_LOG_V(DEBUG, TAG, "uri.port %d", uri.port);
752 OC_LOG_V(DEBUG, TAG, "uri.query.s %s", uri.query.s);
753 OC_LOG_V(DEBUG, TAG, "secure uri %d", uri.secure);
756 coapMsgType = OCToCoAPQoS(qos);
758 // Decide method type
762 case OC_REST_PRESENCE:
764 coapMethod = COAP_REQUEST_GET;
767 coapMethod = COAP_REQUEST_PUT;
770 coapMethod = COAP_REQUEST_POST;
773 coapMethod = COAP_REQUEST_DELETE;
775 case OC_REST_OBSERVE_ALL:
776 case OC_REST_OBSERVE:
777 case OC_REST_CANCEL_OBSERVE:
778 coapMethod = COAP_REQUEST_GET;
779 observeOption = (method == OC_REST_CANCEL_OBSERVE)?
780 OC_OBSERVE_DEREGISTER:OC_OBSERVE_REGISTER;
781 coap_insert(&optList, CreateNewOptionNode(COAP_OPTION_OBSERVE,
782 sizeof(observeOption), (uint8_t *)&observeOption), OrderOptions);
785 coapMethod = OC_REST_NOMETHOD;
786 OC_LOG(FATAL, TAG, PCF("OCDoCoAPResource only supports GET, PUT, & OBSERVE methods"));
790 VERIFY_NON_NULL(gCoAPCtx);
791 pdu = GenerateCoAPPdu(coapMsgType, coapMethod,
792 coap_new_message_id(gCoAPCtx), token,
793 (unsigned char*) payload, optList);
794 VERIFY_NON_NULL(pdu);
796 ret = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &dst, pdu, flag);
799 if (ret!= OC_STACK_OK)
801 OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu"));
806 OCStackResult OCDoCoAPResponse(OCServerProtocolResponse *response)
808 OCStackResult result = OC_STACK_ERROR;
809 coap_pdu_t * sendPdu = NULL;
810 coap_list_t *optList = NULL;
811 uint8_t msgType = COAP_MESSAGE_NON;
812 uint8_t mediaType = COAP_MEDIATYPE_APPLICATION_JSON;
813 uint32_t maxAge = 0x2ffff;
814 coap_send_flags_t sendFlag = (coap_send_flags_t)0;
816 //uint32_t observeOption = OC_OBSERVE_NO_OPTION;
817 //OCStackResult responseResult;
819 OC_LOG(INFO, TAG, PCF("Entering OCDoCoAPResponse"));
821 if(response->notificationFlag && response->qos == OC_HIGH_QOS)
823 msgType = COAP_MESSAGE_CON;
825 else if(response->notificationFlag && response->qos != OC_HIGH_QOS)
827 msgType = COAP_MESSAGE_NON;
829 else if(!response->notificationFlag && !response->slowFlag && response->qos == OC_HIGH_QOS)
831 msgType = COAP_MESSAGE_ACK;
833 else if(!response->notificationFlag && response->slowFlag && response->qos == OC_HIGH_QOS)
835 msgType = COAP_MESSAGE_CON;
837 else if(!response->notificationFlag)
839 msgType = COAP_MESSAGE_NON;
842 if(response->coapID == 0)
844 response->coapID = coap_new_message_id(gCoAPCtx);
847 if (response->observationOption != OC_OBSERVE_NO_OPTION)
849 result = FormOptionList(&optList, &mediaType, &maxAge,
850 &response->observationOption, NULL,
851 strlen((char *)response->resourceUri), response->resourceUri,
853 response->sendVendorSpecificHeaderOptions,
854 response->numSendVendorSpecificHeaderOptions);
858 result = FormOptionList(&optList, &mediaType, &maxAge,
860 strlen((char *)response->resourceUri), response->resourceUri,
862 response->sendVendorSpecificHeaderOptions,
863 response->numSendVendorSpecificHeaderOptions);
865 VERIFY_SUCCESS(result, OC_STACK_OK);
867 sendPdu = GenerateCoAPPdu(msgType, OCToCoAPResponseCode(response->result),
868 response->coapID, response->requestToken, (unsigned char *)response->payload,
871 VERIFY_NON_NULL(sendPdu);
872 coap_show_pdu(sendPdu);
874 sendFlag = (coap_send_flags_t)(response->delayedResNeeded ? SEND_DELAYED : 0);
875 sendFlag = (coap_send_flags_t)( sendFlag | (response->secured ? SEND_SECURE_PORT : 0));
877 if (SendCoAPPdu(gCoAPCtx, (coap_address_t *) (response->requesterAddr), sendPdu, sendFlag)
880 OC_LOG(ERROR, TAG, PCF("A problem occurred in sending a pdu"));
881 return OC_STACK_ERROR;
887 OC_LOG(ERROR, TAG, PCF("Error formatting server response"));
888 return OC_STACK_ERROR;
893 * Stop the CoAP client or server processing
895 * @return 0 - success, else - TBD error
897 OCStackResult OCStopCoAP() {
898 OC_LOG(INFO, TAG, PCF("Entering OCStopCoAP"));
899 coap_free_context(gCoAPCtx);
905 * Called in main loop of CoAP client or server. Allows low-level CoAP processing of
906 * send, receive, timeout, discovery, callbacks, etc.
908 * @return 0 - success, else - TBD error
910 OCStackResult OCProcessCoAP() {
912 OC_LOG(INFO, TAG, PCF("Entering OCProcessCoAP"));
914 read = coap_read(gCoAPCtx, gCoAPCtx->sockfd);
916 OC_LOG(INFO, TAG, PCF("This is a Unicast<============"));
918 if (-1 != gCoAPCtx->sockfd_wellknown) {
919 read = coap_read(gCoAPCtx, gCoAPCtx->sockfd_wellknown);
922 OC_LOG(INFO, TAG, PCF("This is a Multicast<==========="));
925 if (-1 != gCoAPCtx->sockfd_dtls) {
926 read = coap_read(gCoAPCtx, gCoAPCtx->sockfd_dtls);
929 OC_LOG(INFO, TAG, PCF("This is a Secure packet<==========="));
932 coap_dispatch(gCoAPCtx);
934 HandleSendQueue(gCoAPCtx);
941 * Retrieve the info about the end-point where resource is being hosted.
942 * Currently, this method only provides the IP port with which the socket
945 * @return 0 - success, else - TBD error
947 OCStackResult OCGetResourceEndPointInfo (OCResource *resPtr, void *info) {
949 OCStackResult result = OC_STACK_ERROR;
951 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceEndPointInfo"));
952 VERIFY_NON_NULL(resPtr);
953 VERIFY_NON_NULL(info);
955 sfd = (resPtr->resourceProperties & OC_SECURE) ? gCoAPCtx->sockfd_dtls :
958 if (OCGetSocketInfo(sfd, (uint16_t*)info) == ERR_SUCCESS)
959 result = OC_STACK_OK;