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)
167 if(clientResponse == NULL)
169 OC_LOG(INFO, TAG, "The clientResponse is NULL");
170 return OC_STACK_DELETE_TRANSACTION;
172 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
174 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
177 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
178 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
179 OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", clientResponse->resJSONPayload);
181 if(clientResponse->rcvdVendorSpecificHeaderOptions &&
182 clientResponse->numRcvdVendorSpecificHeaderOptions)
184 OC_LOG (INFO, TAG, "Received vendor specific options");
186 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
187 for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
189 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
191 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
192 ((OCHeaderOption)rcvdOptions[i]).optionID );
193 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
194 ((OCHeaderOption)rcvdOptions[i]).optionLength);
198 return OC_STACK_DELETE_TRANSACTION;
201 OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
202 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
204 OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
209 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
210 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
211 OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d", gNumObserveNotifies);
212 OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response", clientResponse->resJSONPayload);
213 gNumObserveNotifies++;
214 if (gNumObserveNotifies == 3) //large number to test observing in DELETE case.
216 if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON){
217 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
218 OC_LOG(ERROR, TAG, "Observe cancel error");
220 return OC_STACK_DELETE_TRANSACTION;
221 }else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM){
222 if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK){
223 OC_LOG(ERROR, TAG, "Observe cancel error");
227 if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER){
228 OC_LOG(INFO, TAG, "This also serves as a registration confirmation");
229 }else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER){
230 OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
231 return OC_STACK_DELETE_TRANSACTION;
232 }else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION){
233 OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
234 return OC_STACK_DELETE_TRANSACTION;
237 return OC_STACK_KEEP_TRANSACTION;
240 OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) {
241 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
243 OC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully");
248 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
249 OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
250 OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d", gNumPresenceNotifies);
251 OC_LOG_V(INFO, TAG, "JSON = %s =============> Presence Response", clientResponse->resJSONPayload);
252 gNumPresenceNotifies++;
253 if (gNumPresenceNotifies == 20)
255 if (OCCancel (gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){
256 OC_LOG(ERROR, TAG, "Presence cancel error");
258 return OC_STACK_DELETE_TRANSACTION;
261 return OC_STACK_KEEP_TRANSACTION;
265 // This is a function called back when a device is discovered
266 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
267 OCClientResponse * clientResponse) {
268 uint8_t remoteIpAddr[4];
269 uint16_t remotePortNu;
271 if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
273 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
278 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
280 OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
281 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
282 OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
285 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
286 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
287 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
289 parseClientResponse(clientResponse);
293 case TEST_GET_REQ_NON:
294 InitGetRequest(OC_LOW_QOS, 0);
296 case TEST_PUT_REQ_NON:
299 case TEST_POST_REQ_NON:
300 InitPostRequest(OC_LOW_QOS);
302 case TEST_DELETE_REQ_NON:
303 InitDeleteRequest(OC_LOW_QOS);
305 case TEST_OBS_REQ_NON:
306 case TEST_OBS_REQ_NON_CANCEL_IMM:
307 InitObserveRequest(OC_LOW_QOS);
309 case TEST_GET_UNAVAILABLE_RES_REQ_NON:
310 InitGetRequestToUnavailableResource();
312 case TEST_GET_REQ_CON:
313 InitGetRequest(OC_HIGH_QOS, 0);
315 case TEST_POST_REQ_CON:
316 InitPostRequest(OC_HIGH_QOS);
318 case TEST_DELETE_REQ_CON:
319 InitDeleteRequest(OC_HIGH_QOS);
321 case TEST_OBS_REQ_CON:
322 InitObserveRequest(OC_HIGH_QOS);
325 case TEST_OBS_PRESENCE:
326 case TEST_OBS_PRESENCE_WITH_FILTER:
330 case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
331 InitGetRequest(OC_LOW_QOS, 1);
339 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
345 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
346 std::ostringstream query;
347 query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
348 if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER)
350 query << "?rt=core.light";
352 return (InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS, presenceCB, NULL, 0));
355 int InitGetRequestToUnavailableResource()
357 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
358 std::ostringstream query;
359 query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
360 return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0));
363 int InitObserveRequest(OCQualityOfService qos)
365 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
366 std::ostringstream query;
367 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
368 return (InvokeOCDoResource(query, OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
373 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
374 std::ostringstream query;
375 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
376 return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
379 int InitPostRequest(OCQualityOfService qos)
381 OCStackResult result;
382 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
383 std::ostringstream query;
384 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
386 // First POST operation (to create an Light instance)
387 result = InvokeOCDoResource(query, OC_REST_POST,
388 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
390 if (OC_STACK_OK != result)
392 // Error can happen if for example, network connectivity is down
393 OC_LOG(INFO, TAG, "First POST call did not succeed");
396 // Second POST operation (to create an Light instance)
397 result = InvokeOCDoResource(query, OC_REST_POST,
398 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
400 if (OC_STACK_OK != result)
402 OC_LOG(INFO, TAG, "Second POST call did not succeed");
405 // This POST operation will update the original resourced /a/light
406 return (InvokeOCDoResource(query, OC_REST_POST,
407 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
408 postReqCB, NULL, 0));
411 void* RequestDeleteDeathResourceTask(void* myqos)
413 sleep (30); //long enough to give the server time to finish deleting the resource.
414 std::ostringstream query;
415 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
417 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
419 // Second DELETE operation to delete the resource that might have been removed already.
420 OCQualityOfService qos;
426 OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
428 deleteReqCB, NULL, 0);
430 if (OC_STACK_OK != result)
432 OC_LOG(INFO, TAG, "Second DELETE call did not succeed");
438 int InitDeleteRequest(OCQualityOfService qos)
440 OCStackResult result;
441 std::ostringstream query;
442 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
444 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
446 // First DELETE operation
447 result = InvokeOCDoResource(query, OC_REST_DELETE,
449 deleteReqCB, NULL, 0);
450 if (OC_STACK_OK != result)
452 // Error can happen if for example, network connectivity is down
453 OC_LOG(INFO, TAG, "First DELETE call did not succeed");
457 //Create a thread to delete this resource again
459 pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
462 OC_LOG_V(INFO, TAG, "\n\nExit %s", __func__);
466 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions)
468 OCHeaderOption options[MAX_HEADER_OPTIONS];
470 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
471 std::ostringstream query;
472 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
474 if(withVendorSpecificHeaderOptions)
476 uint8_t option0[] = {1,2,3,4,5,6,7,8,9,10};
477 uint8_t option1[] = {11,12,13,14,15,16,17,18,19,20};
478 memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
479 options[0].protocolID = OC_COAP_ID;
480 options[0].optionID = 2048;
481 memcpy(options[0].optionData, option0, sizeof(option0));
482 options[0].optionLength = 10;
483 options[1].protocolID = OC_COAP_ID;
484 options[1].optionID = 3000;
485 memcpy(options[1].optionData, option1, sizeof(option1));
486 options[1].optionLength = 10;
488 if(withVendorSpecificHeaderOptions)
490 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, options, 2));
494 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
501 OCCallbackData cbData;
503 /* Start a discovery query*/
504 char szQueryUri[64] = { 0 };
505 if (UNICAST_DISCOVERY)
507 strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
511 strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
513 cbData.cb = discoveryReqCB;
514 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
516 ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
517 if (ret != OC_STACK_OK)
519 OC_LOG(ERROR, TAG, "OCStack resource error");
524 int main(int argc, char* argv[]) {
525 uint8_t addr[20] = {0};
526 uint8_t* paddr = NULL;
527 uint16_t port = USE_RANDOM_PORT;
528 uint8_t ifname[] = "eth0";
531 while ((opt = getopt(argc, argv, "u:t:")) != -1)
536 UNICAST_DISCOVERY = atoi(optarg);
539 TEST_CASE = atoi(optarg);
547 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
548 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
555 /*Get Ip address on defined interface and initialize coap on it with random port number
556 * this port number will be used as a source port in all coap communications*/
557 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
558 sizeof(addr)) == ERR_SUCCESS)
560 OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
564 /* Initialize OCStack*/
565 if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) {
566 OC_LOG(ERROR, TAG, "OCStack init error");
572 // Break from loop with Ctrl+C
573 OC_LOG(INFO, TAG, "Entering occlient main loop...");
574 signal(SIGINT, handleSigInt);
577 if (OCProcess() != OC_STACK_OK) {
578 OC_LOG(ERROR, TAG, "OCStack process error");
584 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
586 if (OCStop() != OC_STACK_OK) {
587 OC_LOG(ERROR, TAG, "OCStack stop error");
593 std::string getIPAddrTBServer(OCClientResponse * clientResponse) {
594 if(!clientResponse) return "";
595 if(!clientResponse->addr) return "";
596 uint8_t a, b, c, d = 0;
597 if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
599 char ipaddr[16] = {'\0'};
600 snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf
601 return std::string (ipaddr);
604 std::string getPortTBServer(OCClientResponse * clientResponse){
605 if(!clientResponse) return "";
606 if(!clientResponse->addr) return "";
608 if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
609 std::ostringstream ss;
614 std::string getQueryStrForGetPut(OCClientResponse * clientResponse){
619 void parseClientResponse(OCClientResponse * clientResponse){
620 coapServerIP = getIPAddrTBServer(clientResponse);
621 coapServerPort = getPortTBServer(clientResponse);
622 coapServerResource = getQueryStrForGetPut(clientResponse);