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 #include "occlientbasicops.h"
31 #include "ocpayload.h"
32 #include "payload_logging.h"
33 #include "oic_string.h"
36 #define TAG "occlientbasicops"
37 static int UnicastDiscovery = 0;
38 static int TestCase = 0;
39 static int ConnType = 0;
40 static int DevOwner = 0;
42 static char DISCOVERY_QUERY[] = "%s/oic/res";
43 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
44 static OCDevAddr endpoint;
46 static std::string coapServerResource;
47 static int coapSecureResource;
48 static OCConnectivityType ocConnType;
50 //Secure Virtual Resource database for Iotivity Client application
51 //It contains Client's Identity and the PSK credentials
52 //of other devices which the client trusts
53 static char CRED_FILE_DEVOWNER[] = "oic_svr_db_client_devowner.dat";
54 static char CRED_FILE_NONDEVOWNER[] = "oic_svr_db_client_nondevowner.dat";
55 const char * OIC_RSRC_DOXM_URI = "/oic/sec/doxm";
59 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
60 void handleSigInt(int signum)
68 OCPayload* putPayload()
70 OCRepPayload* payload = OCRepPayloadCreate();
74 std::cout << "Failed to create put payload object"<<std::endl;
78 OCRepPayloadSetPropInt(payload, "power", 15);
79 OCRepPayloadSetPropBool(payload, "state", true);
81 return (OCPayload*) payload;
84 static void PrintUsage()
86 OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
87 OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
88 OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
89 OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
90 " Initiate Nonconfirmable Get/Put/Post Requests");
91 OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
92 OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
93 OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
94 OIC_LOG(INFO, TAG, "-d 0 : Client as Device Owner");
95 OIC_LOG(INFO, TAG, "-d 1 : Client as Non Device Owner");
98 OCStackResult InvokeOCDoResource(std::ostringstream &query,
100 const OCDevAddr *dest,
101 OCQualityOfService qos,
102 OCClientResponseHandler cb,
103 OCHeaderOption * options, uint8_t numOptions)
106 OCCallbackData cbData;
109 cbData.context = NULL;
112 ret = OCDoResource(NULL, method, query.str().c_str(), dest,
113 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
114 ocConnType, qos, &cbData, options, numOptions);
116 if (ret != OC_STACK_OK)
118 OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
124 OCStackApplicationResult putReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
126 OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
130 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
131 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
132 OIC_LOG(INFO, TAG, ("=============> Put Response"));
134 return OC_STACK_DELETE_TRANSACTION;
137 OCStackApplicationResult postReqCB(void *, OCDoHandle, OCClientResponse *clientResponse)
139 OIC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
143 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
144 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
145 OIC_LOG(INFO, TAG, ("=============> Post Response"));
147 return OC_STACK_DELETE_TRANSACTION;
150 OCStackApplicationResult getReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
152 OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
156 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
157 OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
158 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
159 OIC_LOG(INFO, TAG, ("=============> Get Response"));
161 return OC_STACK_DELETE_TRANSACTION;
164 // This is a function called back when a device is discovered
165 OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
166 OCClientResponse * clientResponse)
168 OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
172 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
174 "Device =============> Discovered @ %s:%d",
175 clientResponse->devAddr.addr,
176 clientResponse->devAddr.port);
178 if (clientResponse->result == OC_STACK_OK)
180 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
182 ocConnType = clientResponse->connType;
183 endpoint = clientResponse->devAddr;
185 if (parseClientResponse(clientResponse) != -1)
189 case TEST_NON_CON_OP:
190 InitGetRequest(OC_LOW_QOS);
191 InitPutRequest(OC_LOW_QOS);
192 //InitPostRequest(OC_LOW_QOS);
195 InitGetRequest(OC_HIGH_QOS);
196 InitPutRequest(OC_HIGH_QOS);
197 //InitPostRequest(OC_HIGH_QOS);
204 return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
208 int InitPutRequest(OCQualityOfService qos)
210 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
211 std::ostringstream query;
212 query << coapServerResource;
213 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
214 return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
215 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
218 int InitPostRequest(OCQualityOfService qos)
220 OCStackResult result;
222 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
223 std::ostringstream query;
224 query << coapServerResource;
225 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
227 // First POST operation (to create an LED instance)
228 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
229 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
231 if (OC_STACK_OK != result)
233 // Error can happen if for example, network connectivity is down
234 OIC_LOG(INFO, TAG, "First POST call did not succeed");
237 // Second POST operation (to create an LED instance)
238 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
239 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
241 if (OC_STACK_OK != result)
243 OIC_LOG(INFO, TAG, "Second POST call did not succeed");
246 // This POST operation will update the original resourced /a/led
247 return (InvokeOCDoResource(query, OC_REST_POST, &endpoint,
248 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
249 postReqCB, NULL, 0));
252 int InitGetRequest(OCQualityOfService qos)
254 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
255 std::ostringstream query;
256 query << coapServerResource;
257 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
259 return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
260 ((qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS),
267 OCCallbackData cbData;
269 char ipaddr[100] = { '\0' };
271 if (UnicastDiscovery)
273 OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
274 OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
275 OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
277 if (fgets(ipaddr, sizeof (ipaddr), stdin))
279 StripNewLineChar(ipaddr); //Strip newline char from ipaddr
283 OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
284 return OC_STACK_INVALID_PARAM;
287 snprintf(queryUri, sizeof (queryUri), DISCOVERY_QUERY, ipaddr);
289 cbData.cb = discoveryReqCB;
290 cbData.context = NULL;
293 /* Start a discovery query*/
294 OIC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
295 (UnicastDiscovery) ? "Unicast" : "Multicast",
298 ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
299 OC_LOW_QOS, &cbData, NULL, 0);
300 if (ret != OC_STACK_OK)
302 OIC_LOG(ERROR, TAG, "OCStack resource error");
307 FILE* client_fopen_devowner(const char *path, const char *mode)
310 return fopen(CRED_FILE_DEVOWNER, mode);
313 FILE* client_fopen_nondevowner(const char *path, const char *mode)
316 return fopen(CRED_FILE_NONDEVOWNER, mode);
318 int main(int argc, char* argv[])
321 struct timespec timeout;
322 OCPersistentStorage ps;
324 while ((opt = getopt(argc, argv, "u:t:c:d:")) != -1)
329 UnicastDiscovery = atoi(optarg);
332 TestCase = atoi(optarg);
335 ConnType = atoi(optarg);
338 DevOwner = atoi(optarg);
346 if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
347 (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS)||
348 (ConnType < CT_ADAPTER_DEFAULT || ConnType >= MAX_CT))
355 if(ConnType == CT_ADAPTER_DEFAULT || ConnType == CT_IP)
357 discoveryReqConnType = CT_DEFAULT;
361 OIC_LOG(INFO, TAG, "Using Default Connectivity type");
366 // Initialize Persistent Storage for SVR database
368 ps = { client_fopen_devowner, fread, fwrite, fclose, unlink };
370 ps = { client_fopen_nondevowner, fread, fwrite, fclose, unlink };
371 OCRegisterPersistentStorageHandler(&ps);
373 /* Initialize OCStack*/
374 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
376 OIC_LOG(ERROR, TAG, "OCStack init error");
383 timeout.tv_nsec = 100000000L;
385 // Break from loop with Ctrl+C
386 OIC_LOG(INFO, TAG, "Entering occlient main loop...");
387 signal(SIGINT, handleSigInt);
390 if (OCProcess() != OC_STACK_OK)
392 OIC_LOG(ERROR, TAG, "OCStack process error");
396 nanosleep(&timeout, NULL);
398 OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
400 if (OCStop() != OC_STACK_OK)
402 OIC_LOG(ERROR, TAG, "OCStack stop error");
408 int parseClientResponse(OCClientResponse * clientResponse)
410 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
412 // Initialize all global variables
413 coapServerResource.clear();
414 coapSecureResource = 0;
418 coapServerResource.assign(res->uri);
419 OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
420 if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_DOXM_URI))
422 OIC_LOG(INFO,TAG,"Skip: doxm is secure virtual resource");
428 OIC_LOG_V(INFO,TAG,"SECUREPORT: %d",res->port);
429 endpoint.port = res->port;
430 coapSecureResource = 1;
433 OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
435 // If we discovered a secure resource, exit from here
436 if (coapSecureResource)