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 //=============================================================================
26 #include "ocstackconfig.h"
27 #include "occlientcb.h"
28 #include "ocobserve.h"
39 //=============================================================================
41 //=============================================================================
42 #define TAG PCF("OCCoAP")
43 #define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \
44 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
45 #define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg); goto exit;} }
47 //=============================================================================
49 //=============================================================================
50 #define COAP_BLOCK_FILL_VALUE (0xFF)
52 //=============================================================================
54 //=============================================================================
56 static uint8_t coapWKIpAddr[] = { 224, 0, 1, 187 };
57 static coap_context_t *gCoAPCtx = NULL;
59 //=============================================================================
61 //=============================================================================
63 //generate a coap token
64 void OCGenerateCoAPToken(OCCoAPToken * token)
68 token->tokenLength = MAX_TOKEN_LENGTH;
69 OCFillRandomMem((uint8_t*)token->token, token->tokenLength);
73 //This function is called back by libcoap when ack or rst are received
74 static void HandleCoAPAckRst(struct coap_context_t * ctx, uint8_t msgType,
75 const coap_queue_t * sentQueue){
79 coap_pdu_t * sentPdu = sentQueue->pdu;
80 OCStackResult result = OC_STACK_ERROR;
81 uint32_t observationOption = OC_OBSERVE_NO_OPTION;
82 // {{0}} to eliminate warning for known compiler bug 53119
83 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119
84 OCCoAPToken sentToken = {{0}};
86 result = ParseCoAPPdu(sentPdu, NULL, NULL, &observationOption, NULL, NULL, NULL,
87 NULL, NULL, NULL, NULL, NULL);
88 VERIFY_SUCCESS(result, OC_STACK_OK);
90 // fill OCCoAPToken structure
91 RetrieveOCCoAPToken(sentPdu, &sentToken);
93 if(msgType == COAP_MESSAGE_RST)
95 if(myStackMode != OC_CLIENT)
97 result = OCStackFeedBack(&sentToken, OC_OBSERVER_NOT_INTERESTED);
98 if(result == OC_STACK_OK)
101 "Received RST, removing all queues associated with Token %d bytes",
102 sentToken.tokenLength);
103 OC_LOG_BUFFER(INFO, TAG, sentToken.token, sentToken.tokenLength);
104 coap_cancel_all_messages(ctx, &sentQueue->remote, sentToken.token,
105 sentToken.tokenLength);
109 else if(observationOption != OC_OBSERVE_NO_OPTION && msgType == COAP_MESSAGE_ACK)
111 OC_LOG_V(DEBUG, TAG, "Received ACK, for Token %d bytes",sentToken.tokenLength);
112 OC_LOG_BUFFER(INFO, TAG, sentToken.token, sentToken.tokenLength);
113 // now the observer is still interested
114 if(myStackMode != OC_CLIENT)
116 OCStackFeedBack(&sentToken, OC_OBSERVER_STILL_INTERESTED);
123 //This function is called back by libcoap when a request is received
124 static void HandleCoAPRequests(struct coap_context_t *ctx,
125 const coap_queue_t * rcvdRequest)
129 OCServerProtocolRequest protocolRequest;
130 memset(&protocolRequest, 0, sizeof(OCServerProtocolRequest));
131 coap_block_t rcvdBlock1;
132 coap_block_t rcvdBlock2;
133 memset(&rcvdBlock1, COAP_BLOCK_FILL_VALUE, sizeof(coap_block_t));
134 memset(&rcvdBlock2, COAP_BLOCK_FILL_VALUE, sizeof(coap_block_t));
135 uint16_t rcvdSize1 = 0;
136 coap_pdu_t * rcvdPdu = rcvdRequest->pdu;
137 coap_pdu_t * sendPdu = NULL;
138 coap_send_flags_t sendFlag;
139 OCStackResult result = OC_STACK_ERROR;
140 OCStackResult requestResult = OC_STACK_ERROR;
142 if(myStackMode == OC_CLIENT)
144 //TODO: should the client be responding to requests?
148 protocolRequest.observationOption = OC_OBSERVE_NO_OPTION;
149 protocolRequest.qos = (rcvdPdu->hdr->type == COAP_MESSAGE_CON) ?
150 OC_HIGH_QOS : OC_LOW_QOS;
151 protocolRequest.coapID = rcvdPdu->hdr->id;
152 protocolRequest.delayedResNeeded = rcvdRequest->delayedResNeeded;
153 protocolRequest.secured = rcvdRequest->secure;
155 // fill OCCoAPToken structure
156 RetrieveOCCoAPToken(rcvdPdu, &protocolRequest.requestToken);
157 OC_LOG_V(INFO, TAG, " Token received %d bytes",
158 protocolRequest.requestToken.tokenLength);
159 OC_LOG_BUFFER(INFO, TAG, protocolRequest.requestToken.token,
160 protocolRequest.requestToken.tokenLength);
163 memcpy(&protocolRequest.requesterAddr, (OCDevAddr *) &rcvdRequest->remote,
166 // Retrieve Uri and Query from received coap pdu
167 result = ParseCoAPPdu(rcvdPdu, protocolRequest.resourceUrl,
168 protocolRequest.query,
169 &(protocolRequest.observationOption), NULL,
170 &(protocolRequest.numRcvdVendorSpecificHeaderOptions),
171 protocolRequest.rcvdVendorSpecificHeaderOptions,
172 &rcvdBlock1, &rcvdBlock2, &rcvdSize1, NULL,
173 protocolRequest.reqJSONPayload);
174 VERIFY_SUCCESS(result, OC_STACK_OK);
176 switch (rcvdPdu->hdr->code)
178 case COAP_REQUEST_GET:
180 protocolRequest.method = OC_REST_GET;
183 case COAP_REQUEST_POST:
185 protocolRequest.method = OC_REST_POST;
188 case COAP_REQUEST_DELETE:
190 protocolRequest.method = OC_REST_DELETE;
193 case COAP_REQUEST_PUT:
195 protocolRequest.method = OC_REST_PUT;
200 OC_LOG_V(ERROR, TAG, "Received CoAP method %d not supported",
206 if(rcvdBlock1.szx != 7)
208 protocolRequest.reqPacketSize = 1 << (rcvdBlock1.szx + 4);
209 protocolRequest.reqMorePacket = rcvdBlock1.m;
210 protocolRequest.reqPacketNum = rcvdBlock1.num;
214 // No block1 received
215 rcvdSize1 = strlen((const char *)protocolRequest.reqJSONPayload)+1;
216 protocolRequest.reqTotalSize = rcvdSize1;
219 if(rcvdBlock2.szx != 7)
221 protocolRequest.resPacketSize = 1 << (rcvdBlock2.szx + 4);
222 protocolRequest.resPacketNum = rcvdBlock2.num;
225 requestResult = HandleStackRequests(&protocolRequest);
227 if(requestResult == OC_STACK_VIRTUAL_DO_NOT_HANDLE ||
228 requestResult == OC_STACK_OK ||
229 requestResult == OC_STACK_RESOURCE_CREATED ||
230 requestResult == OC_STACK_RESOURCE_DELETED)
234 else if(requestResult == OC_STACK_NO_MEMORY ||
235 requestResult == OC_STACK_ERROR ||
236 requestResult == OC_STACK_NOTIMPL ||
237 requestResult == OC_STACK_NO_RESOURCE ||
238 requestResult == OC_STACK_RESOURCE_ERROR)
240 // TODO: should we send an error also when we receive a non-secured request to a secure resource?
241 // TODO: should we consider some sort of error response
242 OC_LOG(DEBUG, TAG, PCF("We should send some sort of error message"));
243 // generate the pdu, if the request was CON, then the response is ACK, otherwire NON
244 sendPdu = GenerateCoAPPdu((rcvdPdu->hdr->type == COAP_MESSAGE_CON)? COAP_MESSAGE_ACK : COAP_MESSAGE_NON,
245 OCToCoAPResponseCode(requestResult), rcvdPdu->hdr->id,
246 &protocolRequest.requestToken, NULL, NULL);
247 VERIFY_NON_NULL(sendPdu);
248 coap_show_pdu(sendPdu);
249 sendFlag = (coap_send_flags_t)(rcvdRequest->secure ? SEND_SECURE_PORT : 0);
250 if(SendCoAPPdu(gCoAPCtx, (coap_address_t*) &(rcvdRequest->remote), sendPdu,
253 OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu"));
257 else if(requestResult == OC_STACK_SLOW_RESOURCE)
259 if(rcvdPdu->hdr->type == COAP_MESSAGE_CON)
261 // generate the pdu, if the request was CON, then the response is ACK, otherwire NON
262 sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0, rcvdPdu->hdr->id,
264 VERIFY_NON_NULL(sendPdu);
265 coap_show_pdu(sendPdu);
267 sendFlag = (coap_send_flags_t)(rcvdRequest->secure ? SEND_SECURE_PORT : 0);
268 if(SendCoAPPdu(gCoAPCtx, (coap_address_t*) &(rcvdRequest->remote), sendPdu,
271 OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu"));
283 uint32_t GetTime(float afterSeconds)
287 return now + (uint32_t)(afterSeconds * COAP_TICKS_PER_SECOND);
290 //This function is called back by libcoap when a response is received
291 static void HandleCoAPResponses(struct coap_context_t *ctx,
292 const coap_queue_t * rcvdResponse) {
293 OCResponse * response = NULL;
294 OCCoAPToken rcvdToken;
295 OCClientResponse clientResponse;
296 memset(&clientResponse, 0, sizeof(OCClientResponse));
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)){
344 isPresenceNotification = 1;
345 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
346 tok = strtok((char *)bufRes, "[:]");
347 tok = strtok(NULL, "[:]");
348 VERIFY_NON_NULL(tok);
349 sequenceNumber = (uint32_t )atol(tok);
350 OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", sequenceNumber);
351 tok = strtok(NULL, "[:]");
352 VERIFY_NON_NULL(tok);
353 maxAge = (uint32_t )atol(tok);
354 OC_LOG_V(DEBUG, TAG, "The received TTL is %u", maxAge);
355 tok = strtok(NULL, "[:]");
356 bufRes[strlen((char *)bufRes)] = ':';
358 resourceTypeName = (char *)OCMalloc(strlen(tok));
359 if(!resourceTypeName)
363 strcpy(resourceTypeName, tok);
364 bufRes[strlen((char *)bufRes)] = ':';
365 OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s",
371 // fill OCCoAPToken structure
372 RetrieveOCCoAPToken(recvPdu, &rcvdToken);
373 OC_LOG_V(INFO, TAG,"Received a pdu with Token", rcvdToken.tokenLength);
374 OC_LOG_BUFFER(INFO, TAG, rcvdToken.token, rcvdToken.tokenLength);
376 // fill OCClientResponse structure
377 result = FormOCClientResponse(&clientResponse, CoAPToOCResponseCode(recvPdu->hdr->code),
378 (OCDevAddr *) &(rcvdResponse->remote), sequenceNumber, bufRes);
379 VERIFY_SUCCESS(result, OC_STACK_OK);
381 cbNode = GetClientCB(&rcvdToken, NULL, NULL);
384 // Check if the application subcribed for presence
387 // get the address of the remote
388 OCDevAddrToIPv4Addr((OCDevAddr *) &(rcvdResponse->remote), remoteIpAddr,
389 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
390 OCDevAddrToPort((OCDevAddr *) &(rcvdResponse->remote), &remotePortNu);
391 sprintf((char *)fullUri, "coap://%d.%d.%d.%d:%d%s",
392 remoteIpAddr[0],remoteIpAddr[1],remoteIpAddr[2],remoteIpAddr[3],
393 remotePortNu,rcvdUri);
394 cbNode = GetClientCB(NULL, NULL, fullUri);
397 // Check if application subscribed for multicast presence
400 sprintf((char *)fullUri, "%s%s", OC_MULTICAST_IP, rcvdUri);
401 cbNode = GetClientCB(NULL, NULL, fullUri);
402 isMulticastPresence = 1;
406 // fill OCResponse structure
407 result = FormOCResponse(&response, cbNode, maxAge, &clientResponse);
408 VERIFY_SUCCESS(result, OC_STACK_OK);
412 if(!isObserveNotification)
415 if(!isPresenceNotification)
418 OC_LOG(INFO, TAG, PCF("Received a regular response"));
419 if(recvPdu->hdr->type == COAP_MESSAGE_CON)
421 sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0,
422 recvPdu->hdr->id, NULL, NULL, NULL);
423 VERIFY_NON_NULL(sendPdu);
424 result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote,
426 (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
432 if(isObserveNotification)
434 OC_LOG(INFO, TAG, PCF("Received an observe notification"));
435 if(recvPdu->hdr->type == COAP_MESSAGE_CON)
437 sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0,
438 recvPdu->hdr->id, NULL, NULL, NULL);
439 VERIFY_NON_NULL(sendPdu);
440 result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote,
442 (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
444 //TODO: check the standard for methods to detect wrap around condition
445 if(cbNode->method == OC_REST_OBSERVE &&
446 (clientResponse.sequenceNumber <= cbNode->sequenceNumber ||
447 (clientResponse.sequenceNumber > cbNode->sequenceNumber &&
448 clientResponse.sequenceNumber == (MAX_SEQUENCE_NUMBER))))
450 OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \
451 Ignoring Incoming:%d Against Current:%d.",
452 clientResponse.sequenceNumber, cbNode->sequenceNumber);
455 if(clientResponse.sequenceNumber > cbNode->sequenceNumber){
456 cbNode->sequenceNumber = clientResponse.sequenceNumber;
462 if(isPresenceNotification)
464 OC_LOG(INFO, TAG, PCF("Received a presence notification"));
465 if(!cbNode->presence)
467 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
468 VERIFY_NON_NULL(cbNode->presence);
469 cbNode->presence->timeOut = NULL;
470 cbNode->presence->timeOut = (uint32_t *)
471 OCMalloc(PresenceTimeOutSize * sizeof(uint32_t));
472 if(!(cbNode->presence->timeOut)){
473 OCFree(cbNode->presence);
479 OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
480 response->clientResponse->result = OC_STACK_PRESENCE_STOPPED;
483 OCFree(cbNode->presence->timeOut);
484 OCFree(cbNode->presence);
485 cbNode->presence = NULL;
490 OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0));
491 cbNode->presence->TTL = maxAge;
492 for(int index = 0; index < PresenceTimeOutSize; index++)
494 lowerBound = GetTime(((float)(PresenceTimeOut[index])
495 /(float)100)*(float)cbNode->presence->TTL);
496 higherBound = GetTime(((float)(PresenceTimeOut[index + 1])
497 /(float)100)*(float)cbNode->presence->TTL);
498 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
499 OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound);
500 OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound);
501 OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d", cbNode->presence->timeOut[index]);
503 cbNode->presence->TTLlevel = 0;
504 OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel);
505 if(cbNode->sequenceNumber == clientResponse.sequenceNumber)
507 OC_LOG(INFO, TAG, PCF("===============No presence change"));
510 OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack"));
511 cbNode->sequenceNumber = clientResponse.sequenceNumber;;
514 if(resourceTypeName && response->cbNode->filterResourceType)
516 if(strcmp(resourceTypeName,
517 (const char *)response->cbNode->filterResourceType)!=0)
519 //Ignore presence callback if resource type does not match filter.
524 else if(isMulticastPresence)
526 // Check if the same nonce for a given host
527 OCMulticastNode* mcNode = NULL;
528 unsigned char senderUri[MAX_URI_LENGTH] = { 0 };
529 sprintf((char *)senderUri, "%d.%d.%d.%d:%d",
530 remoteIpAddr[0],remoteIpAddr[1],remoteIpAddr[2],remoteIpAddr[3],
532 mcNode = GetMCPresenceNode(senderUri);
536 if(mcNode->nonce == clientResponse.sequenceNumber)
538 OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
541 mcNode->nonce = clientResponse.sequenceNumber;
545 uint32_t uriLen = strlen((char*)senderUri);
546 unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
549 memcpy(uri, senderUri, (uriLen + 1));
554 PCF("===============No Memory for URI to store in the presence node"));
557 result = AddMCPresenceNode(&mcNode, (unsigned char*) uri,
558 clientResponse.sequenceNumber);
559 if(result == OC_STACK_NO_MEMORY)
562 PCF("===============No Memory for Multicast Presence Node"));
567 if(resourceTypeName && response->cbNode->filterResourceType)
569 if(strcmp(resourceTypeName,
570 (const char *)response->cbNode->filterResourceType)!=0)
572 //Ignore presence callback if resource type does not match filter.
580 HandleStackResponses(response);
582 else if(!cbNode && isObserveNotification)
584 OC_LOG(INFO, TAG, PCF("Received an observe notification, but I do not have callback \
585 ------------ sending RESET"));
586 sendPdu = GenerateCoAPPdu(COAP_MESSAGE_RST, 0,
587 recvPdu->hdr->id, NULL, NULL, NULL);
588 VERIFY_NON_NULL(sendPdu);
589 result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote, sendPdu,
590 (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
591 VERIFY_SUCCESS(result, OC_STACK_OK);
594 else if(!cbNode && isPresenceNotification)
596 OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
597 ------------ ignoring"));
602 OC_LOG(INFO, TAG, PCF("Received a response, but I do not have callback. \
603 ------------ sending RESET"));
604 sendPdu = GenerateCoAPPdu(COAP_MESSAGE_RST, 0,
605 recvPdu->hdr->id, NULL, NULL, NULL);
606 VERIFY_NON_NULL(sendPdu);
607 result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote, sendPdu,
608 (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0));
609 VERIFY_SUCCESS(result, OC_STACK_OK);
615 //=============================================================================
617 //=============================================================================
620 * Initialize the CoAP client or server with its IPv4 address and CoAP port
623 * IP Address of host device
625 * Port of host device
627 * Host device is client, server, or client-server
633 OCStackResult OCInitCoAP(const char *address, uint16_t port, OCMode mode) {
635 OCStackResult ret = OC_STACK_ERROR;
637 TODO ("Below should go away and be replaced by OC_LOG");
638 coap_log_t log_level = (coap_log_t)(LOG_DEBUG + 1);
640 uint8_t ipAddr[4] = { 0 };
641 uint16_t parsedPort = 0;
643 OC_LOG(INFO, TAG, PCF("Entering OCInitCoAP"));
645 coap_set_log_level(log_level);
649 if (!ParseIPv4Address((unsigned char *) address, ipAddr, &parsedPort))
651 ret = OC_STACK_ERROR;
655 OC_LOG_V(INFO, TAG, "Parsed IP Address %d.%d.%d.%d",
656 ipAddr[0],ipAddr[1],ipAddr[2],ipAddr[3]);
659 gCoAPCtx = coap_new_context(ipAddr, port);
660 VERIFY_NON_NULL(gCoAPCtx);
662 // To allow presence notification work we need to init socket gCoAPCtx->sockfd_wellknown
663 // for servers as well as clients
664 OCBuildIPv4Address(coapWKIpAddr[0], coapWKIpAddr[1], coapWKIpAddr[2],
665 coapWKIpAddr[3], COAP_DEFAULT_PORT, &mcastAddr);
667 coap_join_wellknown_group(gCoAPCtx,
668 (coap_address_t* )&mcastAddr), 0);
670 coap_register_request_handler(gCoAPCtx, HandleCoAPRequests);
671 coap_register_response_handler(gCoAPCtx, HandleCoAPResponses);
672 coap_register_ack_rst_handler(gCoAPCtx, HandleCoAPAckRst);
677 if (ret != OC_STACK_OK)
685 * Discover OC resources
687 * @param method - method to perform on the resource
688 * @param qos - Quality of Service the request will be sent on
689 * @param token - token which will added to the request
690 * @param Uri - URI of the resource to interact with
691 * @param payload - the request payload to be added to the request before sending
692 * by the stack when discovery or resource interaction is complete
693 * @param options - The address of an array containing the vendor specific
694 * header options to be sent with the request
699 OCStackResult OCDoCoAPResource(OCMethod method, OCQualityOfService qos, OCCoAPToken * token,
700 const char *Uri, const char *payload, OCHeaderOption * options, uint8_t numOptions)
703 OCStackResult ret = OC_STACK_ERROR;
704 coap_pdu_t *pdu = NULL;
707 uint8_t ipAddr[4] = { 0 };
709 coap_list_t *optList = NULL;
712 uint32_t observeOption;
713 coap_send_flags_t flag = (coap_send_flags_t)0;
715 OC_LOG(INFO, TAG, PCF("Entering OCDoCoAPResource"));
718 OC_LOG_V(INFO, TAG, "URI = %s", Uri);
719 VERIFY_SUCCESS(coap_split_uri((unsigned char * )Uri, strlen(Uri), &uri), OC_STACK_OK);
721 // Generate the destination address
722 if (uri.host.length && ParseIPv4Address(uri.host.s, ipAddr, &port)) {
723 OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], uri.port,
729 VERIFY_SUCCESS(FormOptionList(&optList, NULL, NULL, NULL,
730 (uint16_t*)&uri.port, uri.path.length, uri.path.s, uri.query.length,
731 uri.query.s, options, numOptions), OC_STACK_OK);
733 //TODO : Investigate the scenario where there will be no uri for OCDoCoAPResource
734 flag = (coap_send_flags_t) (uri.secure ? SEND_SECURE_PORT : 0);
735 OC_LOG_V(DEBUG, TAG, "uri.host.s %s", uri.host.s);
736 OC_LOG_V(DEBUG, TAG, "uri.path.s %s", uri.path.s);
737 OC_LOG_V(DEBUG, TAG, "uri.port %d", uri.port);
738 OC_LOG_V(DEBUG, TAG, "uri.query.s %s", uri.query.s);
739 OC_LOG_V(DEBUG, TAG, "secure uri %d", uri.secure);
742 coapMsgType = OCToCoAPQoS(qos);
744 // Decide method type
748 case OC_REST_PRESENCE:
750 coapMethod = COAP_REQUEST_GET;
753 coapMethod = COAP_REQUEST_PUT;
756 coapMethod = COAP_REQUEST_POST;
759 coapMethod = COAP_REQUEST_DELETE;
761 case OC_REST_OBSERVE_ALL:
762 case OC_REST_OBSERVE:
763 case OC_REST_CANCEL_OBSERVE:
764 coapMethod = COAP_REQUEST_GET;
765 observeOption = (method == OC_REST_CANCEL_OBSERVE)?
766 OC_OBSERVE_DEREGISTER:OC_OBSERVE_REGISTER;
767 coap_insert(&optList, CreateNewOptionNode(COAP_OPTION_OBSERVE,
768 sizeof(observeOption), (uint8_t *)&observeOption), OrderOptions);
771 coapMethod = OC_REST_NOMETHOD;
772 OC_LOG(FATAL, TAG, PCF("OCDoCoAPResource only supports GET, PUT, & OBSERVE methods"));
776 VERIFY_NON_NULL(gCoAPCtx);
777 pdu = GenerateCoAPPdu(coapMsgType, coapMethod,
778 coap_new_message_id(gCoAPCtx), token,
779 (unsigned char*) payload, optList);
780 VERIFY_NON_NULL(pdu);
782 ret = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &dst, pdu, flag);
785 if (ret!= OC_STACK_OK)
787 OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu"));
792 OCStackResult OCDoCoAPResponse(OCServerProtocolResponse *response)
794 OCStackResult result = OC_STACK_ERROR;
795 coap_pdu_t * sendPdu = NULL;
796 coap_list_t *optList = NULL;
797 uint8_t msgType = COAP_MESSAGE_NON;
798 uint8_t mediaType = COAP_MEDIATYPE_APPLICATION_JSON;
799 uint32_t maxAge = 0x2ffff;
800 coap_send_flags_t sendFlag = (coap_send_flags_t)0;
802 //uint32_t observeOption = OC_OBSERVE_NO_OPTION;
803 //OCStackResult responseResult;
805 OC_LOG(INFO, TAG, PCF("Entering OCDoCoAPResponse"));
807 if(response->notificationFlag && response->qos == OC_HIGH_QOS)
809 msgType = COAP_MESSAGE_CON;
811 else if(response->notificationFlag && response->qos != OC_HIGH_QOS)
813 msgType = COAP_MESSAGE_NON;
815 else if(!response->notificationFlag && !response->slowFlag && response->qos == OC_HIGH_QOS)
817 msgType = COAP_MESSAGE_ACK;
819 else if(!response->notificationFlag && response->slowFlag && response->qos == OC_HIGH_QOS)
821 msgType = COAP_MESSAGE_CON;
823 else if(!response->notificationFlag)
825 msgType = COAP_MESSAGE_NON;
828 if(response->coapID == 0)
830 response->coapID = coap_new_message_id(gCoAPCtx);
833 if (response->observationOption != OC_OBSERVE_NO_OPTION)
835 result = FormOptionList(&optList, &mediaType, &maxAge,
836 &response->observationOption, NULL,
837 strlen((char *)response->resourceUri), response->resourceUri,
839 response->sendVendorSpecificHeaderOptions,
840 response->numSendVendorSpecificHeaderOptions);
844 result = FormOptionList(&optList, &mediaType, &maxAge,
846 strlen((char *)response->resourceUri), response->resourceUri,
848 response->sendVendorSpecificHeaderOptions,
849 response->numSendVendorSpecificHeaderOptions);
851 VERIFY_SUCCESS(result, OC_STACK_OK);
853 sendPdu = GenerateCoAPPdu(msgType, OCToCoAPResponseCode(response->result),
854 response->coapID, response->requestToken, (unsigned char *)response->payload,
857 VERIFY_NON_NULL(sendPdu);
858 coap_show_pdu(sendPdu);
860 sendFlag = (coap_send_flags_t)(response->delayedResNeeded ? SEND_DELAYED : 0);
861 sendFlag = (coap_send_flags_t)( sendFlag | (response->secured ? SEND_SECURE_PORT : 0));
863 if (SendCoAPPdu(gCoAPCtx, (coap_address_t *) (response->requesterAddr), sendPdu, sendFlag)
866 OC_LOG(ERROR, TAG, PCF("A problem occurred in sending a pdu"));
867 return OC_STACK_ERROR;
873 OC_LOG(ERROR, TAG, PCF("Error formatting server response"));
874 return OC_STACK_ERROR;
879 * Stop the CoAP client or server processing
881 * @return 0 - success, else - TBD error
883 OCStackResult OCStopCoAP() {
884 OC_LOG(INFO, TAG, PCF("Entering OCStopCoAP"));
885 coap_free_context(gCoAPCtx);
891 * Called in main loop of CoAP client or server. Allows low-level CoAP processing of
892 * send, receive, timeout, discovery, callbacks, etc.
894 * @return 0 - success, else - TBD error
896 OCStackResult OCProcessCoAP() {
898 OC_LOG(INFO, TAG, PCF("Entering OCProcessCoAP"));
900 read = coap_read(gCoAPCtx, gCoAPCtx->sockfd);
902 OC_LOG(INFO, TAG, PCF("This is a Unicast<============"));
904 if (-1 != gCoAPCtx->sockfd_wellknown) {
905 read = coap_read(gCoAPCtx, gCoAPCtx->sockfd_wellknown);
908 OC_LOG(INFO, TAG, PCF("This is a Multicast<==========="));
911 if (-1 != gCoAPCtx->sockfd_dtls) {
912 read = coap_read(gCoAPCtx, gCoAPCtx->sockfd_dtls);
915 OC_LOG(INFO, TAG, PCF("This is a Secure packet<==========="));
918 coap_dispatch(gCoAPCtx);
920 HandleSendQueue(gCoAPCtx);
927 * Retrieve the info about the end-point where resource is being hosted.
928 * Currently, this method only provides the IP port with which the socket
931 * @return 0 - success, else - TBD error
933 OCStackResult OCGetResourceEndPointInfo (OCResource *resPtr, void *info) {
935 OCStackResult result = OC_STACK_ERROR;
937 OC_LOG(INFO, TAG, PCF("Entering OCGetResourceEndPointInfo"));
938 VERIFY_NON_NULL(resPtr);
939 VERIFY_NON_NULL(info);
941 sfd = (resPtr->resourceProperties & OC_SECURE) ? gCoAPCtx->sockfd_dtls :
944 if (OCGetSocketInfo(sfd, (uint16_t*)info) == ERR_SUCCESS)
945 result = OC_STACK_OK;