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 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 ;
222 int InitPutRequest(OCQualityOfService qos)
224 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
225 std::ostringstream query;
226 query << coapServerResource;
229 endpoint.adapter = OC_ADAPTER_TCP;
231 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
232 return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
233 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
236 int InitPostRequest(OCQualityOfService qos)
238 OCStackResult result;
240 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
241 std::ostringstream query;
242 query << coapServerResource;
245 endpoint.adapter = OC_ADAPTER_TCP;
247 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
249 // First POST operation (to create an LED instance)
250 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
251 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
253 if (OC_STACK_OK != result)
255 // Error can happen if for example, network connectivity is down
256 OIC_LOG(INFO, TAG, "First POST call did not succeed");
259 // Second POST operation (to create an LED instance)
260 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
261 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
263 if (OC_STACK_OK != result)
265 OIC_LOG(INFO, TAG, "Second POST call did not succeed");
268 // This POST operation will update the original resourced /a/led (as long as
269 // the server is set to max 2 /lcd resources)
270 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
271 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
273 if (OC_STACK_OK != result)
275 OIC_LOG(INFO, TAG, "Third POST call did not succeed");
280 int InitGetRequest(OCQualityOfService qos)
282 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
283 std::ostringstream query;
284 query << coapServerResource;
287 endpoint.adapter = OC_ADAPTER_TCP;
289 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
291 return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
292 ((qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS),
299 OCCallbackData cbData;
301 char ipaddr[100] = { '\0' };
303 if (UnicastDiscovery)
305 OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
306 OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
307 OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
309 if (fgets(ipaddr, sizeof (ipaddr), stdin))
311 StripNewLineChar(ipaddr); //Strip newline char from ipaddr
315 OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
316 return OC_STACK_INVALID_PARAM;
319 snprintf(queryUri, sizeof (queryUri), DISCOVERY_QUERY, ipaddr);
321 cbData.cb = discoveryReqCB;
322 cbData.context = NULL;
325 /* Start a discovery query*/
326 OIC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
327 (UnicastDiscovery) ? "Unicast" : "Multicast",
330 ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
331 OC_LOW_QOS, &cbData, NULL, 0);
332 if (ret != OC_STACK_OK)
334 OIC_LOG(ERROR, TAG, "OCStack resource error");
339 FILE* client_fopen_devowner(const char *path, const char *mode)
342 return fopen(CRED_FILE_DEVOWNER, mode);
345 FILE* client_fopen_nondevowner(const char *path, const char *mode)
348 return fopen(CRED_FILE_NONDEVOWNER, mode);
350 int main(int argc, char* argv[])
353 struct timespec timeout;
354 OCPersistentStorage ps;
356 while ((opt = getopt(argc, argv, "u:t:c:d:p:")) != -1)
361 UnicastDiscovery = atoi(optarg);
364 TestCase = atoi(optarg);
367 ConnType = atoi(optarg);
370 DevOwner = atoi(optarg);
374 WithTcp = atoi(optarg);
388 if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
389 (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS)||
390 (ConnType < CT_ADAPTER_DEFAULT || ConnType >= MAX_CT))
397 if(ConnType == CT_ADAPTER_DEFAULT || ConnType == CT_IP)
399 discoveryReqConnType = CT_DEFAULT;
403 OIC_LOG(INFO, TAG, "Using Default Connectivity type");
408 // Initialize Persistent Storage for SVR database
410 ps = { client_fopen_devowner, fread, fwrite, fclose, unlink };
412 ps = { client_fopen_nondevowner, fread, fwrite, fclose, unlink };
413 OCRegisterPersistentStorageHandler(&ps);
415 /* Initialize OCStack*/
416 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
418 OIC_LOG(ERROR, TAG, "OCStack init error");
425 timeout.tv_nsec = 100000000L;
427 // Break from loop with Ctrl+C
428 OIC_LOG(INFO, TAG, "Entering occlient main loop...");
429 signal(SIGINT, handleSigInt);
432 if (OCProcess() != OC_STACK_OK)
434 OIC_LOG(ERROR, TAG, "OCStack process error");
438 nanosleep(&timeout, NULL);
440 OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
442 if (OCStop() != OC_STACK_OK)
444 OIC_LOG(ERROR, TAG, "OCStack stop error");
450 int parseClientResponse(OCClientResponse * clientResponse)
452 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
454 // Initialize all global variables
455 coapServerResource.clear();
456 coapSecureResource = 0;
460 coapServerResource.assign(res->uri);
461 OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
462 if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_DOXM_URI))
464 OIC_LOG(INFO,TAG,"Skip: doxm is secure virtual resource");
468 if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_PSTAT_URI))
470 OIC_LOG(INFO,TAG,"Skip: pstat is secure virtual resource");
479 OIC_LOG_V(INFO,TAG,"SECUREPORT tcp: %d",res->tcpPort);
480 endpoint.port = res->tcpPort;
485 OIC_LOG_V(INFO,TAG,"SECUREPORT udp: %d",res->port);
486 endpoint.port = res->port;
488 coapSecureResource = 1;
491 OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
493 // If we discovered a secure resource, exit from here
494 if (coapSecureResource)