ocpayload.h: Factor out logging
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / secure / occlientbasicops.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 "occlientbasicops.h"
31 #include "ocpayload.h"
32 #include "payload_logging.h"
33 #include "oic_string.h"
34 #include "common.h"
35
36 #define TAG "occlientbasicops"
37 static int UNICAST_DISCOVERY = 0;
38 static int TEST_CASE = 0;
39 static int CONN_TYPE = 0;
40
41 static int IPV4_ADDR_SIZE = 24;
42 static char UNICAST_DISCOVERY_QUERY[] = "coap://%s/oic/res";
43 static char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
44 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
45
46 static std::string coapServerIP;
47 static std::string coapServerPort;
48 static std::string coapServerResource;
49 static int coapSecureResource;
50 static OCConnectivityType ocConnType;
51
52
53 //Secure Virtual Resource database for Iotivity Client application
54 //It contains Client's Identity and the PSK credentials
55 //of other devices which the client trusts
56 static char CRED_FILE[] = "oic_svr_db_client.json";
57
58
59 int gQuitFlag = 0;
60
61 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
62 void handleSigInt(int signum)
63 {
64     if (signum == SIGINT)
65     {
66         gQuitFlag = 1;
67     }
68 }
69
70 OCPayload* putPayload()
71 {
72     OCRepPayload* payload = OCRepPayloadCreate();
73
74     if(!payload)
75     {
76         std::cout << "Failed to create put payload object"<<std::endl;
77         std::exit(1);
78     }
79
80     OCRepPayloadSetPropInt(payload, "power", 15);
81     OCRepPayloadSetPropBool(payload, "state", true);
82
83     return (OCPayload*) payload;
84 }
85
86 static void PrintUsage()
87 {
88     OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
89     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
90     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
91     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
92             " Initiate Nonconfirmable Get/Put/Post Requests");
93     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
94     OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
95     OC_LOG(INFO, TAG, "-c 1 : IPv4 Connectivity Type");
96 }
97
98 OCStackResult InvokeOCDoResource(std::ostringstream &query,
99         OCMethod method, OCQualityOfService qos,
100         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
101 {
102     OCStackResult ret;
103     OCCallbackData cbData;
104
105     cbData.cb = cb;
106     cbData.context = NULL;
107     cbData.cd = NULL;
108
109     ret = OCDoResource(NULL, method, query.str().c_str(), 0,
110             (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
111             ocConnType, qos, &cbData, options, numOptions);
112
113     if (ret != OC_STACK_OK)
114     {
115         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
116     }
117
118     return ret;
119 }
120
121 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
122 {
123     OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
124
125     if(clientResponse)
126     {
127         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
128         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
129         OC_LOG(INFO, TAG, PCF("=============> Put Response"));
130     }
131     return OC_STACK_DELETE_TRANSACTION;
132 }
133
134 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
135 {
136     OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
137
138     if(clientResponse)
139     {
140         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
141         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
142         OC_LOG(INFO, TAG, PCF("=============> Post Response"));
143     }
144     return OC_STACK_DELETE_TRANSACTION;
145 }
146
147 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
148 {
149     OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
150
151     if(clientResponse)
152     {
153         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
154         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
155         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
156         OC_LOG(INFO, TAG, PCF("=============> Get Response"));
157     }
158     return OC_STACK_DELETE_TRANSACTION;
159 }
160
161 // This is a function called back when a device is discovered
162 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
163         OCClientResponse * clientResponse)
164 {
165     OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
166
167     if (clientResponse)
168     {
169         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
170         OC_LOG_V(INFO, TAG,
171                 "Device =============> Discovered @ %s:%d",
172                 clientResponse->devAddr.addr,
173                 clientResponse->devAddr.port);
174
175         if (clientResponse->result == OC_STACK_OK)
176         {
177             OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
178
179             ocConnType = clientResponse->connType;
180
181             if (parseClientResponse(clientResponse) != -1)
182             {
183                 switch(TEST_CASE)
184                 {
185                     case TEST_NON_CON_OP:
186                         InitGetRequest(OC_LOW_QOS);
187                         InitPutRequest(OC_LOW_QOS);
188                         //InitPostRequest(OC_LOW_QOS);
189                         break;
190                     case TEST_CON_OP:
191                         InitGetRequest(OC_HIGH_QOS);
192                         InitPutRequest(OC_HIGH_QOS);
193                         //InitPostRequest(OC_HIGH_QOS);
194                         break;
195                 }
196             }
197         }
198     }
199
200     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
201
202 }
203
204 int InitPutRequest(OCQualityOfService qos)
205 {
206     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
207     std::ostringstream query;
208     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
209         << ":" << coapServerPort  << coapServerResource;
210     return (InvokeOCDoResource(query, OC_REST_PUT,
211             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
212 }
213
214 int InitPostRequest(OCQualityOfService qos)
215 {
216     OCStackResult result;
217     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
218     std::ostringstream query;
219     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
220         << ":" << coapServerPort << coapServerResource;
221
222     // First POST operation (to create an LED instance)
223     result = InvokeOCDoResource(query, OC_REST_POST,
224             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
225             postReqCB, NULL, 0);
226     if (OC_STACK_OK != result)
227     {
228         // Error can happen if for example, network connectivity is down
229         OC_LOG(INFO, TAG, "First POST call did not succeed");
230     }
231
232     // Second POST operation (to create an LED instance)
233     result = InvokeOCDoResource(query, OC_REST_POST,
234             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
235             postReqCB, NULL, 0);
236     if (OC_STACK_OK != result)
237     {
238         OC_LOG(INFO, TAG, "Second POST call did not succeed");
239     }
240
241     // This POST operation will update the original resourced /a/led
242     return (InvokeOCDoResource(query, OC_REST_POST,
243                 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
244                 postReqCB, NULL, 0));
245 }
246
247 int InitGetRequest(OCQualityOfService qos)
248 {
249     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
250     std::ostringstream query;
251     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
252         << ":" << coapServerPort << coapServerResource;
253
254     return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
255             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
256 }
257
258 int InitDiscovery()
259 {
260     OCStackResult ret;
261     OCMethod method;
262     OCCallbackData cbData;
263     char szQueryUri[MAX_URI_LENGTH] = { 0 };
264
265     if (UNICAST_DISCOVERY)
266     {
267         char ipv4addr[IPV4_ADDR_SIZE];
268         OC_LOG(INFO, TAG, "Enter IPv4 address:port of the Server hosting secure resource"\
269                 "(Ex: 11.12.13.14:1234)\n");
270         if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
271         {
272             //Strip newline char from ipv4addr
273             StripNewLineChar(ipv4addr);
274             snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
275         }
276         else
277         {
278             OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
279             return OC_STACK_INVALID_PARAM;
280         }
281         method = OC_REST_GET;
282     }
283     else
284     {
285         //Send discovery request on Wifi and Ethernet interface
286         discoveryReqConnType = CT_DEFAULT;
287         OICStrcpy(szQueryUri, sizeof(szQueryUri), MULTICAST_DISCOVERY_QUERY);
288         method = OC_REST_DISCOVER;
289     }
290
291     cbData.cb = discoveryReqCB;
292     cbData.context = NULL;
293     cbData.cd = NULL;
294
295     /* Start a discovery query*/
296     OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
297         (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
298         szQueryUri);
299
300     ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
301             discoveryReqConnType, OC_LOW_QOS,
302             &cbData, NULL, 0);
303     if (ret != OC_STACK_OK)
304     {
305         OC_LOG(ERROR, TAG, "OCStack resource error");
306     }
307     return ret;
308 }
309
310 FILE* client_fopen(const char *path, const char *mode)
311 {
312     (void)path;
313     return fopen(CRED_FILE, mode);
314 }
315
316 int main(int argc, char* argv[])
317 {
318     int opt;
319     struct timespec timeout;
320
321     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
322     {
323         switch(opt)
324         {
325             case 'u':
326                 UNICAST_DISCOVERY = atoi(optarg);
327                 break;
328             case 't':
329                 TEST_CASE = atoi(optarg);
330                 break;
331             case 'c':
332                 CONN_TYPE = atoi(optarg);
333                 break;
334             default:
335                 PrintUsage();
336                 return -1;
337         }
338     }
339
340     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
341             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS)||
342             (CONN_TYPE < CT_ADAPTER_DEFAULT || CONN_TYPE >= MAX_CT))
343     {
344         PrintUsage();
345         return -1;
346     }
347
348
349     if(CONN_TYPE == CT_ADAPTER_DEFAULT || CONN_TYPE ==  CT_IP)
350     {
351         discoveryReqConnType = CT_DEFAULT;
352     }
353     else
354     {
355         OC_LOG(INFO, TAG, "Using Default Connectivity type");
356         PrintUsage();
357     }
358
359
360     // Initialize Persistent Storage for SVR database
361     OCPersistentStorage ps = {};
362     ps.open = client_fopen;
363     ps.read = fread;
364     ps.write = fwrite;
365     ps.close = fclose;
366     ps.unlink = unlink;
367     OCRegisterPersistentStorageHandler(&ps);
368
369     /* Initialize OCStack*/
370     if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
371     {
372         OC_LOG(ERROR, TAG, "OCStack init error");
373         return 0;
374     }
375
376     InitDiscovery();
377
378     timeout.tv_sec  = 0;
379     timeout.tv_nsec = 100000000L;
380
381     // Break from loop with Ctrl+C
382     OC_LOG(INFO, TAG, "Entering occlient main loop...");
383     signal(SIGINT, handleSigInt);
384     while (!gQuitFlag)
385     {
386         if (OCProcess() != OC_STACK_OK)
387         {
388             OC_LOG(ERROR, TAG, "OCStack process error");
389             return 0;
390         }
391
392         nanosleep(&timeout, NULL);
393     }
394     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
395
396     if (OCStop() != OC_STACK_OK)
397     {
398         OC_LOG(ERROR, TAG, "OCStack stop error");
399     }
400
401     return 0;
402 }
403
404 std::string getPortTBServer(OCClientResponse * clientResponse)
405 {
406     if(!clientResponse) return "";
407     std::ostringstream ss;
408     ss << clientResponse->devAddr.port;
409     return ss.str();
410 }
411
412 int parseClientResponse(OCClientResponse * clientResponse)
413 {
414     OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
415
416     // Initialize all global variables
417     coapServerResource.clear();
418     coapServerPort.clear();
419     coapServerIP.clear();
420     coapSecureResource = 0;
421
422     while(res)
423     {
424         coapServerResource.assign(res->uri);
425         OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
426
427         if(res->secure)
428         {
429             coapSecureResource = 1;
430         }
431
432         OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
433
434         std::ostringstream ss;
435         ss << res->port;
436         coapServerPort = ss.str();
437         std::cout<<"PORT: "<<coapServerPort;
438
439         // If we discovered a secure resource, exit from here
440         if (coapSecureResource)
441         {
442             break;
443         }
444
445         res = res->next;
446     }
447
448     coapServerIP = clientResponse->devAddr.addr;
449
450     if(coapServerPort.length() == 0 || coapServerPort == "0")
451     {
452         coapServerPort = getPortTBServer(clientResponse);
453         OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());
454     }
455
456     return 0;
457 }
458