Added simple query example for non virtual resource in C samples.
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / occlient.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
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
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
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.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <iostream>
27 #include <sstream>
28 #include "ocstack.h"
29 #include "logger.h"
30 #include "occlient.h"
31
32 static int UNICAST_DISCOVERY = 0;
33 static int TEST_CASE = 0;
34 static const char * UNICAST_DISCOVERY_QUERY = "coap://%s:6298/oc/core";
35 static const char * UNICAST_DEVICE_DISCOVERY_QUERY = "coap://%s:6298/oc/core/d";
36 static const char * MULTICAST_DEVICE_DISCOVERY_QUERY = "/oc/core/d";
37 static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oc/core";
38 //The following variable determines the interface (wifi, ethernet etc.)
39 //to be used for sending unicast messages. Default set to WIFI.
40 static OCConnectivityType OC_CONNTYPE = OC_WIFI;
41 static std::string putPayload = "{\"oc\":[{\"rep\":{\"power\":15,\"state\":true}}]}";
42 static std::string coapServerIP = "255.255.255.255";
43 static std::string coapServerPort = "5683";
44 static std::string coapServerResource = "/a/light";
45 static const int IPV4_ADDR_SIZE = 16;
46 //Use ipv4addr for both InitDiscovery and InitDeviceDiscovery
47 char ipv4addr[IPV4_ADDR_SIZE];
48 void StripNewLineChar(char* str);
49
50 // The handle for the observe registration
51 OCDoHandle gObserveDoHandle;
52 #ifdef WITH_PRESENCE
53 // The handle for observe registration
54 OCDoHandle gPresenceHandle;
55 #endif
56 // After this crosses a threshold client deregisters for further notifications
57 int gNumObserveNotifies = 0;
58
59 #ifdef WITH_PRESENCE
60 int gNumPresenceNotifies = 0;
61 #endif
62
63 int gQuitFlag = 0;
64 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
65 void handleSigInt(int signum)
66 {
67     if (signum == SIGINT)
68     {
69         gQuitFlag = 1;
70     }
71 }
72
73 static void PrintUsage()
74 {
75     OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1..17> -c <0|1>");
76     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
77     OC_LOG(INFO, TAG, "-c <0|1> : Send unicast messages over Ethernet or WIFI");
78     OC_LOG(INFO, TAG, "-t 1  :  Discover Resources");
79     OC_LOG(INFO, TAG, "-t 2  :  Discover Resources and Initiate Nonconfirmable Get Request");
80     OC_LOG(INFO, TAG, "-t 3  :  Discover Resources and Initiate Nonconfirmable Get Request"
81             " with query filter.");
82     OC_LOG(INFO, TAG, "-t 4  :  Discover Resources and Initiate Nonconfirmable Put Requests");
83     OC_LOG(INFO, TAG, "-t 5  :  Discover Resources and Initiate Nonconfirmable Post Requests");
84     OC_LOG(INFO, TAG, "-t 6  :  Discover Resources and Initiate Nonconfirmable Delete Requests");
85     OC_LOG(INFO, TAG, "-t 7  :  Discover Resources and Initiate Nonconfirmable Observe Requests");
86     OC_LOG(INFO, TAG, "-t 8  :  Discover Resources and Initiate Nonconfirmable Get Request "\
87             "for a resource which is unavailable");
88     OC_LOG(INFO, TAG, "-t 9  :  Discover Resources and Initiate Confirmable Get Request");
89     OC_LOG(INFO, TAG, "-t 10  :  Discover Resources and Initiate Confirmable Post Request");
90     OC_LOG(INFO, TAG, "-t 11 :  Discover Resources and Initiate Confirmable Delete Requests");
91     OC_LOG(INFO, TAG, "-t 12 :  Discover Resources and Initiate Confirmable Observe Requests"\
92             " and cancel with Low QoS");
93
94 #ifdef WITH_PRESENCE
95     OC_LOG(INFO, TAG, "-t 13 :  Discover Resources and Initiate Nonconfirmable presence");
96     OC_LOG(INFO, TAG, "-t 14 :  Discover Resources and Initiate Nonconfirmable presence with "\
97             "filter");
98     OC_LOG(INFO, TAG, "-t 15 :  Discover Resources and Initiate Nonconfirmable presence with "\
99             "2 filters");
100     OC_LOG(INFO, TAG, "-t 16 :  Discover Resources and Initiate Nonconfirmable multicast presence.");
101 #endif
102
103     OC_LOG(INFO, TAG, "-t 17 :  Discover Resources and Initiate Nonconfirmable Observe Requests "\
104             "then cancel immediately with High QOS");
105     OC_LOG(INFO, TAG, "-t 18 :  Discover Resources and Initiate Nonconfirmable Get Request and "\
106             "add  vendor specific header options");
107     OC_LOG(INFO, TAG, "-t 19 :  Discover Devices");
108 }
109
110 OCStackResult InvokeOCDoResource(std::ostringstream &query,
111                                  OCMethod method,
112                                  OCQualityOfService qos,
113                                  OCClientResponseHandler cb,
114                                  OCHeaderOption * options,
115                                  uint8_t numOptions)
116 {
117     OCStackResult ret;
118     OCCallbackData cbData;
119     OCDoHandle handle;
120
121     cbData.cb = cb;
122     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
123     cbData.cd = NULL;
124
125     ret = OCDoResource(&handle, method, query.str().c_str(), 0,
126                        (method == OC_REST_PUT) ? putPayload.c_str() : NULL,
127                        (OC_CONNTYPE), qos, &cbData, options, numOptions);
128
129     if (ret != OC_STACK_OK)
130     {
131         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
132     }
133     else if (method == OC_REST_OBSERVE || method == OC_REST_OBSERVE_ALL)
134     {
135         gObserveDoHandle = handle;
136     }
137 #ifdef WITH_PRESENCE
138     else if (method == OC_REST_PRESENCE)
139     {
140         gPresenceHandle = handle;
141     }
142 #endif
143
144     return ret;
145 }
146
147 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
148 {
149     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
150     {
151         OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
152     }
153
154     if(clientResponse)
155     {
156         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
157         OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response",
158                 clientResponse->resJSONPayload);
159     }
160     else
161     {
162         OC_LOG_V(INFO, TAG, "putReqCB received Null clientResponse");
163     }
164     return OC_STACK_DELETE_TRANSACTION;
165 }
166
167 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
168 {
169     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
170     {
171         OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
172     }
173
174     if(clientResponse)
175     {
176         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
177         OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
178                 clientResponse->resJSONPayload);
179     }
180     else
181     {
182         OC_LOG_V(INFO, TAG, "postReqCB received Null clientResponse");
183     }
184     return OC_STACK_DELETE_TRANSACTION;
185 }
186
187 OCStackApplicationResult deleteReqCB(void *ctx,
188         OCDoHandle handle, OCClientResponse *clientResponse)
189 {
190     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
191     {
192         OC_LOG(INFO, TAG, "Callback Context for DELETE recvd successfully");
193     }
194
195     if(clientResponse)
196     {
197         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
198         OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response",
199                 clientResponse->resJSONPayload);
200     }
201     else
202     {
203         OC_LOG_V(INFO, TAG, "deleteReqCB received Null clientResponse");
204     }
205     return OC_STACK_DELETE_TRANSACTION;
206 }
207
208 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
209 {
210     if(clientResponse == NULL)
211     {
212         OC_LOG(INFO, TAG, "getReqCB received NULL clientResponse");
213         return   OC_STACK_DELETE_TRANSACTION;
214     }
215
216     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
217     {
218         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
219     }
220
221     OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
222     OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
223     OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", clientResponse->resJSONPayload);
224
225     if(clientResponse->rcvdVendorSpecificHeaderOptions &&
226             clientResponse->numRcvdVendorSpecificHeaderOptions)
227     {
228         OC_LOG (INFO, TAG, "Received vendor specific options");
229         uint8_t i = 0;
230         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
231         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
232         {
233             if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
234             {
235                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
236                         ((OCHeaderOption)rcvdOptions[i]).optionID );
237
238                 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
239                     MAX_HEADER_OPTION_DATA_LENGTH);
240             }
241         }
242     }
243     return OC_STACK_DELETE_TRANSACTION;
244 }
245
246 OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
247 {
248     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
249     {
250         OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
251     }
252
253     if(clientResponse)
254     {
255         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
256         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
257         OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d",
258                 gNumObserveNotifies);
259         OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response",
260                 clientResponse->resJSONPayload);
261         gNumObserveNotifies++;
262         if (gNumObserveNotifies == 15) //large number to test observing in DELETE case.
263         {
264             if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON)
265             {
266                 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
267                 {
268                     OC_LOG(ERROR, TAG, "Observe cancel error");
269                 }
270                 return OC_STACK_DELETE_TRANSACTION;
271             }
272             else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM)
273             {
274                 if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK)
275                 {
276                     OC_LOG(ERROR, TAG, "Observe cancel error");
277                 }
278             }
279         }
280         if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER)
281         {
282             OC_LOG(INFO, TAG, "This also serves as a registration confirmation");
283         }
284         else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER)
285         {
286             OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
287             return OC_STACK_DELETE_TRANSACTION;
288         }
289         else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION)
290         {
291             OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
292             return OC_STACK_DELETE_TRANSACTION;
293         }
294     }
295     else
296     {
297         OC_LOG_V(INFO, TAG, "obsReqCB received Null clientResponse");
298     }
299     return OC_STACK_KEEP_TRANSACTION;
300 }
301 #ifdef WITH_PRESENCE
302 OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
303 {
304     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
305     {
306         OC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully");
307     }
308
309     if (clientResponse)
310     {
311         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
312         OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
313         OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d",
314                 gNumPresenceNotifies);
315         OC_LOG_V(INFO, TAG, "JSON = %s =============> Presence Response",
316                 clientResponse->resJSONPayload);
317         gNumPresenceNotifies++;
318         if (gNumPresenceNotifies == 20)
319         {
320             if (OCCancel(gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
321             {
322                 OC_LOG(ERROR, TAG, "Presence cancel error");
323             }
324             return OC_STACK_DELETE_TRANSACTION;
325         }
326     }
327     else
328     {
329         OC_LOG_V(INFO, TAG, "presenceCB received Null clientResponse");
330     }
331     return OC_STACK_KEEP_TRANSACTION;
332 }
333 #endif
334
335 // This is a function called back when a device is discovered
336 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
337         OCClientResponse * clientResponse)
338 {
339     uint8_t remoteIpAddr[4];
340     uint16_t remotePortNu;
341
342     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
343     {
344         OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
345     }
346
347     if (clientResponse)
348     {
349         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
350
351         OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
352                 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
353         OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
354
355         std::string connectionType = getConnectivityType (clientResponse->connType);
356         OC_LOG_V(INFO, TAG, "Discovered on %s", connectionType.c_str());
357         OC_LOG_V(INFO, TAG,
358                 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
359                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
360                 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
361
362         parseClientResponse(clientResponse);
363
364         switch(TEST_CASE)
365         {
366             case TEST_GET_REQ_NON:
367                 InitGetRequest(OC_LOW_QOS, 0, 0);
368                 break;
369             case TEST_GET_REQ_NON_WITH_FILTERS:
370                 InitGetRequest(OC_LOW_QOS, 0, 1);
371                 break;
372             case TEST_PUT_REQ_NON:
373                 InitPutRequest(OC_LOW_QOS);
374                 break;
375             case TEST_POST_REQ_NON:
376                 InitPostRequest(OC_LOW_QOS);
377                 break;
378             case TEST_DELETE_REQ_NON:
379                 InitDeleteRequest(OC_LOW_QOS);
380                 break;
381             case TEST_OBS_REQ_NON:
382             case TEST_OBS_REQ_NON_CANCEL_IMM:
383                 InitObserveRequest(OC_LOW_QOS);
384                 break;
385             case TEST_GET_UNAVAILABLE_RES_REQ_NON:
386                 InitGetRequestToUnavailableResource(OC_LOW_QOS);
387                 break;
388             case TEST_GET_REQ_CON:
389                 InitGetRequest(OC_HIGH_QOS, 0, 0);
390                 break;
391             case TEST_POST_REQ_CON:
392                 InitPostRequest(OC_HIGH_QOS);
393                 break;
394             case TEST_DELETE_REQ_CON:
395                 InitDeleteRequest(OC_HIGH_QOS);
396                 break;
397             case TEST_OBS_REQ_CON:
398                 InitObserveRequest(OC_HIGH_QOS);
399                 break;
400 #ifdef WITH_PRESENCE
401             case TEST_OBS_PRESENCE:
402             case TEST_OBS_PRESENCE_WITH_FILTER:
403             case TEST_OBS_PRESENCE_WITH_FILTERS:
404             case TEST_OBS_MULTICAST_PRESENCE:
405                 InitPresence();
406                 break;
407 #endif
408             case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
409                 InitGetRequest(OC_LOW_QOS, 1, 0);
410                 break;
411             case TEST_DISCOVER_DEV_REQ:
412                 InitDeviceDiscovery(OC_LOW_QOS);
413                 break;
414             default:
415                 PrintUsage();
416                 break;
417         }
418     }
419     else
420     {
421         OC_LOG_V(INFO, TAG, "discoveryReqCB received Null clientResponse");
422     }
423     return OC_STACK_KEEP_TRANSACTION;
424 }
425
426 OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle,
427         OCClientResponse * clientResponse)
428 {
429     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
430     {
431         OC_LOG(INFO, TAG, "Callback Context for Device DISCOVER query recvd successfully");
432     }
433
434     if(clientResponse)
435     {
436         //OC_LOG truncates the response as it is too long.
437         fprintf(stderr, "Discovery response: \n %s\n", clientResponse->resJSONPayload);
438         fflush(stderr);
439     }
440     else
441     {
442         OC_LOG_V(INFO, TAG, "DeviceDiscoveryReqCB received Null clientResponse");
443     }
444
445     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
446 }
447
448 #ifdef WITH_PRESENCE
449 int InitPresence()
450 {
451     OCStackResult result = OC_STACK_OK;
452     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
453     std::ostringstream query;
454     std::ostringstream querySuffix;
455     query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
456     if(TEST_CASE == TEST_OBS_PRESENCE)
457     {
458         result = InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS,
459                 presenceCB, NULL, 0);
460     }
461     if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER || TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS)
462     {
463         querySuffix.str("");
464         querySuffix << query.str() << "?rt=core.led";
465         result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS,
466                 presenceCB, NULL, 0);
467     }
468     if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS)
469     {
470         if(result == OC_STACK_OK)
471         {
472             querySuffix.str("");
473             querySuffix << query.str() << "?rt=core.fan";
474             result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS,
475                     presenceCB, NULL, 0);
476         }
477     }
478     if(TEST_CASE == TEST_OBS_MULTICAST_PRESENCE)
479     {
480         if(result == OC_STACK_OK)
481         {
482             std::ostringstream multicastPresenceQuery;
483             multicastPresenceQuery.str("");
484             multicastPresenceQuery << "coap://" << OC_MULTICAST_PREFIX << OC_PRESENCE_URI;
485             result = InvokeOCDoResource(multicastPresenceQuery, OC_REST_PRESENCE, OC_LOW_QOS,
486                     presenceCB, NULL, 0);
487         }
488     }
489     return result;
490 }
491 #endif
492
493 int InitGetRequestToUnavailableResource(OCQualityOfService qos)
494 {
495     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
496     std::ostringstream query;
497     query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
498     return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
499             getReqCB, NULL, 0));
500 }
501
502 int InitObserveRequest(OCQualityOfService qos)
503 {
504     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
505     std::ostringstream query;
506     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
507     return (InvokeOCDoResource(query,
508             OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
509 }
510
511 int InitPutRequest(OCQualityOfService qos)
512 {
513     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
514     std::ostringstream query;
515     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
516     return (InvokeOCDoResource(query, OC_REST_PUT, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
517             putReqCB, NULL, 0));
518 }
519
520 int InitPostRequest(OCQualityOfService qos)
521 {
522     OCStackResult result;
523     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
524     std::ostringstream query;
525     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
526
527     // First POST operation (to create an Light instance)
528     result = InvokeOCDoResource(query, OC_REST_POST,
529                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
530                                postReqCB, NULL, 0);
531     if (OC_STACK_OK != result)
532     {
533         // Error can happen if for example, network connectivity is down
534         OC_LOG(INFO, TAG, "First POST call did not succeed");
535     }
536
537     // Second POST operation (to create an Light instance)
538     result = InvokeOCDoResource(query, OC_REST_POST,
539                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
540                                postReqCB, NULL, 0);
541     if (OC_STACK_OK != result)
542     {
543         OC_LOG(INFO, TAG, "Second POST call did not succeed");
544     }
545
546     // This POST operation will update the original resourced /a/light
547     return (InvokeOCDoResource(query, OC_REST_POST,
548                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
549                                postReqCB, NULL, 0));
550 }
551
552 void* RequestDeleteDeathResourceTask(void* myqos)
553 {
554     sleep (30);//long enough to give the server time to finish deleting the resource.
555     std::ostringstream query;
556     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
557
558     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
559
560     // Second DELETE operation to delete the resource that might have been removed already.
561     OCQualityOfService qos;
562     if (myqos == NULL)
563     {
564         qos = OC_LOW_QOS;
565     }
566     else
567     {
568         qos = OC_HIGH_QOS;
569     }
570
571     OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
572                                qos,
573                                deleteReqCB, NULL, 0);
574
575     if (OC_STACK_OK != result)
576     {
577         OC_LOG(INFO, TAG, "Second DELETE call did not succeed");
578     }
579
580     return NULL;
581 }
582
583 int InitDeleteRequest(OCQualityOfService qos)
584 {
585     OCStackResult result;
586     std::ostringstream query;
587     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
588
589     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
590
591     // First DELETE operation
592     result = InvokeOCDoResource(query, OC_REST_DELETE,
593                                qos,
594                                deleteReqCB, NULL, 0);
595     if (OC_STACK_OK != result)
596     {
597         // Error can happen if for example, network connectivity is down
598         OC_LOG(INFO, TAG, "First DELETE call did not succeed");
599     }
600     else
601     {
602         //Create a thread to delete this resource again
603         pthread_t threadId;
604         pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos);
605     }
606
607     OC_LOG_V(INFO, TAG, "\n\nExit  %s", __func__);
608     return result;
609 }
610
611 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions, bool getWithQuery)
612 {
613
614     OCHeaderOption options[MAX_HEADER_OPTIONS];
615
616     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
617     std::ostringstream query;
618     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
619
620     // ocserver is written to only process "power<X" query.
621     if (getWithQuery)
622     {
623         OC_LOG(INFO, TAG, "Using query power<30");
624         query << "?power<30";
625     }
626
627     if (withVendorSpecificHeaderOptions)
628     {
629         uint8_t option0[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
630         uint8_t option1[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
631         memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
632         options[0].protocolID = OC_COAP_ID;
633         options[0].optionID = 2048;
634         memcpy(options[0].optionData, option0, sizeof(option0));
635         options[0].optionLength = 10;
636         options[1].protocolID = OC_COAP_ID;
637         options[1].optionID = 3000;
638         memcpy(options[1].optionData, option1, sizeof(option1));
639         options[1].optionLength = 10;
640     }
641     if (withVendorSpecificHeaderOptions)
642     {
643         return (InvokeOCDoResource(query, OC_REST_GET,
644                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, getReqCB, options, 2));
645     }
646     else
647     {
648         return (InvokeOCDoResource(query, OC_REST_GET,
649                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, getReqCB, NULL, 0));
650     }
651 }
652
653 int InitDeviceDiscovery(OCQualityOfService qos)
654 {
655     OCStackResult ret;
656     OCCallbackData cbData;
657     char szQueryUri[64] = { 0 };
658
659     cbData.cb = DeviceDiscoveryReqCB;
660     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
661     cbData.cd = NULL;
662
663     if(UNICAST_DISCOVERY)
664     {
665         snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DEVICE_DISCOVERY_QUERY, ipv4addr);
666     }
667     else
668     {
669         strncpy(szQueryUri, MULTICAST_DEVICE_DISCOVERY_QUERY,
670                 (strlen(MULTICAST_DEVICE_DISCOVERY_QUERY) + 1));
671     }
672
673     if(UNICAST_DISCOVERY)
674     {
675         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
676                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
677     }
678     else
679     {
680         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
681                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
682     }
683
684     if (ret != OC_STACK_OK)
685     {
686         OC_LOG(ERROR, TAG, "OCStack device error");
687     }
688
689     return ret;
690 }
691
692 int InitDiscovery(OCQualityOfService qos)
693 {
694     OCStackResult ret;
695     OCCallbackData cbData;
696     /* Start a discovery query*/
697     char szQueryUri[64] = { 0 };
698
699     if (UNICAST_DISCOVERY)
700     {
701         snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
702     }
703     else
704     {
705         strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
706     }
707
708     cbData.cb = discoveryReqCB;
709     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
710     cbData.cd = NULL;
711     if(UNICAST_DISCOVERY)
712     {
713         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
714                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
715     }
716     else
717     {
718         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
719                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
720     }
721     if (ret != OC_STACK_OK)
722     {
723         OC_LOG(ERROR, TAG, "OCStack resource error");
724     }
725     return ret;
726 }
727
728 int main(int argc, char* argv[])
729 {
730     int opt;
731
732     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
733     {
734         switch(opt)
735         {
736             case 'u':
737                 UNICAST_DISCOVERY = atoi(optarg);
738                 break;
739             case 't':
740                 TEST_CASE = atoi(optarg);
741                 break;
742             case 'c':
743                 OC_CONNTYPE = OCConnectivityType(atoi(optarg));
744                 break;
745             default:
746                 PrintUsage();
747                 return -1;
748         }
749     }
750
751     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
752             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
753     {
754         PrintUsage();
755         return -1;
756     }
757
758     /* Initialize OCStack*/
759     if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
760     {
761         OC_LOG(ERROR, TAG, "OCStack init error");
762         return 0;
763     }
764     if (UNICAST_DISCOVERY)
765     {
766         printf("Enter IPv4 address of the Server hosting resource (Ex: 192.168.0.15)\n");
767         if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
768         {
769             //Strip newline char from ipv4addr
770             StripNewLineChar(ipv4addr);
771         }
772         else
773         {
774             OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
775             return OC_STACK_INVALID_PARAM;
776         }
777      }
778
779     if(UNICAST_DISCOVERY  == 0  && TEST_CASE == TEST_DISCOVER_DEV_REQ)
780     {
781         InitDeviceDiscovery(OC_LOW_QOS);
782     }
783     else
784     {
785         InitDiscovery(OC_LOW_QOS);
786     }
787
788     // Break from loop with Ctrl+C
789     OC_LOG(INFO, TAG, "Entering occlient main loop...");
790     signal(SIGINT, handleSigInt);
791     while (!gQuitFlag)
792     {
793
794         if (OCProcess() != OC_STACK_OK)
795         {
796             OC_LOG(ERROR, TAG, "OCStack process error");
797             return 0;
798         }
799
800         sleep(2);
801     }
802     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
803
804     if (OCStop() != OC_STACK_OK)
805     {
806         OC_LOG(ERROR, TAG, "OCStack stop error");
807     }
808
809     return 0;
810 }
811
812 std::string getIPAddrTBServer(OCClientResponse * clientResponse)
813 {
814     if (!clientResponse)
815     {
816         return "";
817     }
818     if (!clientResponse->addr)
819     {
820         return "";
821     }
822     uint8_t a, b, c, d = 0;
823     if (0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d))
824     {
825         return "";
826     }
827
828     char ipaddr[16] = {'\0'};
829     // ostringstream not working correctly here, hence snprintf
830     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
831     return std::string (ipaddr);
832 }
833
834 std::string getPortTBServer(OCClientResponse * clientResponse)
835 {
836     if (!clientResponse)
837     {
838         return "";
839     }
840     if (!clientResponse->addr)
841     {
842         return "";
843     }
844     uint16_t p = 0;
845     if (0 != OCDevAddrToPort(clientResponse->addr, &p))
846     {
847         return "";
848     }
849     std::ostringstream ss;
850     ss << p;
851     return ss.str();
852 }
853
854 std::string getConnectivityType (OCConnectivityType connType)
855 {
856     switch (connType)
857     {
858         case OC_ETHERNET:
859             return "Ethernet";
860
861         case OC_WIFI:
862             return "WiFi";
863
864         case OC_LE:
865             return "BLE";
866
867         case OC_EDR:
868             return "BT";
869
870         default:
871             return "Incorrect connectivity";
872     }
873 }
874
875 std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
876 {
877
878     return "/a/light";
879 }
880
881 void parseClientResponse(OCClientResponse * clientResponse)
882 {
883     coapServerIP = getIPAddrTBServer(clientResponse);
884     coapServerPort = getPortTBServer(clientResponse);
885     coapServerResource = getQueryStrForGetPut(clientResponse);
886 }
887