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 const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
38 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
39 static std::string coapServerIP;
40 static std::string coapServerPort;
41 static std::string coapServerResource;
42 static int coapSecureResource;
44 //File containing Client's Identity and the PSK credentials
45 //of other devices which the client trusts
46 //This can be generated using 'gen_sec_bin' application
47 static char CRED_FILE[] = "client_cred.bin";
52 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
53 void handleSigInt(int signum)
61 static void PrintUsage()
63 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
64 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
65 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
66 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
67 " Initiate Nonconfirmable Get/Put/Post Requests");
68 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
71 OCStackResult InvokeOCDoResource(std::ostringstream &query,
72 OCMethod method, OCQualityOfService qos,
73 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
76 OCCallbackData cbData;
80 cbData.context = NULL;
83 ret = OCDoResource(&handle, method, query.str().c_str(), 0,
84 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
85 qos, &cbData, options, numOptions);
87 if (ret != OC_STACK_OK)
89 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
95 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
97 OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
101 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
102 OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
104 return OC_STACK_DELETE_TRANSACTION;
107 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
109 OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
113 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
114 OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
115 clientResponse->resJSONPayload);
117 return OC_STACK_DELETE_TRANSACTION;
120 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
122 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
126 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
127 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
128 OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
129 clientResponse->resJSONPayload);
131 return OC_STACK_DELETE_TRANSACTION;
134 // This is a function called back when a device is discovered
135 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
136 OCClientResponse * clientResponse)
138 uint8_t remoteIpAddr[4];
139 uint16_t remotePortNu;
141 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
145 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
147 OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
148 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
149 OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
152 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
153 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
154 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
156 if (parseClientResponse(clientResponse) != -1)
160 case TEST_NON_CON_OP:
161 InitGetRequest(OC_LOW_QOS);
163 //InitPostRequest(OC_LOW_QOS);
166 InitGetRequest(OC_HIGH_QOS);
168 //InitPostRequest(OC_HIGH_QOS);
174 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
180 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
181 std::ostringstream query;
182 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
183 << ":" << coapServerPort << coapServerResource;
184 return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
187 int InitPostRequest(OCQualityOfService qos)
189 OCStackResult result;
190 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
191 std::ostringstream query;
192 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
193 << ":" << coapServerPort << coapServerResource;
195 // First POST operation (to create an LED instance)
196 result = InvokeOCDoResource(query, OC_REST_POST,
197 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
199 if (OC_STACK_OK != result)
201 // Error can happen if for example, network connectivity is down
202 OC_LOG(INFO, TAG, "First POST call did not succeed");
205 // Second POST operation (to create an LED instance)
206 result = InvokeOCDoResource(query, OC_REST_POST,
207 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
209 if (OC_STACK_OK != result)
211 OC_LOG(INFO, TAG, "Second POST call did not succeed");
214 // This POST operation will update the original resourced /a/led
215 return (InvokeOCDoResource(query, OC_REST_POST,
216 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
217 postReqCB, NULL, 0));
220 int InitGetRequest(OCQualityOfService qos)
222 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
223 std::ostringstream query;
224 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
225 << ":" << coapServerPort << coapServerResource;
227 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
228 OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
234 OCCallbackData cbData;
236 /* Start a discovery query*/
237 char szQueryUri[64] = { 0 };
238 if (UNICAST_DISCOVERY)
240 strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
244 strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
246 cbData.cb = discoveryReqCB;
247 cbData.context = NULL;
249 ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
250 if (ret != OC_STACK_OK)
252 OC_LOG(ERROR, TAG, "OCStack resource error");
257 int main(int argc, char* argv[])
259 uint8_t addr[20] = {0};
260 uint8_t* paddr = NULL;
261 uint16_t port = USE_RANDOM_PORT;
262 uint8_t ifname[] = "eth0";
264 struct timespec timeout;
266 while ((opt = getopt(argc, argv, "u:t:")) != -1)
271 UNICAST_DISCOVERY = atoi(optarg);
274 TEST_CASE = atoi(optarg);
282 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
283 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
290 /*Get Ip address on defined interface and initialize coap on it with random port number
291 * this port number will be used as a source port in all coap communications*/
292 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
293 sizeof(addr)) == ERR_SUCCESS)
295 OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
299 /* Initialize OCStack*/
300 if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK)
302 OC_LOG(ERROR, TAG, "OCStack init error");
307 * Read DTLS PSK credentials from persistent storage and
308 * set in the OC stack.
310 if (SetCredentials(CRED_FILE) != OC_STACK_OK)
312 OC_LOG(ERROR, TAG, "SetCredentials failed");
319 timeout.tv_nsec = 100000000L;
321 // Break from loop with Ctrl+C
322 OC_LOG(INFO, TAG, "Entering occlient main loop...");
323 signal(SIGINT, handleSigInt);
326 if (OCProcess() != OC_STACK_OK)
328 OC_LOG(ERROR, TAG, "OCStack process error");
332 nanosleep(&timeout, NULL);
334 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
336 if (OCStop() != OC_STACK_OK)
338 OC_LOG(ERROR, TAG, "OCStack stop error");
344 std::string getIPAddrTBServer(OCClientResponse * clientResponse)
346 if(!clientResponse) return "";
347 if(!clientResponse->addr) return "";
348 uint8_t a, b, c, d = 0;
349 if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
351 char ipaddr[16] = {'\0'};
352 // ostringstream not working correctly here, hence snprintf
353 snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
354 return std::string (ipaddr);
358 std::string getPortTBServer(OCClientResponse * clientResponse)
360 if(!clientResponse) return "";
361 if(!clientResponse->addr) return "";
363 if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
364 std::ostringstream ss;
369 int parseClientResponse(OCClientResponse * clientResponse)
375 // Initialize all global variables
376 coapServerResource.clear();
377 coapServerPort.clear();
378 coapServerIP.clear();
379 coapSecureResource = 0;
381 root = cJSON_Parse((char *)(clientResponse->resJSONPayload));
387 oc = cJSON_GetObjectItem(root,"oc");
393 if (oc->type == cJSON_Array)
395 if (cJSON_GetArraySize(oc) > 0)
397 cJSON * resource = cJSON_GetArrayItem(oc, 0);
398 if (cJSON_GetObjectItem(resource, "href"))
400 coapServerResource.assign(cJSON_GetObjectItem(resource, "href")->valuestring);
404 coapServerResource = "";
406 OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
408 cJSON * prop = cJSON_GetObjectItem(resource,"prop");
411 // If this is a secure resource, the info about the port at which the
412 // resource is hosted on server is embedded inside discovery JSON response
413 if (cJSON_GetObjectItem(prop, "sec"))
415 if ((cJSON_GetObjectItem(prop, "sec")->valueint) == 1)
417 coapSecureResource = 1;
420 OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
421 if (cJSON_GetObjectItem(prop, "port"))
423 port = cJSON_GetObjectItem(prop, "port")->valueint;
424 OC_LOG_V(INFO, TAG, "Hosting Server Port (embedded inside JSON) -- %u", port);
426 std::ostringstream ss;
428 coapServerPort = ss.str();
435 coapServerIP = getIPAddrTBServer(clientResponse);
438 coapServerPort = getPortTBServer(clientResponse);
439 OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());