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/led";
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");
82 OC_LOG(INFO, TAG, "-t 13 : Discover Resources and Initiate Nonconfirmable Observe Requests then cancel immediately");
83 OC_LOG(INFO, TAG, "-t 14 : Discover Resources and Initiate Nonconfirmable Get Request and add vendor specific header options");
86 OCStackResult InvokeOCDoResource(std::ostringstream &query,
87 OCMethod method, OCQualityOfService qos,
88 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
91 OCCallbackData cbData;
95 cbData.context = (void*)CTX_VAL;
98 ret = OCDoResource(&handle, method, query.str().c_str(), 0,
99 (method == OC_REST_PUT) ? putPayload.c_str() : NULL,
100 qos, &cbData, options, numOptions);
102 if (ret != OC_STACK_OK)
104 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
106 else if (method == OC_REST_OBSERVE || method == OC_REST_OBSERVE_ALL)
108 gObserveDoHandle = handle;
111 else if (method == OC_REST_PRESENCE)
113 gPresenceHandle = handle;
120 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
121 if(ctx == (void*)CTX_VAL)
123 OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
128 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
129 OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
131 return OC_STACK_DELETE_TRANSACTION;
134 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
136 if(ctx == (void*)CTX_VAL)
138 OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
143 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
144 OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response", clientResponse->resJSONPayload);
146 return OC_STACK_DELETE_TRANSACTION;
149 OCStackApplicationResult deleteReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
151 if(ctx == (void*)CTX_VAL)
153 OC_LOG(INFO, TAG, "Callback Context for DELETE recvd successfully");
158 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
159 OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response", clientResponse->resJSONPayload);
161 return OC_STACK_DELETE_TRANSACTION;
164 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
165 if(ctx == (void*)CTX_VAL)
167 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
172 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
173 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
174 OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", clientResponse->resJSONPayload);
176 if(clientResponse->rcvdVendorSpecificHeaderOptions &&
177 clientResponse->numRcvdVendorSpecificHeaderOptions)
179 OC_LOG (INFO, TAG, "Received vendor specific options");
181 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
182 for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
184 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
186 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
187 ((OCHeaderOption)rcvdOptions[i]).optionID );
188 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
189 ((OCHeaderOption)rcvdOptions[i]).optionLength);
193 return OC_STACK_DELETE_TRANSACTION;
196 OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
197 if(ctx == (void*)CTX_VAL)
199 OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
204 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
205 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
206 OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d", gNumObserveNotifies);
207 OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response", clientResponse->resJSONPayload);
208 gNumObserveNotifies++;
209 if (gNumObserveNotifies == 50) //large number to test observing in DELETE case.
211 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*)CTX_VAL)
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: %d", 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*) CTX_VAL)
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:
325 case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
326 InitGetRequest(OC_LOW_QOS, 1);
334 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
340 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
341 std::ostringstream query;
342 query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
343 return (InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS, presenceCB, NULL, 0));
346 int InitGetRequestToUnavailableResource()
348 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
349 std::ostringstream query;
350 query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
351 return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0));
354 int InitObserveRequest(OCQualityOfService qos)
356 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
357 std::ostringstream query;
358 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
359 return (InvokeOCDoResource(query, OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
364 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
365 std::ostringstream query;
366 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
367 return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
370 int InitPostRequest(OCQualityOfService qos)
372 OCStackResult result;
373 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
374 std::ostringstream query;
375 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
377 // First POST operation (to create an LED instance)
378 result = InvokeOCDoResource(query, OC_REST_POST,
379 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
381 if (OC_STACK_OK != result)
383 // Error can happen if for example, network connectivity is down
384 OC_LOG(INFO, TAG, "First POST call did not succeed");
387 // Second POST operation (to create an LED instance)
388 result = InvokeOCDoResource(query, OC_REST_POST,
389 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
391 if (OC_STACK_OK != result)
393 OC_LOG(INFO, TAG, "Second POST call did not succeed");
396 // This POST operation will update the original resourced /a/led
397 return (InvokeOCDoResource(query, OC_REST_POST,
398 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
399 postReqCB, NULL, 0));
402 void* RequestDeleteDeathResourceTask(void* myqos)
404 sleep (30); //long enough to give the server time to finish deleting the resource.
405 std::ostringstream query;
406 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
408 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
410 // Second DELETE operation to delete the resource that might have been removed already.
411 OCQualityOfService qos;
417 OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
419 deleteReqCB, NULL, 0);
421 if (OC_STACK_OK != result)
423 OC_LOG(INFO, TAG, "Second DELETE call did not succeed");
429 int InitDeleteRequest(OCQualityOfService qos)
431 OCStackResult result;
432 std::ostringstream query;
433 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
435 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
437 // First DELETE operation
438 result = InvokeOCDoResource(query, OC_REST_DELETE,
440 deleteReqCB, NULL, 0);
441 if (OC_STACK_OK != result)
443 // Error can happen if for example, network connectivity is down
444 OC_LOG(INFO, TAG, "First DELETE call did not succeed");
448 //Create a thread to delete this resource again
450 pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
453 OC_LOG_V(INFO, TAG, "\n\nExit %s", __func__);
457 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions)
459 OCHeaderOption options[MAX_HEADER_OPTIONS];
461 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
462 std::ostringstream query;
463 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
465 if(withVendorSpecificHeaderOptions)
467 uint8_t option0[] = {1,2,3,4,5,6,7,8,9,10};
468 uint8_t option1[] = {11,12,13,14,15,16,17,18,19,20};
469 memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
470 options[0].protocolID = OC_COAP_ID;
471 options[0].optionID = 2048;
472 memcpy(options[0].optionData, option0, sizeof(option0));
473 options[0].optionLength = 10;
474 options[1].protocolID = OC_COAP_ID;
475 options[1].optionID = 3000;
476 memcpy(options[1].optionData, option1, sizeof(option1));
477 options[1].optionLength = 10;
479 if(withVendorSpecificHeaderOptions)
481 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, options, 2));
485 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
492 OCCallbackData cbData;
494 /* Start a discovery query*/
495 char szQueryUri[64] = { 0 };
496 if (UNICAST_DISCOVERY)
498 strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
502 strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
504 cbData.cb = discoveryReqCB;
505 cbData.context = (void*)CTX_VAL;
507 ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
508 if (ret != OC_STACK_OK)
510 OC_LOG(ERROR, TAG, "OCStack resource error");
515 int main(int argc, char* argv[]) {
516 uint8_t addr[20] = {0};
517 uint8_t* paddr = NULL;
518 uint16_t port = USE_RANDOM_PORT;
519 uint8_t ifname[] = "eth0";
522 while ((opt = getopt(argc, argv, "u:t:")) != -1)
527 UNICAST_DISCOVERY = atoi(optarg);
530 TEST_CASE = atoi(optarg);
538 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
539 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
546 /*Get Ip address on defined interface and initialize coap on it with random port number
547 * this port number will be used as a source port in all coap communications*/
548 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
549 sizeof(addr)) == ERR_SUCCESS)
551 OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
555 /* Initialize OCStack*/
556 if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
557 OC_LOG(ERROR, TAG, "OCStack init error");
563 // Break from loop with Ctrl+C
564 OC_LOG(INFO, TAG, "Entering occlient main loop...");
565 signal(SIGINT, handleSigInt);
568 if (OCProcess() != OC_STACK_OK) {
569 OC_LOG(ERROR, TAG, "OCStack process error");
575 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
577 if (OCStop() != OC_STACK_OK) {
578 OC_LOG(ERROR, TAG, "OCStack stop error");
584 std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
585 if(!clientResponse) return "";
586 if(!clientResponse->addr) return "";
587 uint8_t a, b, c, d = 0;
588 if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
590 char ipaddr[16] = {'\0'};
591 snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
592 return std::string (ipaddr);
595 std::string getPortTBServer(OCClientResponse * clientResponse){
596 if(!clientResponse) return "";
597 if(!clientResponse->addr) return "";
599 if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
600 std::ostringstream ss;
605 std::string getQueryStrForGetPut(OCClientResponse * clientResponse){
610 void parseClientResponse(OCClientResponse * clientResponse){
611 coapServerIP = getIPAddrTBServer(clientResponse);
612 coapServerPort = getPortTBServer(clientResponse);
613 coapServerResource = getQueryStrForGetPut(clientResponse);