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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
30 /** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
38 #include "platform_features.h"
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 ret = OCDoResource(NULL, method, query.str().c_str(), dest,
128 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
129 ocConnType, qos, &cbData, options, numOptions);
131 if (ret != OC_STACK_OK)
133 OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
139 OCStackApplicationResult putReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
141 OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
145 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
146 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
147 OIC_LOG(INFO, TAG, ("=============> Put Response"));
149 return OC_STACK_DELETE_TRANSACTION;
152 OCStackApplicationResult postReqCB(void *, OCDoHandle, OCClientResponse *clientResponse)
154 OIC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
158 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
159 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
160 OIC_LOG(INFO, TAG, ("=============> Post Response"));
162 return OC_STACK_DELETE_TRANSACTION;
165 OCStackApplicationResult getReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
167 OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
171 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
172 OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
173 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
174 OIC_LOG(INFO, TAG, ("=============> Get Response"));
176 return OC_STACK_DELETE_TRANSACTION;
179 // This is a function called back when a device is discovered
180 OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
181 OCClientResponse * clientResponse)
183 OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
187 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
189 "Device =============> Discovered @ %s:%d",
190 clientResponse->devAddr.addr,
191 clientResponse->devAddr.port);
193 if (clientResponse->result == OC_STACK_OK)
195 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
197 ocConnType = clientResponse->connType;
198 endpoint = clientResponse->devAddr;
200 if (parseClientResponse(clientResponse) != -1)
204 case TEST_NON_CON_OP:
205 InitGetRequest(OC_LOW_QOS);
206 InitPutRequest(OC_LOW_QOS);
207 //InitPostRequest(OC_LOW_QOS);
210 InitGetRequest(OC_HIGH_QOS);
211 InitPutRequest(OC_HIGH_QOS);
212 //InitPostRequest(OC_HIGH_QOS);
219 return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
223 int InitPutRequest(OCQualityOfService qos)
225 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
226 std::ostringstream query;
227 query << coapServerResource;
230 endpoint.adapter = OC_ADAPTER_TCP;
232 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
233 return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
234 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
237 int InitPostRequest(OCQualityOfService qos)
239 OCStackResult result;
241 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
242 std::ostringstream query;
243 query << coapServerResource;
244 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
246 // First POST operation (to create an LED instance)
247 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
248 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
250 if (OC_STACK_OK != result)
252 // Error can happen if for example, network connectivity is down
253 OIC_LOG(INFO, TAG, "First POST call did not succeed");
256 // Second POST operation (to create an LED instance)
257 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
258 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
260 if (OC_STACK_OK != result)
262 OIC_LOG(INFO, TAG, "Second POST call did not succeed");
265 // This POST operation will update the original resourced /a/led
266 return (InvokeOCDoResource(query, OC_REST_POST, &endpoint,
267 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
268 postReqCB, NULL, 0));
271 int InitGetRequest(OCQualityOfService qos)
273 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
274 std::ostringstream query;
275 query << coapServerResource;
276 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
278 return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
279 ((qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS),
286 OCCallbackData cbData;
288 char ipaddr[100] = { '\0' };
290 if (UnicastDiscovery)
292 OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
293 OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
294 OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
296 if (fgets(ipaddr, sizeof (ipaddr), stdin))
298 StripNewLineChar(ipaddr); //Strip newline char from ipaddr
302 OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
303 return OC_STACK_INVALID_PARAM;
306 snprintf(queryUri, sizeof (queryUri), DISCOVERY_QUERY, ipaddr);
308 cbData.cb = discoveryReqCB;
309 cbData.context = NULL;
312 /* Start a discovery query*/
313 OIC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
314 (UnicastDiscovery) ? "Unicast" : "Multicast",
317 ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
318 OC_LOW_QOS, &cbData, NULL, 0);
319 if (ret != OC_STACK_OK)
321 OIC_LOG(ERROR, TAG, "OCStack resource error");
326 FILE* client_fopen_devowner(const char *path, const char *mode)
329 return fopen(CRED_FILE_DEVOWNER, mode);
332 FILE* client_fopen_nondevowner(const char *path, const char *mode)
335 return fopen(CRED_FILE_NONDEVOWNER, mode);
337 int main(int argc, char* argv[])
340 struct timespec timeout;
341 OCPersistentStorage ps;
343 while ((opt = getopt(argc, argv, "u:t:c:d:p:")) != -1)
348 UnicastDiscovery = atoi(optarg);
351 TestCase = atoi(optarg);
354 ConnType = atoi(optarg);
357 DevOwner = atoi(optarg);
361 WithTcp = atoi(optarg);
375 if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
376 (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS)||
377 (ConnType < CT_ADAPTER_DEFAULT || ConnType >= MAX_CT))
384 if(ConnType == CT_ADAPTER_DEFAULT || ConnType == CT_IP)
386 discoveryReqConnType = CT_DEFAULT;
390 OIC_LOG(INFO, TAG, "Using Default Connectivity type");
395 // Initialize Persistent Storage for SVR database
397 ps = { client_fopen_devowner, fread, fwrite, fclose, unlink };
399 ps = { client_fopen_nondevowner, fread, fwrite, fclose, unlink };
400 OCRegisterPersistentStorageHandler(&ps);
402 /* Initialize OCStack*/
403 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
405 OIC_LOG(ERROR, TAG, "OCStack init error");
412 timeout.tv_nsec = 100000000L;
414 // Break from loop with Ctrl+C
415 OIC_LOG(INFO, TAG, "Entering occlient main loop...");
416 signal(SIGINT, handleSigInt);
419 if (OCProcess() != OC_STACK_OK)
421 OIC_LOG(ERROR, TAG, "OCStack process error");
425 nanosleep(&timeout, NULL);
427 OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
429 if (OCStop() != OC_STACK_OK)
431 OIC_LOG(ERROR, TAG, "OCStack stop error");
437 int parseClientResponse(OCClientResponse * clientResponse)
439 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
441 // Initialize all global variables
442 coapServerResource.clear();
443 coapSecureResource = 0;
447 coapServerResource.assign(res->uri);
448 OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
449 if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_DOXM_URI))
451 OIC_LOG(INFO,TAG,"Skip: doxm is secure virtual resource");
455 if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_PSTAT_URI))
457 OIC_LOG(INFO,TAG,"Skip: pstat is secure virtual resource");
466 OIC_LOG_V(INFO,TAG,"SECUREPORT tcp: %d",res->tcpPort);
467 endpoint.port = res->tcpPort;
472 OIC_LOG_V(INFO,TAG,"SECUREPORT udp: %d",res->port);
473 endpoint.port = res->port;
475 coapSecureResource = 1;
478 OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
480 // If we discovered a secure resource, exit from here
481 if (coapSecureResource)