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_PAYLOAD(INFO, TAG, clientResponse->payload);
126 OC_LOG(INFO, TAG, PCF("=============> Put Response"));
128 return OC_STACK_DELETE_TRANSACTION;
131 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
133 OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
137 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
138 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
139 OC_LOG(INFO, TAG, PCF("=============> Post Response"));
141 return OC_STACK_DELETE_TRANSACTION;
144 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
146 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
150 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
151 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
152 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
153 OC_LOG(INFO, TAG, PCF("=============> Get Response"));
155 return OC_STACK_DELETE_TRANSACTION;
158 // This is a function called back when a device is discovered
159 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
160 OCClientResponse * clientResponse)
162 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
166 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
168 "Device =============> Discovered @ %s:%d",
169 clientResponse->devAddr.addr,
170 clientResponse->devAddr.port);
171 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
173 ocConnType = clientResponse->connType;
175 if (parseClientResponse(clientResponse) != -1)
179 case TEST_NON_CON_OP:
180 InitGetRequest(OC_LOW_QOS);
181 InitPutRequest(OC_LOW_QOS);
182 //InitPostRequest(OC_LOW_QOS);
185 InitGetRequest(OC_HIGH_QOS);
186 InitPutRequest(OC_HIGH_QOS);
187 //InitPostRequest(OC_HIGH_QOS);
193 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
197 int InitPutRequest(OCQualityOfService qos)
199 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
200 std::ostringstream query;
201 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
202 << ":" << coapServerPort << coapServerResource;
203 return (InvokeOCDoResource(query, OC_REST_PUT,
204 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
207 int InitPostRequest(OCQualityOfService qos)
209 OCStackResult result;
210 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
211 std::ostringstream query;
212 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
213 << ":" << coapServerPort << coapServerResource;
215 // First POST operation (to create an LED instance)
216 result = InvokeOCDoResource(query, OC_REST_POST,
217 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
219 if (OC_STACK_OK != result)
221 // Error can happen if for example, network connectivity is down
222 OC_LOG(INFO, TAG, "First POST call did not succeed");
225 // Second POST operation (to create an LED instance)
226 result = InvokeOCDoResource(query, OC_REST_POST,
227 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
229 if (OC_STACK_OK != result)
231 OC_LOG(INFO, TAG, "Second POST call did not succeed");
234 // This POST operation will update the original resourced /a/led
235 return (InvokeOCDoResource(query, OC_REST_POST,
236 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
237 postReqCB, NULL, 0));
240 int InitGetRequest(OCQualityOfService qos)
242 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
243 std::ostringstream query;
244 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
245 << ":" << coapServerPort << coapServerResource;
247 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
248 OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
255 OCCallbackData cbData;
256 char szQueryUri[MAX_URI_LENGTH] = { 0 };
258 if (UNICAST_DISCOVERY)
260 char ipv4addr[IPV4_ADDR_SIZE];
261 OC_LOG(INFO, TAG, "Enter IPv4 address:port of the Server hosting secure resource"\
262 "(Ex: 11.12.13.14:1234)\n");
263 if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
265 //Strip newline char from ipv4addr
266 StripNewLineChar(ipv4addr);
267 snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
271 OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
272 return OC_STACK_INVALID_PARAM;
274 method = OC_REST_GET;
278 //Send discovery request on Wifi and Ethernet interface
279 discoveryReqConnType = CT_DEFAULT;
280 strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
281 method = OC_REST_DISCOVER;
284 cbData.cb = discoveryReqCB;
285 cbData.context = NULL;
288 /* Start a discovery query*/
289 OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
290 (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
293 ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
294 discoveryReqConnType, OC_LOW_QOS,
296 if (ret != OC_STACK_OK)
298 OC_LOG(ERROR, TAG, "OCStack resource error");
303 FILE* client_fopen(const char *path, const char *mode)
306 return fopen(CRED_FILE, mode);
309 int main(int argc, char* argv[])
312 struct timespec timeout;
314 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
319 UNICAST_DISCOVERY = atoi(optarg);
322 TEST_CASE = atoi(optarg);
325 CONN_TYPE = atoi(optarg);
333 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
334 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS)||
335 (CONN_TYPE < CT_ADAPTER_DEFAULT || CONN_TYPE >= MAX_CT))
342 if(CONN_TYPE == CT_ADAPTER_DEFAULT || CONN_TYPE == CT_IP)
344 discoveryReqConnType = CT_DEFAULT;
348 OC_LOG(INFO, TAG, "Using Default Connectivity type");
353 // Initialize Persistent Storage for SVR database
354 OCPersistentStorage ps = {};
355 ps.open = client_fopen;
360 OCRegisterPersistentStorageHandler(&ps);
362 /* Initialize OCStack*/
363 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
365 OC_LOG(ERROR, TAG, "OCStack init error");
372 timeout.tv_nsec = 100000000L;
374 // Break from loop with Ctrl+C
375 OC_LOG(INFO, TAG, "Entering occlient main loop...");
376 signal(SIGINT, handleSigInt);
379 if (OCProcess() != OC_STACK_OK)
381 OC_LOG(ERROR, TAG, "OCStack process error");
385 nanosleep(&timeout, NULL);
387 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
389 if (OCStop() != OC_STACK_OK)
391 OC_LOG(ERROR, TAG, "OCStack stop error");
397 std::string getPortTBServer(OCClientResponse * clientResponse)
399 if(!clientResponse) return "";
400 std::ostringstream ss;
401 ss << clientResponse->devAddr.port;
405 int parseClientResponse(OCClientResponse * clientResponse)
407 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
409 // Initialize all global variables
410 coapServerResource.clear();
411 coapServerPort.clear();
412 coapServerIP.clear();
413 coapSecureResource = 0;
417 coapServerResource.assign(res->uri);
418 OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
422 coapSecureResource = 1;
425 OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
427 std::ostringstream ss;
429 coapServerPort = ss.str();
430 std::cout<<"PORT: "<<coapServerPort;
432 // If we discovered a secure resource, exit from here
433 if (coapSecureResource)
441 coapServerIP = clientResponse->devAddr.addr;
443 if(coapServerPort.length() == 0 || coapServerPort == "0")
445 coapServerPort = getPortTBServer(clientResponse);
446 OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());