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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 #include "iotivity_config.h"
31 /** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
41 #include "occlientbasicops.h"
42 #include "ocpayload.h"
43 #include "payload_logging.h"
44 #include "oic_string.h"
47 #define TAG "occlientbasicops"
48 static int UnicastDiscovery = 0;
49 static int TestCase = 0;
50 static int ConnType = 0;
51 static int DevOwner = 0;
52 static int WithTcp = 0;
54 static char DISCOVERY_QUERY[] = "%s/oic/res";
55 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
56 static OCDevAddr endpoint;
58 static std::string coapServerResource;
59 static int coapSecureResource;
60 static OCConnectivityType ocConnType;
62 //Secure Virtual Resource database for Iotivity Client application
63 //It contains Client's Identity and the PSK credentials
64 //of other devices which the client trusts
65 static char CRED_FILE_DEVOWNER[] = "oic_svr_db_client_devowner.dat";
66 static char CRED_FILE_NONDEVOWNER[] = "oic_svr_db_client_nondevowner.dat";
67 const char * OIC_RSRC_DOXM_URI = "/oic/sec/doxm";
68 const char * OIC_RSRC_PSTAT_URI = "/oic/sec/pstat";
72 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
73 void handleSigInt(int signum)
81 OCPayload* putPayload()
83 OCRepPayload* payload = OCRepPayloadCreate();
87 std::cout << "Failed to create put payload object"<<std::endl;
91 OCRepPayloadSetPropInt(payload, "power", 15);
92 OCRepPayloadSetPropBool(payload, "state", true);
94 return (OCPayload*) payload;
97 static void PrintUsage()
99 OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
100 OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
101 OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
102 OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
103 " Initiate Nonconfirmable Get/Put/Post Requests");
104 OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
105 OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
106 OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
107 OIC_LOG(INFO, TAG, "-d 0 : Client as Non Device Owner");
108 OIC_LOG(INFO, TAG, "-d 1 : Client as Device Owner");
109 OIC_LOG(INFO, TAG, "-p 0 : Use UDP protocol");
110 OIC_LOG(INFO, TAG, "-p 1 : Use TCP protocol");
113 OCStackResult InvokeOCDoResource(std::ostringstream &query,
115 const OCDevAddr *dest,
116 OCQualityOfService qos,
117 OCClientResponseHandler cb,
118 OCHeaderOption * options, uint8_t numOptions)
121 OCCallbackData cbData;
124 cbData.context = NULL;
127 OCPayload* payload = (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL;
129 ret = OCDoRequest(NULL, method, query.str().c_str(), dest,
130 payload, ocConnType, qos, &cbData, options, numOptions);
132 OCPayloadDestroy(payload);
134 if (ret != OC_STACK_OK)
136 OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
142 OCStackApplicationResult putReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
144 OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
148 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
149 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
150 OIC_LOG(INFO, TAG, "=============> Put Response");
152 return OC_STACK_DELETE_TRANSACTION;
155 OCStackApplicationResult postReqCB(void *, OCDoHandle, OCClientResponse *clientResponse)
157 OIC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
161 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
162 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
163 OIC_LOG(INFO, TAG, "=============> Post Response");
165 return OC_STACK_DELETE_TRANSACTION;
168 OCStackApplicationResult getReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
170 OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
174 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
175 OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
176 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
177 OIC_LOG(INFO, TAG, "=============> Get Response");
179 return OC_STACK_DELETE_TRANSACTION;
182 // This is a function called back when a device is discovered
183 OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
184 OCClientResponse * clientResponse)
186 OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
190 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
192 "Device =============> Discovered @ %s:%d",
193 clientResponse->devAddr.addr,
194 clientResponse->devAddr.port);
196 if (clientResponse->result == OC_STACK_OK)
198 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
200 ocConnType = clientResponse->connType;
201 endpoint = clientResponse->devAddr;
203 if (parseClientResponse(clientResponse) != -1)
207 case TEST_NON_CON_OP:
208 InitGetRequest(OC_LOW_QOS);
209 InitPutRequest(OC_LOW_QOS);
210 InitPostRequest(OC_LOW_QOS);
213 InitGetRequest(OC_HIGH_QOS);
214 InitPutRequest(OC_HIGH_QOS);
215 InitPostRequest(OC_HIGH_QOS);
222 return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
225 int InitPutRequest(OCQualityOfService qos)
227 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
228 std::ostringstream query;
229 query << coapServerResource;
232 endpoint.adapter = OC_ADAPTER_TCP;
234 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
235 return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
236 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
239 int InitPostRequest(OCQualityOfService qos)
241 OCStackResult result;
243 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
244 std::ostringstream query;
245 query << coapServerResource;
248 endpoint.adapter = OC_ADAPTER_TCP;
250 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
252 // First POST operation (to create an LED instance)
253 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
254 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
256 if (OC_STACK_OK != result)
258 // Error can happen if for example, network connectivity is down
259 OIC_LOG(INFO, TAG, "First POST call did not succeed");
262 // Second POST operation (to create an LED instance)
263 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
264 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
266 if (OC_STACK_OK != result)
268 OIC_LOG(INFO, TAG, "Second POST call did not succeed");
271 // This POST operation will update the original resourced /a/led (as long as
272 // the server is set to max 2 /lcd resources)
273 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
274 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
276 if (OC_STACK_OK != result)
278 OIC_LOG(INFO, TAG, "Third POST call did not succeed");
283 int InitGetRequest(OCQualityOfService qos)
285 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
286 std::ostringstream query;
287 query << coapServerResource;
290 endpoint.adapter = OC_ADAPTER_TCP;
292 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
294 return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
295 ((qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS),
302 OCCallbackData cbData;
304 char ipaddr[100] = { '\0' };
306 if (UnicastDiscovery)
308 OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
309 OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
310 OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
312 if (fgets(ipaddr, sizeof (ipaddr), stdin))
314 StripNewLineChar(ipaddr); //Strip newline char from ipaddr
318 OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
319 return OC_STACK_INVALID_PARAM;
322 snprintf(queryUri, sizeof (queryUri), DISCOVERY_QUERY, ipaddr);
324 cbData.cb = discoveryReqCB;
325 cbData.context = NULL;
328 /* Start a discovery query*/
329 OIC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
330 (UnicastDiscovery) ? "Unicast" : "Multicast",
333 ret = OCDoRequest(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
334 OC_LOW_QOS, &cbData, NULL, 0);
335 if (ret != OC_STACK_OK)
337 OIC_LOG(ERROR, TAG, "OCStack resource error");
342 FILE* client_fopen_devowner(const char *path, const char *mode)
345 return fopen(CRED_FILE_DEVOWNER, mode);
348 FILE* client_fopen_nondevowner(const char *path, const char *mode)
351 return fopen(CRED_FILE_NONDEVOWNER, mode);
353 int main(int argc, char* argv[])
356 struct timespec timeout;
357 OCPersistentStorage ps;
359 while ((opt = getopt(argc, argv, "u:t:c:d:p:")) != -1)
364 UnicastDiscovery = atoi(optarg);
367 TestCase = atoi(optarg);
370 ConnType = atoi(optarg);
373 DevOwner = atoi(optarg);
377 WithTcp = atoi(optarg);
391 if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
392 (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS)||
393 (ConnType < CT_ADAPTER_DEFAULT || ConnType >= MAX_CT))
400 if(ConnType == CT_ADAPTER_DEFAULT || ConnType == CT_IP)
402 discoveryReqConnType = CT_DEFAULT;
406 OIC_LOG(INFO, TAG, "Using Default Connectivity type");
411 // Initialize Persistent Storage for SVR database
413 ps = { client_fopen_devowner, fread, fwrite, fclose, unlink };
415 ps = { client_fopen_nondevowner, fread, fwrite, fclose, unlink };
416 OCRegisterPersistentStorageHandler(&ps);
418 /* Initialize OCStack*/
419 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
421 OIC_LOG(ERROR, TAG, "OCStack init error");
428 timeout.tv_nsec = 100000000L;
430 // Break from loop with Ctrl+C
431 OIC_LOG(INFO, TAG, "Entering occlient main loop...");
432 signal(SIGINT, handleSigInt);
435 if (OCProcess() != OC_STACK_OK)
437 OIC_LOG(ERROR, TAG, "OCStack process error");
441 nanosleep(&timeout, NULL);
443 OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
445 if (OCStop() != OC_STACK_OK)
447 OIC_LOG(ERROR, TAG, "OCStack stop error");
453 int parseClientResponse(OCClientResponse * clientResponse)
455 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
457 // Initialize all global variables
458 coapServerResource.clear();
459 coapSecureResource = 0;
463 coapServerResource.assign(res->uri);
464 OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
465 if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_DOXM_URI))
467 OIC_LOG(INFO,TAG,"Skip: doxm is secure virtual resource");
471 if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_PSTAT_URI))
473 OIC_LOG(INFO,TAG,"Skip: pstat is secure virtual resource");
482 OIC_LOG_V(INFO,TAG,"SECUREPORT tcp: %d",res->tcpPort);
483 endpoint.port = res->tcpPort;
488 OIC_LOG_V(INFO,TAG,"SECUREPORT udp: %d",res->port);
489 endpoint.port = res->port;
491 coapSecureResource = 1;
494 OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
496 // If we discovered a secure resource, exit from here
497 if (coapSecureResource)