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;
53 static char DISCOVERY_QUERY[] = "%s/oic/res";
54 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
55 static OCDevAddr endpoint;
57 static std::string coapServerResource;
58 static int coapSecureResource;
59 static OCConnectivityType ocConnType;
61 //Secure Virtual Resource database for Iotivity Client application
62 //It contains Client's Identity and the PSK credentials
63 //of other devices which the client trusts
64 static char CRED_FILE_DEVOWNER[] = "oic_svr_db_client_devowner.dat";
65 static char CRED_FILE_NONDEVOWNER[] = "oic_svr_db_client_nondevowner.dat";
66 const char * OIC_RSRC_DOXM_URI = "/oic/sec/doxm";
67 const char * OIC_RSRC_PSTAT_URI = "/oic/sec/pstat";
71 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
72 void handleSigInt(int signum)
80 OCPayload* putPayload()
82 OCRepPayload* payload = OCRepPayloadCreate();
86 std::cout << "Failed to create put payload object"<<std::endl;
90 OCRepPayloadSetPropInt(payload, "power", 15);
91 OCRepPayloadSetPropBool(payload, "state", true);
93 return (OCPayload*) payload;
96 static void PrintUsage()
98 OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
99 OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
100 OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
101 OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
102 " Initiate Nonconfirmable Get/Put/Post Requests");
103 OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
104 OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
105 OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
106 OIC_LOG(INFO, TAG, "-d 0 : Client as Non Device Owner");
107 OIC_LOG(INFO, TAG, "-d 1 : Client as Device Owner");
110 OCStackResult InvokeOCDoResource(std::ostringstream &query,
112 const OCDevAddr *dest,
113 OCQualityOfService qos,
114 OCClientResponseHandler cb,
115 OCHeaderOption * options, uint8_t numOptions)
118 OCCallbackData cbData;
121 cbData.context = NULL;
124 ret = OCDoResource(NULL, method, query.str().c_str(), dest,
125 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
126 ocConnType, qos, &cbData, options, numOptions);
128 if (ret != OC_STACK_OK)
130 OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
136 OCStackApplicationResult putReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
138 OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
142 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
143 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
144 OIC_LOG(INFO, TAG, ("=============> Put Response"));
146 return OC_STACK_DELETE_TRANSACTION;
149 OCStackApplicationResult postReqCB(void *, OCDoHandle, OCClientResponse *clientResponse)
151 OIC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
155 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
156 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
157 OIC_LOG(INFO, TAG, ("=============> Post Response"));
159 return OC_STACK_DELETE_TRANSACTION;
162 OCStackApplicationResult getReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
164 OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
168 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
169 OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
170 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
171 OIC_LOG(INFO, TAG, ("=============> Get Response"));
173 return OC_STACK_DELETE_TRANSACTION;
176 // This is a function called back when a device is discovered
177 OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
178 OCClientResponse * clientResponse)
180 OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
184 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
186 "Device =============> Discovered @ %s:%d",
187 clientResponse->devAddr.addr,
188 clientResponse->devAddr.port);
190 if (clientResponse->result == OC_STACK_OK)
192 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
194 ocConnType = clientResponse->connType;
195 endpoint = clientResponse->devAddr;
197 if (parseClientResponse(clientResponse) != -1)
201 case TEST_NON_CON_OP:
202 InitGetRequest(OC_LOW_QOS);
203 InitPutRequest(OC_LOW_QOS);
204 //InitPostRequest(OC_LOW_QOS);
207 InitGetRequest(OC_HIGH_QOS);
208 InitPutRequest(OC_HIGH_QOS);
209 //InitPostRequest(OC_HIGH_QOS);
216 return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
220 int InitPutRequest(OCQualityOfService qos)
222 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
223 std::ostringstream query;
224 query << coapServerResource;
225 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
226 return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
227 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
230 int InitPostRequest(OCQualityOfService qos)
232 OCStackResult result;
234 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
235 std::ostringstream query;
236 query << coapServerResource;
237 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
239 // First POST operation (to create an LED instance)
240 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
241 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
243 if (OC_STACK_OK != result)
245 // Error can happen if for example, network connectivity is down
246 OIC_LOG(INFO, TAG, "First POST call did not succeed");
249 // Second 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 OIC_LOG(INFO, TAG, "Second POST call did not succeed");
258 // This POST operation will update the original resourced /a/led
259 return (InvokeOCDoResource(query, OC_REST_POST, &endpoint,
260 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
261 postReqCB, NULL, 0));
264 int InitGetRequest(OCQualityOfService qos)
266 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
267 std::ostringstream query;
268 query << coapServerResource;
269 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
271 return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
272 ((qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS),
279 OCCallbackData cbData;
281 char ipaddr[100] = { '\0' };
283 if (UnicastDiscovery)
285 OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
286 OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
287 OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
289 if (fgets(ipaddr, sizeof (ipaddr), stdin))
291 StripNewLineChar(ipaddr); //Strip newline char from ipaddr
295 OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
296 return OC_STACK_INVALID_PARAM;
299 snprintf(queryUri, sizeof (queryUri), DISCOVERY_QUERY, ipaddr);
301 cbData.cb = discoveryReqCB;
302 cbData.context = NULL;
305 /* Start a discovery query*/
306 OIC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
307 (UnicastDiscovery) ? "Unicast" : "Multicast",
310 ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
311 OC_LOW_QOS, &cbData, NULL, 0);
312 if (ret != OC_STACK_OK)
314 OIC_LOG(ERROR, TAG, "OCStack resource error");
319 FILE* client_fopen_devowner(const char *path, const char *mode)
322 return fopen(CRED_FILE_DEVOWNER, mode);
325 FILE* client_fopen_nondevowner(const char *path, const char *mode)
328 return fopen(CRED_FILE_NONDEVOWNER, mode);
330 int main(int argc, char* argv[])
333 struct timespec timeout;
334 OCPersistentStorage ps;
336 while ((opt = getopt(argc, argv, "u:t:c:d:")) != -1)
341 UnicastDiscovery = atoi(optarg);
344 TestCase = atoi(optarg);
347 ConnType = atoi(optarg);
350 DevOwner = atoi(optarg);
358 if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
359 (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS)||
360 (ConnType < CT_ADAPTER_DEFAULT || ConnType >= MAX_CT))
367 if(ConnType == CT_ADAPTER_DEFAULT || ConnType == CT_IP)
369 discoveryReqConnType = CT_DEFAULT;
373 OIC_LOG(INFO, TAG, "Using Default Connectivity type");
378 // Initialize Persistent Storage for SVR database
380 ps = { client_fopen_devowner, fread, fwrite, fclose, unlink };
382 ps = { client_fopen_nondevowner, fread, fwrite, fclose, unlink };
383 OCRegisterPersistentStorageHandler(&ps);
385 /* Initialize OCStack*/
386 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
388 OIC_LOG(ERROR, TAG, "OCStack init error");
395 timeout.tv_nsec = 100000000L;
397 // Break from loop with Ctrl+C
398 OIC_LOG(INFO, TAG, "Entering occlient main loop...");
399 signal(SIGINT, handleSigInt);
402 if (OCProcess() != OC_STACK_OK)
404 OIC_LOG(ERROR, TAG, "OCStack process error");
408 nanosleep(&timeout, NULL);
410 OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
412 if (OCStop() != OC_STACK_OK)
414 OIC_LOG(ERROR, TAG, "OCStack stop error");
420 int parseClientResponse(OCClientResponse * clientResponse)
422 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
424 // Initialize all global variables
425 coapServerResource.clear();
426 coapSecureResource = 0;
430 coapServerResource.assign(res->uri);
431 OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
432 if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_DOXM_URI))
434 OIC_LOG(INFO,TAG,"Skip: doxm is secure virtual resource");
438 if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_PSTAT_URI))
440 OIC_LOG(INFO,TAG,"Skip: pstat is secure virtual resource");
446 OIC_LOG_V(INFO,TAG,"SECUREPORT: %d",res->port);
447 endpoint.port = res->port;
448 coapSecureResource = 1;
451 OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
453 // If we discovered a secure resource, exit from here
454 if (coapSecureResource)