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*)DEFAULT_CONTEXT_VALUE;
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*)DEFAULT_CONTEXT_VALUE)
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*)DEFAULT_CONTEXT_VALUE)
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*)DEFAULT_CONTEXT_VALUE)
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*)DEFAULT_CONTEXT_VALUE)
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*)DEFAULT_CONTEXT_VALUE)
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 == 3) //large number to test observing in DELETE case.
212 if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON){
213 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
214 OC_LOG(ERROR, TAG, "Observe cancel error");
216 return OC_STACK_DELETE_TRANSACTION;
217 }else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM){
218 if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK){
219 OC_LOG(ERROR, TAG, "Observe cancel error");
223 if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER){
224 OC_LOG(INFO, TAG, "This also serves as a registration confirmation");
225 }else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER){
226 OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
227 return OC_STACK_DELETE_TRANSACTION;
228 }else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION){
229 OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
230 return OC_STACK_DELETE_TRANSACTION;
233 return OC_STACK_KEEP_TRANSACTION;
236 OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
237 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
239 OC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully");
244 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
245 OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
246 OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d", gNumPresenceNotifies);
247 OC_LOG_V(INFO, TAG, "JSON = %s =============> Presence Response", clientResponse->resJSONPayload);
248 gNumPresenceNotifies++;
249 if (gNumPresenceNotifies == 20)
251 if (OCCancel (gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
252 OC_LOG(ERROR, TAG, "Presence cancel error");
254 return OC_STACK_DELETE_TRANSACTION;
257 return OC_STACK_KEEP_TRANSACTION;
261 // This is a function called back when a device is discovered
262 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
263 OCClientResponse * clientResponse) {
264 uint8_t remoteIpAddr[4];
265 uint16_t remotePortNu;
267 if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
269 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
274 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
276 OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
277 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
278 OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
281 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
282 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
283 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
285 parseClientResponse(clientResponse);
289 case TEST_GET_REQ_NON:
290 InitGetRequest(OC_LOW_QOS, 0);
292 case TEST_PUT_REQ_NON:
295 case TEST_POST_REQ_NON:
296 InitPostRequest(OC_LOW_QOS);
298 case TEST_DELETE_REQ_NON:
299 InitDeleteRequest(OC_LOW_QOS);
301 case TEST_OBS_REQ_NON:
302 case TEST_OBS_REQ_NON_CANCEL_IMM:
303 InitObserveRequest(OC_LOW_QOS);
305 case TEST_GET_UNAVAILABLE_RES_REQ_NON:
306 InitGetRequestToUnavailableResource();
308 case TEST_GET_REQ_CON:
309 InitGetRequest(OC_HIGH_QOS, 0);
311 case TEST_POST_REQ_CON:
312 InitPostRequest(OC_HIGH_QOS);
314 case TEST_DELETE_REQ_CON:
315 InitDeleteRequest(OC_HIGH_QOS);
317 case TEST_OBS_REQ_CON:
318 InitObserveRequest(OC_HIGH_QOS);
321 case TEST_OBS_PRESENCE:
322 case TEST_OBS_PRESENCE_WITH_FILTER:
326 case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
327 InitGetRequest(OC_LOW_QOS, 1);
335 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
341 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
342 std::ostringstream query;
343 query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
344 if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER)
346 query << "?rt=core.light";
348 return (InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS, presenceCB, NULL, 0));
351 int InitGetRequestToUnavailableResource()
353 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
354 std::ostringstream query;
355 query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
356 return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0));
359 int InitObserveRequest(OCQualityOfService qos)
361 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
362 std::ostringstream query;
363 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
364 return (InvokeOCDoResource(query, OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
369 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
370 std::ostringstream query;
371 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
372 return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
375 int InitPostRequest(OCQualityOfService qos)
377 OCStackResult result;
378 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
379 std::ostringstream query;
380 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
382 // First POST operation (to create an Light instance)
383 result = InvokeOCDoResource(query, OC_REST_POST,
384 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
386 if (OC_STACK_OK != result)
388 // Error can happen if for example, network connectivity is down
389 OC_LOG(INFO, TAG, "First POST call did not succeed");
392 // Second POST operation (to create an Light instance)
393 result = InvokeOCDoResource(query, OC_REST_POST,
394 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
396 if (OC_STACK_OK != result)
398 OC_LOG(INFO, TAG, "Second POST call did not succeed");
401 // This POST operation will update the original resourced /a/light
402 return (InvokeOCDoResource(query, OC_REST_POST,
403 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
404 postReqCB, NULL, 0));
407 void* RequestDeleteDeathResourceTask(void* myqos)
409 sleep (30); //long enough to give the server time to finish deleting the resource.
410 std::ostringstream query;
411 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
413 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
415 // Second DELETE operation to delete the resource that might have been removed already.
416 OCQualityOfService qos;
422 OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
424 deleteReqCB, NULL, 0);
426 if (OC_STACK_OK != result)
428 OC_LOG(INFO, TAG, "Second DELETE call did not succeed");
434 int InitDeleteRequest(OCQualityOfService qos)
436 OCStackResult result;
437 std::ostringstream query;
438 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
440 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
442 // First DELETE operation
443 result = InvokeOCDoResource(query, OC_REST_DELETE,
445 deleteReqCB, NULL, 0);
446 if (OC_STACK_OK != result)
448 // Error can happen if for example, network connectivity is down
449 OC_LOG(INFO, TAG, "First DELETE call did not succeed");
453 //Create a thread to delete this resource again
455 pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
458 OC_LOG_V(INFO, TAG, "\n\nExit %s", __func__);
462 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions)
464 OCHeaderOption options[MAX_HEADER_OPTIONS];
466 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
467 std::ostringstream query;
468 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
470 if(withVendorSpecificHeaderOptions)
472 uint8_t option0[] = {1,2,3,4,5,6,7,8,9,10};
473 uint8_t option1[] = {11,12,13,14,15,16,17,18,19,20};
474 memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
475 options[0].protocolID = OC_COAP_ID;
476 options[0].optionID = 2048;
477 memcpy(options[0].optionData, option0, sizeof(option0));
478 options[0].optionLength = 10;
479 options[1].protocolID = OC_COAP_ID;
480 options[1].optionID = 3000;
481 memcpy(options[1].optionData, option1, sizeof(option1));
482 options[1].optionLength = 10;
484 if(withVendorSpecificHeaderOptions)
486 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, options, 2));
490 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
497 OCCallbackData cbData;
499 /* Start a discovery query*/
500 char szQueryUri[64] = { 0 };
501 if (UNICAST_DISCOVERY)
503 strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
507 strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
509 cbData.cb = discoveryReqCB;
510 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
512 ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
513 if (ret != OC_STACK_OK)
515 OC_LOG(ERROR, TAG, "OCStack resource error");
520 int main(int argc, char* argv[]) {
521 uint8_t addr[20] = {0};
522 uint8_t* paddr = NULL;
523 uint16_t port = USE_RANDOM_PORT;
524 uint8_t ifname[] = "eth0";
527 while ((opt = getopt(argc, argv, "u:t:")) != -1)
532 UNICAST_DISCOVERY = atoi(optarg);
535 TEST_CASE = atoi(optarg);
543 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
544 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
551 /*Get Ip address on defined interface and initialize coap on it with random port number
552 * this port number will be used as a source port in all coap communications*/
553 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
554 sizeof(addr)) == ERR_SUCCESS)
556 OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
560 /* Initialize OCStack*/
561 if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
562 OC_LOG(ERROR, TAG, "OCStack init error");
568 // Break from loop with Ctrl+C
569 OC_LOG(INFO, TAG, "Entering occlient main loop...");
570 signal(SIGINT, handleSigInt);
573 if (OCProcess() != OC_STACK_OK) {
574 OC_LOG(ERROR, TAG, "OCStack process error");
580 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
582 if (OCStop() != OC_STACK_OK) {
583 OC_LOG(ERROR, TAG, "OCStack stop error");
589 std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
590 if(!clientResponse) return "";
591 if(!clientResponse->addr) return "";
592 uint8_t a, b, c, d = 0;
593 if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
595 char ipaddr[16] = {'\0'};
596 snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
597 return std::string (ipaddr);
600 std::string getPortTBServer(OCClientResponse * clientResponse){
601 if(!clientResponse) return "";
602 if(!clientResponse->addr) return "";
604 if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
605 std::ostringstream ss;
610 std::string getQueryStrForGetPut(OCClientResponse * clientResponse){
615 void parseClientResponse(OCClientResponse * clientResponse){
616 coapServerIP = getIPAddrTBServer(clientResponse);
617 coapServerPort = getPortTBServer(clientResponse);
618 coapServerResource = getQueryStrForGetPut(clientResponse);