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"
34 #define TAG "occlientbasicops"
35 static int UNICAST_DISCOVERY = 0;
36 static int TEST_CASE = 0;
37 static int CONN_TYPE = 0;
39 static int IPV4_ADDR_SIZE = 16;
40 static char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oic/res";
41 static char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
42 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
44 static std::string putPayload = "{\"oic\":[{\"rep\":{\"state\":\"off\",\"power\":10}}]}";
45 static std::string coapServerIP;
46 static std::string coapServerPort;
47 static std::string coapServerResource;
48 static int coapSecureResource;
49 static OCConnectivityType ocConnType;
52 //Secure Virtual Resource database for Iotivity Client application
53 //It contains Client's Identity and the PSK credentials
54 //of other devices which the client trusts
55 static char CRED_FILE[] = "oic_svr_db_client.json";
60 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
61 void handleSigInt(int signum)
69 static void PrintUsage()
71 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1|2>");
72 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
73 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
74 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
75 " Initiate Nonconfirmable Get/Put/Post Requests");
76 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
77 OC_LOG(INFO, TAG, "-c 0 : Default IPv4 and IPv6 auto-selection");
78 OC_LOG(INFO, TAG, "-c 1 : IPv4 Connectivity Type");
79 OC_LOG(INFO, TAG, "-c 2 : IPv6 Connectivity Type (IPv6 not currently supported)");
82 OCStackResult InvokeOCDoResource(std::ostringstream &query,
83 OCMethod method, OCQualityOfService qos,
84 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
87 OCCallbackData cbData;
90 cbData.context = NULL;
93 ret = OCDoResource(NULL, method, query.str().c_str(), 0,
94 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
95 ocConnType, qos, &cbData, options, numOptions);
97 if (ret != OC_STACK_OK)
99 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
105 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
107 OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
111 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
112 OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
114 return OC_STACK_DELETE_TRANSACTION;
117 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
119 OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
123 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
124 OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
125 clientResponse->resJSONPayload);
127 return OC_STACK_DELETE_TRANSACTION;
130 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
132 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
136 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
137 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
138 OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
139 clientResponse->resJSONPayload);
141 return OC_STACK_DELETE_TRANSACTION;
144 // This is a function called back when a device is discovered
145 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
146 OCClientResponse * clientResponse)
148 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
152 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
154 "Device =============> Discovered %s @ %s:%d",
155 clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
157 ocConnType = clientResponse->connType;
159 if (parseClientResponse(clientResponse) != -1)
163 case TEST_NON_CON_OP:
164 InitGetRequest(OC_LOW_QOS);
165 InitPutRequest(OC_LOW_QOS);
166 //InitPostRequest(OC_LOW_QOS);
169 InitGetRequest(OC_HIGH_QOS);
170 InitPutRequest(OC_HIGH_QOS);
171 //InitPostRequest(OC_HIGH_QOS);
177 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
181 int InitPutRequest(OCQualityOfService qos)
183 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
184 std::ostringstream query;
185 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
186 << ":" << coapServerPort << coapServerResource;
187 return (InvokeOCDoResource(query, OC_REST_PUT,
188 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
191 int InitPostRequest(OCQualityOfService qos)
193 OCStackResult result;
194 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
195 std::ostringstream query;
196 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
197 << ":" << coapServerPort << coapServerResource;
199 // First POST operation (to create an LED instance)
200 result = InvokeOCDoResource(query, OC_REST_POST,
201 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
203 if (OC_STACK_OK != result)
205 // Error can happen if for example, network connectivity is down
206 OC_LOG(INFO, TAG, "First POST call did not succeed");
209 // Second POST operation (to create an LED instance)
210 result = InvokeOCDoResource(query, OC_REST_POST,
211 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
213 if (OC_STACK_OK != result)
215 OC_LOG(INFO, TAG, "Second POST call did not succeed");
218 // This POST operation will update the original resourced /a/led
219 return (InvokeOCDoResource(query, OC_REST_POST,
220 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
221 postReqCB, NULL, 0));
224 int InitGetRequest(OCQualityOfService qos)
226 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
227 std::ostringstream query;
228 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
229 << ":" << coapServerPort << coapServerResource;
231 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
232 OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
239 OCCallbackData cbData;
240 char szQueryUri[MAX_URI_LENGTH] = { 0 };
242 if (UNICAST_DISCOVERY)
244 char ipv4addr[IPV4_ADDR_SIZE];
245 printf("Enter IPv4 address of the Server hosting secure resource (Ex: 11.12.13.14)\n");
246 if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
248 //Strip newline char from ipv4addr
249 StripNewLineChar(ipv4addr);
250 snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
254 OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
255 return OC_STACK_INVALID_PARAM;
257 method = OC_REST_GET;
261 //Send discovery request on Wifi and Ethernet interface
262 discoveryReqConnType = CT_DEFAULT;
263 strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
264 method = OC_REST_DISCOVER;
267 cbData.cb = discoveryReqCB;
268 cbData.context = NULL;
271 /* Start a discovery query*/
272 OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
273 (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
276 ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
277 discoveryReqConnType, OC_LOW_QOS,
279 if (ret != OC_STACK_OK)
281 OC_LOG(ERROR, TAG, "OCStack resource error");
286 FILE* client_fopen(const char *path, const char *mode)
289 return fopen(CRED_FILE, mode);
292 int main(int argc, char* argv[])
295 struct timespec timeout;
297 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
302 UNICAST_DISCOVERY = atoi(optarg);
305 TEST_CASE = atoi(optarg);
308 CONN_TYPE = atoi(optarg);
316 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
317 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS)||
318 (CONN_TYPE < CT_ADAPTER_DEFAULT || CONN_TYPE >= MAX_CT))
325 if(CONN_TYPE == CT_ADAPTER_DEFAULT)
327 discoveryReqConnType = CT_DEFAULT;
329 else if(CONN_TYPE == CT_IPV4)
331 discoveryReqConnType = CT_IP_USE_V4;
333 else if(CONN_TYPE == CT_IPV6)
335 //TODO: Remove when IPv6 is available.
336 //discoveryReqConnType = CT_IP_USE_V6;
337 OC_LOG(ERROR, TAG, "IPv6 is currently not supported !!!!");
343 printf("Using Default Connectivity type\n\n");
348 // Initialize Persistent Storage for SVR database
349 OCPersistentStorage ps = {};
350 ps.open = client_fopen;
355 OCRegisterPersistentStorageHandler(&ps);
357 /* Initialize OCStack*/
358 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
360 OC_LOG(ERROR, TAG, "OCStack init error");
367 timeout.tv_nsec = 100000000L;
369 // Break from loop with Ctrl+C
370 OC_LOG(INFO, TAG, "Entering occlient main loop...");
371 signal(SIGINT, handleSigInt);
374 if (OCProcess() != OC_STACK_OK)
376 OC_LOG(ERROR, TAG, "OCStack process error");
380 nanosleep(&timeout, NULL);
382 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
384 if (OCStop() != OC_STACK_OK)
386 OC_LOG(ERROR, TAG, "OCStack stop error");
392 std::string getPortTBServer(OCClientResponse * clientResponse)
394 if(!clientResponse) return "";
395 std::ostringstream ss;
396 ss << clientResponse->devAddr.port;
400 int parseClientResponse(OCClientResponse * clientResponse)
406 // Initialize all global variables
407 coapServerResource.clear();
408 coapServerPort.clear();
409 coapServerIP.clear();
410 coapSecureResource = 0;
412 root = cJSON_Parse((char *)(clientResponse->resJSONPayload));
418 oc = cJSON_GetObjectItem(root,"oic");
419 if (!oc || oc->type != cJSON_Array)
425 cJSON * firstDevice = cJSON_GetArrayItem(oc, 0);
432 cJSON * links = cJSON_GetObjectItem(firstDevice,"links");
439 if (links->type == cJSON_Array)
441 int numRsrcs = cJSON_GetArraySize(links);
442 for(int i = 0; i < numRsrcs; i++)
444 cJSON * resource = cJSON_GetArrayItem(links, i);
445 if (cJSON_GetObjectItem(resource, "href"))
447 coapServerResource.assign(cJSON_GetObjectItem(resource, "href")->valuestring);
451 coapServerResource = "";
453 OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
456 cJSON * policy = cJSON_GetObjectItem(resource,"p");
459 // If this is a secure resource, the info about the port at which the
460 // resource is hosted on server is embedded inside discovery JSON response
461 if (cJSON_GetObjectItem(policy, "sec"))
463 if ((cJSON_GetObjectItem(policy, "sec")->valueint) == 1)
465 coapSecureResource = 1;
468 OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
469 if (cJSON_GetObjectItem(policy, "port"))
471 port = cJSON_GetObjectItem(policy, "port")->valueint;
472 OC_LOG_V(INFO, TAG, "Hosting Server Port (embedded inside JSON) -- %u", port);
474 std::ostringstream ss;
476 coapServerPort = ss.str();
481 // If we discovered a secure resource, exit from here
482 if (coapSecureResource)
490 coapServerIP = clientResponse->devAddr.addr;
493 coapServerPort = getPortTBServer(clientResponse);
494 OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());