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"
32 #include "oic_string.h"
35 #define TAG "occlientbasicops"
36 static int UNICAST_DISCOVERY = 0;
37 static int TEST_CASE = 0;
38 static int CONN_TYPE = 0;
40 static int IPV4_ADDR_SIZE = 24;
41 static char UNICAST_DISCOVERY_QUERY[] = "coap://%s/oic/res";
42 static char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
43 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
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 OCPayload* putPayload()
71 OCRepPayload* payload = OCRepPayloadCreate();
75 std::cout << "Failed to create put payload object"<<std::endl;
79 OCRepPayloadSetPropInt(payload, "power", 15);
80 OCRepPayloadSetPropBool(payload, "state", true);
82 return (OCPayload*) payload;
85 static void PrintUsage()
87 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
88 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
89 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
90 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
91 " Initiate Nonconfirmable Get/Put/Post Requests");
92 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
93 OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
94 OC_LOG(INFO, TAG, "-c 1 : IPv4 Connectivity Type");
97 OCStackResult InvokeOCDoResource(std::ostringstream &query,
98 OCMethod method, OCQualityOfService qos,
99 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
102 OCCallbackData cbData;
105 cbData.context = NULL;
108 ret = OCDoResource(NULL, method, query.str().c_str(), 0,
109 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
110 ocConnType, qos, &cbData, options, numOptions);
112 if (ret != OC_STACK_OK)
114 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
120 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
122 OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
126 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
127 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
128 OC_LOG(INFO, TAG, PCF("=============> Put Response"));
130 return OC_STACK_DELETE_TRANSACTION;
133 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
135 OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
139 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
140 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
141 OC_LOG(INFO, TAG, PCF("=============> Post Response"));
143 return OC_STACK_DELETE_TRANSACTION;
146 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
148 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
152 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
153 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
154 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
155 OC_LOG(INFO, TAG, PCF("=============> Get Response"));
157 return OC_STACK_DELETE_TRANSACTION;
160 // This is a function called back when a device is discovered
161 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
162 OCClientResponse * clientResponse)
164 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
168 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
170 "Device =============> Discovered @ %s:%d",
171 clientResponse->devAddr.addr,
172 clientResponse->devAddr.port);
174 if (clientResponse->result == OC_STACK_OK)
176 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
178 ocConnType = clientResponse->connType;
180 if (parseClientResponse(clientResponse) != -1)
184 case TEST_NON_CON_OP:
185 InitGetRequest(OC_LOW_QOS);
186 InitPutRequest(OC_LOW_QOS);
187 //InitPostRequest(OC_LOW_QOS);
190 InitGetRequest(OC_HIGH_QOS);
191 InitPutRequest(OC_HIGH_QOS);
192 //InitPostRequest(OC_HIGH_QOS);
199 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
203 int InitPutRequest(OCQualityOfService qos)
205 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
206 std::ostringstream query;
207 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
208 << ":" << coapServerPort << coapServerResource;
209 return (InvokeOCDoResource(query, OC_REST_PUT,
210 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
213 int InitPostRequest(OCQualityOfService qos)
215 OCStackResult result;
216 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
217 std::ostringstream query;
218 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
219 << ":" << coapServerPort << coapServerResource;
221 // First POST operation (to create an LED instance)
222 result = InvokeOCDoResource(query, OC_REST_POST,
223 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
225 if (OC_STACK_OK != result)
227 // Error can happen if for example, network connectivity is down
228 OC_LOG(INFO, TAG, "First POST call did not succeed");
231 // Second POST operation (to create an LED instance)
232 result = InvokeOCDoResource(query, OC_REST_POST,
233 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
235 if (OC_STACK_OK != result)
237 OC_LOG(INFO, TAG, "Second POST call did not succeed");
240 // This POST operation will update the original resourced /a/led
241 return (InvokeOCDoResource(query, OC_REST_POST,
242 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
243 postReqCB, NULL, 0));
246 int InitGetRequest(OCQualityOfService qos)
248 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
249 std::ostringstream query;
250 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
251 << ":" << coapServerPort << coapServerResource;
253 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
254 OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
261 OCCallbackData cbData;
262 char szQueryUri[MAX_URI_LENGTH] = { 0 };
264 if (UNICAST_DISCOVERY)
266 char ipv4addr[IPV4_ADDR_SIZE];
267 OC_LOG(INFO, TAG, "Enter IPv4 address:port of the Server hosting secure resource"\
268 "(Ex: 11.12.13.14:1234)\n");
269 if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
271 //Strip newline char from ipv4addr
272 StripNewLineChar(ipv4addr);
273 snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
277 OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
278 return OC_STACK_INVALID_PARAM;
280 method = OC_REST_GET;
284 //Send discovery request on Wifi and Ethernet interface
285 discoveryReqConnType = CT_DEFAULT;
286 OICStrcpy(szQueryUri, sizeof(szQueryUri), MULTICAST_DISCOVERY_QUERY);
287 method = OC_REST_DISCOVER;
290 cbData.cb = discoveryReqCB;
291 cbData.context = NULL;
294 /* Start a discovery query*/
295 OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
296 (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
299 ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
300 discoveryReqConnType, OC_LOW_QOS,
302 if (ret != OC_STACK_OK)
304 OC_LOG(ERROR, TAG, "OCStack resource error");
309 FILE* client_fopen(const char *path, const char *mode)
312 return fopen(CRED_FILE, mode);
315 int main(int argc, char* argv[])
318 struct timespec timeout;
320 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
325 UNICAST_DISCOVERY = atoi(optarg);
328 TEST_CASE = atoi(optarg);
331 CONN_TYPE = atoi(optarg);
339 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
340 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS)||
341 (CONN_TYPE < CT_ADAPTER_DEFAULT || CONN_TYPE >= MAX_CT))
348 if(CONN_TYPE == CT_ADAPTER_DEFAULT || CONN_TYPE == CT_IP)
350 discoveryReqConnType = CT_DEFAULT;
354 OC_LOG(INFO, TAG, "Using Default Connectivity type");
359 // Initialize Persistent Storage for SVR database
360 OCPersistentStorage ps = {};
361 ps.open = client_fopen;
366 OCRegisterPersistentStorageHandler(&ps);
368 /* Initialize OCStack*/
369 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
371 OC_LOG(ERROR, TAG, "OCStack init error");
378 timeout.tv_nsec = 100000000L;
380 // Break from loop with Ctrl+C
381 OC_LOG(INFO, TAG, "Entering occlient main loop...");
382 signal(SIGINT, handleSigInt);
385 if (OCProcess() != OC_STACK_OK)
387 OC_LOG(ERROR, TAG, "OCStack process error");
391 nanosleep(&timeout, NULL);
393 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
395 if (OCStop() != OC_STACK_OK)
397 OC_LOG(ERROR, TAG, "OCStack stop error");
403 std::string getPortTBServer(OCClientResponse * clientResponse)
405 if(!clientResponse) return "";
406 std::ostringstream ss;
407 ss << clientResponse->devAddr.port;
411 int parseClientResponse(OCClientResponse * clientResponse)
413 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
415 // Initialize all global variables
416 coapServerResource.clear();
417 coapServerPort.clear();
418 coapServerIP.clear();
419 coapSecureResource = 0;
423 coapServerResource.assign(res->uri);
424 OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
428 coapSecureResource = 1;
431 OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
433 std::ostringstream ss;
435 coapServerPort = ss.str();
436 std::cout<<"PORT: "<<coapServerPort;
438 // If we discovered a secure resource, exit from here
439 if (coapSecureResource)
447 coapServerIP = clientResponse->devAddr.addr;
449 if(coapServerPort.length() == 0 || coapServerPort == "0")
451 coapServerPort = getPortTBServer(clientResponse);
452 OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());