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"
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 = 24;
40 static char UNICAST_DISCOVERY_QUERY[] = "coap://%s/oic/res";
41 static char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
42 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
44 static std::string coapServerIP;
45 static std::string coapServerPort;
46 static std::string coapServerResource;
47 static int coapSecureResource;
48 static OCConnectivityType ocConnType;
51 //Secure Virtual Resource database for Iotivity Client application
52 //It contains Client's Identity and the PSK credentials
53 //of other devices which the client trusts
54 static char CRED_FILE[] = "oic_svr_db_client.json";
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 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
87 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
88 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
89 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
90 " Initiate Nonconfirmable Get/Put/Post Requests");
91 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
92 OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
93 OC_LOG(INFO, TAG, "-c 1 : IPv4 Connectivity Type");
96 OCStackResult InvokeOCDoResource(std::ostringstream &query,
97 OCMethod method, OCQualityOfService qos,
98 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
101 OCCallbackData cbData;
104 cbData.context = NULL;
107 ret = OCDoResource(NULL, method, query.str().c_str(), 0,
108 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
109 ocConnType, qos, &cbData, options, numOptions);
111 if (ret != OC_STACK_OK)
113 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
119 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
121 OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
125 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
126 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
127 OC_LOG(INFO, TAG, PCF("=============> Put Response"));
129 return OC_STACK_DELETE_TRANSACTION;
132 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
134 OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
138 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
139 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
140 OC_LOG(INFO, TAG, PCF("=============> Post Response"));
142 return OC_STACK_DELETE_TRANSACTION;
145 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
147 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
151 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
152 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
153 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
154 OC_LOG(INFO, TAG, PCF("=============> Get Response"));
156 return OC_STACK_DELETE_TRANSACTION;
159 // This is a function called back when a device is discovered
160 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
161 OCClientResponse * clientResponse)
163 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
167 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
169 "Device =============> Discovered @ %s:%d",
170 clientResponse->devAddr.addr,
171 clientResponse->devAddr.port);
173 if (clientResponse->result == OC_STACK_OK)
175 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
177 ocConnType = clientResponse->connType;
179 if (parseClientResponse(clientResponse) != -1)
183 case TEST_NON_CON_OP:
184 InitGetRequest(OC_LOW_QOS);
185 InitPutRequest(OC_LOW_QOS);
186 //InitPostRequest(OC_LOW_QOS);
189 InitGetRequest(OC_HIGH_QOS);
190 InitPutRequest(OC_HIGH_QOS);
191 //InitPostRequest(OC_HIGH_QOS);
198 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
202 int InitPutRequest(OCQualityOfService qos)
204 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
205 std::ostringstream query;
206 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
207 << ":" << coapServerPort << coapServerResource;
208 return (InvokeOCDoResource(query, OC_REST_PUT,
209 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
212 int InitPostRequest(OCQualityOfService qos)
214 OCStackResult result;
215 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
216 std::ostringstream query;
217 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
218 << ":" << coapServerPort << coapServerResource;
220 // First POST operation (to create an LED instance)
221 result = InvokeOCDoResource(query, OC_REST_POST,
222 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
224 if (OC_STACK_OK != result)
226 // Error can happen if for example, network connectivity is down
227 OC_LOG(INFO, TAG, "First POST call did not succeed");
230 // Second POST operation (to create an LED instance)
231 result = InvokeOCDoResource(query, OC_REST_POST,
232 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
234 if (OC_STACK_OK != result)
236 OC_LOG(INFO, TAG, "Second POST call did not succeed");
239 // This POST operation will update the original resourced /a/led
240 return (InvokeOCDoResource(query, OC_REST_POST,
241 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
242 postReqCB, NULL, 0));
245 int InitGetRequest(OCQualityOfService qos)
247 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
248 std::ostringstream query;
249 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
250 << ":" << coapServerPort << coapServerResource;
252 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
253 OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
260 OCCallbackData cbData;
261 char szQueryUri[MAX_URI_LENGTH] = { 0 };
263 if (UNICAST_DISCOVERY)
265 char ipv4addr[IPV4_ADDR_SIZE];
266 OC_LOG(INFO, TAG, "Enter IPv4 address:port of the Server hosting secure resource"\
267 "(Ex: 11.12.13.14:1234)\n");
268 if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
270 //Strip newline char from ipv4addr
271 StripNewLineChar(ipv4addr);
272 snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
276 OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
277 return OC_STACK_INVALID_PARAM;
279 method = OC_REST_GET;
283 //Send discovery request on Wifi and Ethernet interface
284 discoveryReqConnType = CT_DEFAULT;
285 strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
286 method = OC_REST_DISCOVER;
289 cbData.cb = discoveryReqCB;
290 cbData.context = NULL;
293 /* Start a discovery query*/
294 OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
295 (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
298 ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
299 discoveryReqConnType, OC_LOW_QOS,
301 if (ret != OC_STACK_OK)
303 OC_LOG(ERROR, TAG, "OCStack resource error");
308 FILE* client_fopen(const char *path, const char *mode)
311 return fopen(CRED_FILE, mode);
314 int main(int argc, char* argv[])
317 struct timespec timeout;
319 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
324 UNICAST_DISCOVERY = atoi(optarg);
327 TEST_CASE = atoi(optarg);
330 CONN_TYPE = atoi(optarg);
338 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
339 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS)||
340 (CONN_TYPE < CT_ADAPTER_DEFAULT || CONN_TYPE >= MAX_CT))
347 if(CONN_TYPE == CT_ADAPTER_DEFAULT || CONN_TYPE == CT_IP)
349 discoveryReqConnType = CT_DEFAULT;
353 OC_LOG(INFO, TAG, "Using Default Connectivity type");
358 // Initialize Persistent Storage for SVR database
359 OCPersistentStorage ps = {};
360 ps.open = client_fopen;
365 OCRegisterPersistentStorageHandler(&ps);
367 /* Initialize OCStack*/
368 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
370 OC_LOG(ERROR, TAG, "OCStack init error");
377 timeout.tv_nsec = 100000000L;
379 // Break from loop with Ctrl+C
380 OC_LOG(INFO, TAG, "Entering occlient main loop...");
381 signal(SIGINT, handleSigInt);
384 if (OCProcess() != OC_STACK_OK)
386 OC_LOG(ERROR, TAG, "OCStack process error");
390 nanosleep(&timeout, NULL);
392 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
394 if (OCStop() != OC_STACK_OK)
396 OC_LOG(ERROR, TAG, "OCStack stop error");
402 std::string getPortTBServer(OCClientResponse * clientResponse)
404 if(!clientResponse) return "";
405 std::ostringstream ss;
406 ss << clientResponse->devAddr.port;
410 int parseClientResponse(OCClientResponse * clientResponse)
412 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
414 // Initialize all global variables
415 coapServerResource.clear();
416 coapServerPort.clear();
417 coapServerIP.clear();
418 coapSecureResource = 0;
422 coapServerResource.assign(res->uri);
423 OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
427 coapSecureResource = 1;
430 OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
432 std::ostringstream ss;
434 coapServerPort = ss.str();
435 std::cout<<"PORT: "<<coapServerPort;
437 // If we discovered a secure resource, exit from here
438 if (coapSecureResource)
446 coapServerIP = clientResponse->devAddr.addr;
448 if(coapServerPort.length() == 0 || coapServerPort == "0")
450 coapServerPort = getPortTBServer(clientResponse);
451 OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());