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;
39 static int IPV4_ADDR_SIZE = 16;
41 static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
43 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
44 static std::string coapServerIP;
45 static std::string coapServerPort;
46 static std::string coapServerResource;
47 static int coapSecureResource;
49 //File containing Client's Identity and the PSK credentials
50 //of other devices which the client trusts
51 //This can be generated using 'gen_sec_bin' application
52 static char CRED_FILE[] = "client_cred.bin";
57 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
58 void handleSigInt(int signum)
66 static void PrintUsage()
68 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
69 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
70 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
71 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
72 " Initiate Nonconfirmable Get/Put/Post Requests");
73 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
76 OCStackResult InvokeOCDoResource(std::ostringstream &query,
77 OCMethod method, OCQualityOfService qos,
78 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
81 OCCallbackData cbData;
85 cbData.context = NULL;
88 ret = OCDoResource(&handle, method, query.str().c_str(), 0,
89 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
90 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 if (parseClientResponse(clientResponse) != -1)
165 case TEST_NON_CON_OP:
166 InitGetRequest(OC_LOW_QOS);
168 //InitPostRequest(OC_LOW_QOS);
171 InitGetRequest(OC_HIGH_QOS);
173 //InitPostRequest(OC_HIGH_QOS);
179 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
185 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
186 std::ostringstream query;
187 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
188 << ":" << coapServerPort << coapServerResource;
189 return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
192 int InitPostRequest(OCQualityOfService qos)
194 OCStackResult result;
195 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
196 std::ostringstream query;
197 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
198 << ":" << coapServerPort << coapServerResource;
200 // First POST operation (to create an LED instance)
201 result = InvokeOCDoResource(query, OC_REST_POST,
202 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
204 if (OC_STACK_OK != result)
206 // Error can happen if for example, network connectivity is down
207 OC_LOG(INFO, TAG, "First POST call did not succeed");
210 // Second POST operation (to create an LED instance)
211 result = InvokeOCDoResource(query, OC_REST_POST,
212 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
214 if (OC_STACK_OK != result)
216 OC_LOG(INFO, TAG, "Second POST call did not succeed");
219 // This POST operation will update the original resourced /a/led
220 return (InvokeOCDoResource(query, OC_REST_POST,
221 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
222 postReqCB, NULL, 0));
225 int InitGetRequest(OCQualityOfService qos)
227 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
228 std::ostringstream query;
229 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
230 << ":" << coapServerPort << coapServerResource;
232 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
233 OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
239 OCCallbackData cbData;
241 /* Start a discovery query*/
242 char szQueryUri[MAX_URI_LENGTH] = { 0 };
244 if (UNICAST_DISCOVERY)
247 char ipv4addr[IPV4_ADDR_SIZE];
249 printf("Enter IPv4 address of the Server hosting secure resource (Ex: 11.12.13.14)\n");
250 fgets(ipv4addr, IPV4_ADDR_SIZE, stdin);
251 snprintf(szQueryUri, sizeof(szQueryUri), "coap://%s:5683/oc/core", ipv4addr);
253 strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
258 strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
260 cbData.cb = discoveryReqCB;
261 cbData.context = NULL;
263 ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
264 if (ret != OC_STACK_OK)
266 OC_LOG(ERROR, TAG, "OCStack resource error");
271 int main(int argc, char* argv[])
273 uint8_t addr[20] = {0};
274 uint8_t* paddr = NULL;
275 uint16_t port = USE_RANDOM_PORT;
276 uint8_t ifname[] = "eth0";
278 struct timespec timeout;
280 while ((opt = getopt(argc, argv, "u:t:")) != -1)
285 UNICAST_DISCOVERY = atoi(optarg);
288 TEST_CASE = atoi(optarg);
296 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
297 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
304 /*Get Ip address on defined interface and initialize coap on it with random port number
305 * this port number will be used as a source port in all coap communications*/
306 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
307 sizeof(addr)) == ERR_SUCCESS)
309 OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
313 /* Initialize OCStack*/
314 if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK)
316 OC_LOG(ERROR, TAG, "OCStack init error");
321 * Read DTLS PSK credentials from persistent storage and
322 * set in the OC stack.
324 if (SetCredentials(CRED_FILE) != OC_STACK_OK)
326 OC_LOG(ERROR, TAG, "SetCredentials failed");
333 timeout.tv_nsec = 100000000L;
335 // Break from loop with Ctrl+C
336 OC_LOG(INFO, TAG, "Entering occlient main loop...");
337 signal(SIGINT, handleSigInt);
340 if (OCProcess() != OC_STACK_OK)
342 OC_LOG(ERROR, TAG, "OCStack process error");
346 nanosleep(&timeout, NULL);
348 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
350 if (OCStop() != OC_STACK_OK)
352 OC_LOG(ERROR, TAG, "OCStack stop error");
358 std::string getIPAddrTBServer(OCClientResponse * clientResponse)
360 if(!clientResponse) return "";
361 if(!clientResponse->addr) return "";
362 uint8_t a, b, c, d = 0;
363 if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
365 char ipaddr[16] = {'\0'};
366 // ostringstream not working correctly here, hence snprintf
367 snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
368 return std::string (ipaddr);
372 std::string getPortTBServer(OCClientResponse * clientResponse)
374 if(!clientResponse) return "";
375 if(!clientResponse->addr) return "";
377 if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
378 std::ostringstream ss;
383 int parseClientResponse(OCClientResponse * clientResponse)
389 // Initialize all global variables
390 coapServerResource.clear();
391 coapServerPort.clear();
392 coapServerIP.clear();
393 coapSecureResource = 0;
395 root = cJSON_Parse((char *)(clientResponse->resJSONPayload));
401 oc = cJSON_GetObjectItem(root,"oc");
407 if (oc->type == cJSON_Array)
409 if (cJSON_GetArraySize(oc) > 0)
411 cJSON * resource = cJSON_GetArrayItem(oc, 0);
412 if (cJSON_GetObjectItem(resource, "href"))
414 coapServerResource.assign(cJSON_GetObjectItem(resource, "href")->valuestring);
418 coapServerResource = "";
420 OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
422 cJSON * prop = cJSON_GetObjectItem(resource,"prop");
425 // If this is a secure resource, the info about the port at which the
426 // resource is hosted on server is embedded inside discovery JSON response
427 if (cJSON_GetObjectItem(prop, "sec"))
429 if ((cJSON_GetObjectItem(prop, "sec")->valueint) == 1)
431 coapSecureResource = 1;
434 OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
435 if (cJSON_GetObjectItem(prop, "port"))
437 port = cJSON_GetObjectItem(prop, "port")->valueint;
438 OC_LOG_V(INFO, TAG, "Hosting Server Port (embedded inside JSON) -- %u", port);
440 std::ostringstream ss;
442 coapServerPort = ss.str();
449 coapServerIP = getIPAddrTBServer(clientResponse);
452 coapServerPort = getPortTBServer(clientResponse);
453 OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());