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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
32 static int UNICAST_DISCOVERY = 0;
33 static int TEST_CASE = 0;
34 static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
35 static std::string putPayload = "{\"state\":\"on\",\"power\":5}";
36 static std::string coapServerIP = "255.255.255.255";
37 static std::string coapServerPort = "5683";
38 static std::string coapServerResource = "/a/light";
40 // The handle for the observe registration
41 OCDoHandle gObserveDoHandle;
43 // The handle for observe registration
44 OCDoHandle gPresenceHandle;
46 // After this crosses a threshold client deregisters for further notifications
47 int gNumObserveNotifies = 0;
50 int gNumPresenceNotifies = 0;
54 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
55 void handleSigInt(int signum) {
56 if (signum == SIGINT) {
61 static void PrintUsage()
63 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3|4|5|6|7>");
64 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
65 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
66 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and Initiate Nonconfirmable Get Request");
67 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Nonconfirmable Put Requests");
68 OC_LOG(INFO, TAG, "-t 4 : Discover Resources and Initiate Nonconfirmable Post Requests");
69 OC_LOG(INFO, TAG, "-t 5 : Discover Resources and Initiate Nonconfirmable Delete Requests");
70 OC_LOG(INFO, TAG, "-t 6 : Discover Resources and Initiate Nonconfirmable Observe Requests");
71 OC_LOG(INFO, TAG, "-t 7 : Discover Resources and Initiate Nonconfirmable Get Request for a resource which is unavailable");
73 OC_LOG(INFO, TAG, "-t 8 : Discover Resources and Initiate Confirmable Get Request");
74 OC_LOG(INFO, TAG, "-t 9 : Discover Resources and Initiate Confirmable Post Request");
75 OC_LOG(INFO, TAG, "-t 10 : Discover Resources and Initiate Confirmable Delete Requests");
76 OC_LOG(INFO, TAG, "-t 11 : Discover Resources and Initiate Confirmable Observe Requests");
79 OC_LOG(INFO, TAG, "-t 12 : Discover Resources and Initiate Nonconfirmable presence");
80 OC_LOG(INFO, TAG, "-t 13 : Discover Resources and Initiate Nonconfirmable presence with filter");
83 OC_LOG(INFO, TAG, "-t 14 : Discover Resources and Initiate Nonconfirmable Observe Requests then cancel immediately");
84 OC_LOG(INFO, TAG, "-t 15 : Discover Resources and Initiate Nonconfirmable Get Request and add vendor specific header options");
87 OCStackResult InvokeOCDoResource(std::ostringstream &query,
88 OCMethod method, OCQualityOfService qos,
89 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
92 OCCallbackData cbData;
96 cbData.context = (void*)CTX_VAL;
99 ret = OCDoResource(&handle, method, query.str().c_str(), 0,
100 (method == OC_REST_PUT) ? putPayload.c_str() : NULL,
101 qos, &cbData, options, numOptions);
103 if (ret != OC_STACK_OK)
105 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
107 else if (method == OC_REST_OBSERVE || method == OC_REST_OBSERVE_ALL)
109 gObserveDoHandle = handle;
112 else if (method == OC_REST_PRESENCE)
114 gPresenceHandle = handle;
121 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
122 if(ctx == (void*)CTX_VAL)
124 OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
129 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
130 OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
132 return OC_STACK_DELETE_TRANSACTION;
135 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
137 if(ctx == (void*)CTX_VAL)
139 OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
144 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
145 OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response", clientResponse->resJSONPayload);
147 return OC_STACK_DELETE_TRANSACTION;
150 OCStackApplicationResult deleteReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
152 if(ctx == (void*)CTX_VAL)
154 OC_LOG(INFO, TAG, "Callback Context for DELETE recvd successfully");
159 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
160 OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response", clientResponse->resJSONPayload);
162 return OC_STACK_DELETE_TRANSACTION;
165 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
166 if(ctx == (void*)CTX_VAL)
168 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
173 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
174 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
175 OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", clientResponse->resJSONPayload);
177 if(clientResponse->rcvdVendorSpecificHeaderOptions &&
178 clientResponse->numRcvdVendorSpecificHeaderOptions)
180 OC_LOG (INFO, TAG, "Received vendor specific options");
182 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
183 for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
185 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
187 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
188 ((OCHeaderOption)rcvdOptions[i]).optionID );
189 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
190 ((OCHeaderOption)rcvdOptions[i]).optionLength);
194 return OC_STACK_DELETE_TRANSACTION;
197 OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
198 if(ctx == (void*)CTX_VAL)
200 OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
205 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
206 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
207 OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d", gNumObserveNotifies);
208 OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response", clientResponse->resJSONPayload);
209 gNumObserveNotifies++;
210 if (gNumObserveNotifies == 50) //large number to test observing in DELETE case.
212 if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON){
214 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
215 OC_LOG(ERROR, TAG, "Observe cancel error");
217 return OC_STACK_DELETE_TRANSACTION;
218 }else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM){
219 if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK){
220 OC_LOG(ERROR, TAG, "Observe cancel error");
224 if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER){
225 OC_LOG(INFO, TAG, "This also serves as a registration confirmation");
226 }else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER){
227 OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
228 return OC_STACK_DELETE_TRANSACTION;
229 }else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION){
230 OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
231 return OC_STACK_DELETE_TRANSACTION;
234 return OC_STACK_KEEP_TRANSACTION;
237 OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
238 if(ctx == (void*)CTX_VAL)
240 OC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully");
245 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
246 OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
247 OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d", gNumPresenceNotifies);
248 OC_LOG_V(INFO, TAG, "JSON = %s =============> Presence Response", clientResponse->resJSONPayload);
249 gNumPresenceNotifies++;
250 if (gNumPresenceNotifies == 20)
252 if (OCCancel (gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
253 OC_LOG(ERROR, TAG, "Presence cancel error");
255 return OC_STACK_DELETE_TRANSACTION;
258 return OC_STACK_KEEP_TRANSACTION;
262 // This is a function called back when a device is discovered
263 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
264 OCClientResponse * clientResponse) {
265 uint8_t remoteIpAddr[4];
266 uint16_t remotePortNu;
268 if (ctx == (void*) CTX_VAL)
270 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
275 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
277 OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
278 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
279 OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
282 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
283 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
284 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
286 parseClientResponse(clientResponse);
290 case TEST_GET_REQ_NON:
291 InitGetRequest(OC_LOW_QOS, 0);
293 case TEST_PUT_REQ_NON:
296 case TEST_POST_REQ_NON:
297 InitPostRequest(OC_LOW_QOS);
299 case TEST_DELETE_REQ_NON:
300 InitDeleteRequest(OC_LOW_QOS);
302 case TEST_OBS_REQ_NON:
303 case TEST_OBS_REQ_NON_CANCEL_IMM:
304 InitObserveRequest(OC_LOW_QOS);
306 case TEST_GET_UNAVAILABLE_RES_REQ_NON:
307 InitGetRequestToUnavailableResource();
309 case TEST_GET_REQ_CON:
310 InitGetRequest(OC_HIGH_QOS, 0);
312 case TEST_POST_REQ_CON:
313 InitPostRequest(OC_HIGH_QOS);
315 case TEST_DELETE_REQ_CON:
316 InitDeleteRequest(OC_HIGH_QOS);
318 case TEST_OBS_REQ_CON:
319 InitObserveRequest(OC_HIGH_QOS);
322 case TEST_OBS_PRESENCE:
323 case TEST_OBS_PRESENCE_WITH_FILTER:
327 case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
328 InitGetRequest(OC_LOW_QOS, 1);
336 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
342 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
343 std::ostringstream query;
344 query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
345 if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER)
347 query << "?rt=core.light";
349 return (InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS, presenceCB, NULL, 0));
352 int InitGetRequestToUnavailableResource()
354 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
355 std::ostringstream query;
356 query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
357 return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0));
360 int InitObserveRequest(OCQualityOfService qos)
362 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
363 std::ostringstream query;
364 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
365 return (InvokeOCDoResource(query, OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
370 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
371 std::ostringstream query;
372 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
373 return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
376 int InitPostRequest(OCQualityOfService qos)
378 OCStackResult result;
379 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
380 std::ostringstream query;
381 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
383 // First POST operation (to create an Light instance)
384 result = InvokeOCDoResource(query, OC_REST_POST,
385 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
387 if (OC_STACK_OK != result)
389 // Error can happen if for example, network connectivity is down
390 OC_LOG(INFO, TAG, "First POST call did not succeed");
393 // Second POST operation (to create an Light instance)
394 result = InvokeOCDoResource(query, OC_REST_POST,
395 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
397 if (OC_STACK_OK != result)
399 OC_LOG(INFO, TAG, "Second POST call did not succeed");
402 // This POST operation will update the original resourced /a/light
403 return (InvokeOCDoResource(query, OC_REST_POST,
404 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
405 postReqCB, NULL, 0));
408 void* RequestDeleteDeathResourceTask(void* myqos)
410 sleep (30); //long enough to give the server time to finish deleting the resource.
411 std::ostringstream query;
412 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
414 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
416 // Second DELETE operation to delete the resource that might have been removed already.
417 OCQualityOfService qos;
423 OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
425 deleteReqCB, NULL, 0);
427 if (OC_STACK_OK != result)
429 OC_LOG(INFO, TAG, "Second DELETE call did not succeed");
435 int InitDeleteRequest(OCQualityOfService qos)
437 OCStackResult result;
438 std::ostringstream query;
439 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
441 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
443 // First DELETE operation
444 result = InvokeOCDoResource(query, OC_REST_DELETE,
446 deleteReqCB, NULL, 0);
447 if (OC_STACK_OK != result)
449 // Error can happen if for example, network connectivity is down
450 OC_LOG(INFO, TAG, "First DELETE call did not succeed");
454 //Create a thread to delete this resource again
456 pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
459 OC_LOG_V(INFO, TAG, "\n\nExit %s", __func__);
463 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions)
465 OCHeaderOption options[MAX_HEADER_OPTIONS];
467 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
468 std::ostringstream query;
469 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
471 if(withVendorSpecificHeaderOptions)
473 uint8_t option0[] = {1,2,3,4,5,6,7,8,9,10};
474 uint8_t option1[] = {11,12,13,14,15,16,17,18,19,20};
475 memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
476 options[0].protocolID = OC_COAP_ID;
477 options[0].optionID = 2048;
478 memcpy(options[0].optionData, option0, sizeof(option0));
479 options[0].optionLength = 10;
480 options[1].protocolID = OC_COAP_ID;
481 options[1].optionID = 3000;
482 memcpy(options[1].optionData, option1, sizeof(option1));
483 options[1].optionLength = 10;
485 if(withVendorSpecificHeaderOptions)
487 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, options, 2));
491 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
498 OCCallbackData cbData;
500 /* Start a discovery query*/
501 char szQueryUri[64] = { 0 };
502 if (UNICAST_DISCOVERY)
504 strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
508 strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
510 cbData.cb = discoveryReqCB;
511 cbData.context = (void*)CTX_VAL;
513 ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
514 if (ret != OC_STACK_OK)
516 OC_LOG(ERROR, TAG, "OCStack resource error");
521 int main(int argc, char* argv[]) {
522 uint8_t addr[20] = {0};
523 uint8_t* paddr = NULL;
524 uint16_t port = USE_RANDOM_PORT;
525 uint8_t ifname[] = "eth0";
528 while ((opt = getopt(argc, argv, "u:t:")) != -1)
533 UNICAST_DISCOVERY = atoi(optarg);
536 TEST_CASE = atoi(optarg);
544 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
545 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
552 /*Get Ip address on defined interface and initialize coap on it with random port number
553 * this port number will be used as a source port in all coap communications*/
554 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
555 sizeof(addr)) == ERR_SUCCESS)
557 OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
561 /* Initialize OCStack*/
562 if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
563 OC_LOG(ERROR, TAG, "OCStack init error");
569 // Break from loop with Ctrl+C
570 OC_LOG(INFO, TAG, "Entering occlient main loop...");
571 signal(SIGINT, handleSigInt);
574 if (OCProcess() != OC_STACK_OK) {
575 OC_LOG(ERROR, TAG, "OCStack process error");
581 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
583 if (OCStop() != OC_STACK_OK) {
584 OC_LOG(ERROR, TAG, "OCStack stop error");
590 std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
591 if(!clientResponse) return "";
592 if(!clientResponse->addr) return "";
593 uint8_t a, b, c, d = 0;
594 if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
596 char ipaddr[16] = {'\0'};
597 snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
598 return std::string (ipaddr);
601 std::string getPortTBServer(OCClientResponse * clientResponse){
602 if(!clientResponse) return "";
603 if(!clientResponse->addr) return "";
605 if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
606 std::ostringstream ss;
611 std::string getQueryStrForGetPut(OCClientResponse * clientResponse){
616 void parseClientResponse(OCClientResponse * clientResponse){
617 coapServerIP = getIPAddrTBServer(clientResponse);
618 coapServerPort = getPortTBServer(clientResponse);
619 coapServerResource = getQueryStrForGetPut(clientResponse);