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;
38 static int IPV4_ADDR_SIZE = 16;
39 static char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oc/core";
40 static char MULTICAST_DISCOVERY_QUERY[] = "/oc/core";
42 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
43 static std::string coapServerIP;
44 static std::string coapServerPort;
45 static std::string coapServerResource;
46 static int coapSecureResource;
47 static OCConnectivityType ocConnType;
50 //File containing Client's Identity and the PSK credentials
51 //of other devices which the client trusts
52 //This can be generated using 'gen_sec_bin' application
53 static char CRED_FILE[] = "client_cred.bin";
58 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
59 void handleSigInt(int signum)
67 static void PrintUsage()
69 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
70 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
71 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
72 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
73 " Initiate Nonconfirmable Get/Put/Post Requests");
74 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
77 OCStackResult InvokeOCDoResource(std::ostringstream &query,
78 OCMethod method, OCQualityOfService qos,
79 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
82 OCCallbackData cbData;
85 cbData.context = NULL;
88 ret = OCDoResource(NULL, method, query.str().c_str(), 0,
89 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
90 ocConnType, qos, &cbData, options, numOptions);
92 if (ret != OC_STACK_OK)
94 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
100 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
102 OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
106 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
107 OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
109 return OC_STACK_DELETE_TRANSACTION;
112 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
114 OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
118 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
119 OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
120 clientResponse->resJSONPayload);
122 return OC_STACK_DELETE_TRANSACTION;
125 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
127 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
131 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
132 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
133 OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
134 clientResponse->resJSONPayload);
136 return OC_STACK_DELETE_TRANSACTION;
139 // This is a function called back when a device is discovered
140 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
141 OCClientResponse * clientResponse)
143 uint8_t remoteIpAddr[4];
144 uint16_t remotePortNu;
146 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
150 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
152 OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
153 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
154 OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
157 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
158 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
159 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
161 ocConnType = clientResponse->connType;
163 if (parseClientResponse(clientResponse) != -1)
167 case TEST_NON_CON_OP:
168 InitGetRequest(OC_LOW_QOS);
169 InitPutRequest(OC_LOW_QOS);
170 //InitPostRequest(OC_LOW_QOS);
173 InitGetRequest(OC_HIGH_QOS);
174 InitPutRequest(OC_HIGH_QOS);
175 //InitPostRequest(OC_HIGH_QOS);
181 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
185 int InitPutRequest(OCQualityOfService qos)
187 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
188 std::ostringstream query;
189 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
190 << ":" << coapServerPort << coapServerResource;
191 return (InvokeOCDoResource(query, OC_REST_PUT,
192 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
195 int InitPostRequest(OCQualityOfService qos)
197 OCStackResult result;
198 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
199 std::ostringstream query;
200 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
201 << ":" << coapServerPort << coapServerResource;
203 // First POST operation (to create an LED instance)
204 result = InvokeOCDoResource(query, OC_REST_POST,
205 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
207 if (OC_STACK_OK != result)
209 // Error can happen if for example, network connectivity is down
210 OC_LOG(INFO, TAG, "First POST call did not succeed");
213 // Second POST operation (to create an LED instance)
214 result = InvokeOCDoResource(query, OC_REST_POST,
215 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
217 if (OC_STACK_OK != result)
219 OC_LOG(INFO, TAG, "Second POST call did not succeed");
222 // This POST operation will update the original resourced /a/led
223 return (InvokeOCDoResource(query, OC_REST_POST,
224 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
225 postReqCB, NULL, 0));
228 int InitGetRequest(OCQualityOfService qos)
230 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
231 std::ostringstream query;
232 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
233 << ":" << coapServerPort << coapServerResource;
235 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
236 OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
239 int InitDiscovery(OCQualityOfService qos)
242 OCCallbackData cbData;
243 char szQueryUri[MAX_URI_LENGTH] = { 0 };
244 OCConnectivityType discoveryReqConnType;
246 if (UNICAST_DISCOVERY)
248 char ipv4addr[IPV4_ADDR_SIZE];
249 printf("Enter IPv4 address of the Server hosting secure resource (Ex: 11.12.13.14)\n");
250 if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
252 //Strip newline char from ipv4addr
253 StripNewLineChar(ipv4addr);
254 snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
258 OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
259 return OC_STACK_INVALID_PARAM;
261 printf("Select Connectivity type on which discovery request needs to be send : ");
262 printf("0:ETH, 1:WIFI\n");
263 discoveryReqConnType = ((getchar() - '0') == 0) ? OC_ETHERNET : OC_WIFI;
267 //Send discovery request on Wifi and Ethernet interface
268 discoveryReqConnType = OC_ALL;
269 strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
272 cbData.cb = discoveryReqCB;
273 cbData.context = NULL;
276 /* Start a discovery query*/
277 OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
278 (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
281 ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0,
282 discoveryReqConnType, ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
284 if (ret != OC_STACK_OK)
286 OC_LOG(ERROR, TAG, "OCStack resource error");
291 int main(int argc, char* argv[])
294 struct timespec timeout;
296 while ((opt = getopt(argc, argv, "u:t:")) != -1)
301 UNICAST_DISCOVERY = atoi(optarg);
304 TEST_CASE = atoi(optarg);
312 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
313 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
319 /* Initialize OCStack*/
320 if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
322 OC_LOG(ERROR, TAG, "OCStack init error");
327 * Read DTLS PSK credentials from persistent storage and
328 * set in the OC stack.
330 if (SetCredentials(CRED_FILE) != OC_STACK_OK)
332 OC_LOG(ERROR, TAG, "SetCredentials failed");
336 if(TEST_CASE == TEST_NON_CON_OP)
338 InitDiscovery(OC_LOW_QOS);
340 else if(TEST_CASE == TEST_CON_OP)
342 InitDiscovery(OC_HIGH_QOS);
346 timeout.tv_nsec = 100000000L;
348 // Break from loop with Ctrl+C
349 OC_LOG(INFO, TAG, "Entering occlient main loop...");
350 signal(SIGINT, handleSigInt);
353 if (OCProcess() != OC_STACK_OK)
355 OC_LOG(ERROR, TAG, "OCStack process error");
359 nanosleep(&timeout, NULL);
361 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
363 if (OCStop() != OC_STACK_OK)
365 OC_LOG(ERROR, TAG, "OCStack stop error");
371 std::string getIPAddrTBServer(OCClientResponse * clientResponse)
373 if(!clientResponse) return "";
374 if(!clientResponse->addr) return "";
375 uint8_t a, b, c, d = 0;
376 if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
378 char ipaddr[16] = {'\0'};
379 // ostringstream not working correctly here, hence snprintf
380 snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
381 return std::string (ipaddr);
385 std::string getPortTBServer(OCClientResponse * clientResponse)
387 if(!clientResponse) return "";
388 if(!clientResponse->addr) return "";
390 if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
391 std::ostringstream ss;
396 int parseClientResponse(OCClientResponse * clientResponse)
402 // Initialize all global variables
403 coapServerResource.clear();
404 coapServerPort.clear();
405 coapServerIP.clear();
406 coapSecureResource = 0;
408 root = cJSON_Parse((char *)(clientResponse->resJSONPayload));
414 oc = cJSON_GetObjectItem(root,"oc");
420 if (oc->type == cJSON_Array)
422 if (cJSON_GetArraySize(oc) > 0)
424 cJSON * resource = cJSON_GetArrayItem(oc, 0);
425 if (cJSON_GetObjectItem(resource, "href"))
427 coapServerResource.assign(cJSON_GetObjectItem(resource, "href")->valuestring);
431 coapServerResource = "";
433 OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
435 cJSON * prop = cJSON_GetObjectItem(resource,"prop");
438 // If this is a secure resource, the info about the port at which the
439 // resource is hosted on server is embedded inside discovery JSON response
440 if (cJSON_GetObjectItem(prop, "sec"))
442 if ((cJSON_GetObjectItem(prop, "sec")->valueint) == 1)
444 coapSecureResource = 1;
447 OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
448 if (cJSON_GetObjectItem(prop, "port"))
450 port = cJSON_GetObjectItem(prop, "port")->valueint;
451 OC_LOG_V(INFO, TAG, "Hosting Server Port (embedded inside JSON) -- %u", port);
453 std::ostringstream ss;
455 coapServerPort = ss.str();
462 coapServerIP = getIPAddrTBServer(clientResponse);
465 coapServerPort = getPortTBServer(clientResponse);
466 OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());