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 "payload_logging.h"
33 #include "oic_string.h"
36 #define TAG "occlientbasicops"
37 static int UNICAST_DISCOVERY = 0;
38 static int TEST_CASE = 0;
39 static int CONN_TYPE = 0;
41 static int IPV4_ADDR_SIZE = 24;
42 static char UNICAST_DISCOVERY_QUERY[] = "coap://%s/oic/res";
43 static char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
44 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
46 static std::string coapServerIP;
47 static std::string coapServerPort;
48 static std::string coapServerResource;
49 static int coapSecureResource;
50 static OCConnectivityType ocConnType;
53 //Secure Virtual Resource database for Iotivity Client application
54 //It contains Client's Identity and the PSK credentials
55 //of other devices which the client trusts
56 static char CRED_FILE[] = "oic_svr_db_client.json";
61 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
62 void handleSigInt(int signum)
70 OCPayload* putPayload()
72 OCRepPayload* payload = OCRepPayloadCreate();
76 std::cout << "Failed to create put payload object"<<std::endl;
80 OCRepPayloadSetPropInt(payload, "power", 15);
81 OCRepPayloadSetPropBool(payload, "state", true);
83 return (OCPayload*) payload;
86 static void PrintUsage()
88 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
89 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
90 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
91 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
92 " Initiate Nonconfirmable Get/Put/Post Requests");
93 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
94 OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
95 OC_LOG(INFO, TAG, "-c 1 : IPv4 Connectivity Type");
98 OCStackResult InvokeOCDoResource(std::ostringstream &query,
99 OCMethod method, OCQualityOfService qos,
100 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
103 OCCallbackData cbData;
106 cbData.context = NULL;
109 ret = OCDoResource(NULL, method, query.str().c_str(), 0,
110 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
111 ocConnType, qos, &cbData, options, numOptions);
113 if (ret != OC_STACK_OK)
115 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
121 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
123 OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
127 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
128 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
129 OC_LOG(INFO, TAG, PCF("=============> Put Response"));
131 return OC_STACK_DELETE_TRANSACTION;
134 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
136 OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
140 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
141 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
142 OC_LOG(INFO, TAG, PCF("=============> Post Response"));
144 return OC_STACK_DELETE_TRANSACTION;
147 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
149 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
153 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
154 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
155 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
156 OC_LOG(INFO, TAG, PCF("=============> Get Response"));
158 return OC_STACK_DELETE_TRANSACTION;
161 // This is a function called back when a device is discovered
162 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
163 OCClientResponse * clientResponse)
165 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
169 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
171 "Device =============> Discovered @ %s:%d",
172 clientResponse->devAddr.addr,
173 clientResponse->devAddr.port);
175 if (clientResponse->result == OC_STACK_OK)
177 OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
179 ocConnType = clientResponse->connType;
181 if (parseClientResponse(clientResponse) != -1)
185 case TEST_NON_CON_OP:
186 InitGetRequest(OC_LOW_QOS);
187 InitPutRequest(OC_LOW_QOS);
188 //InitPostRequest(OC_LOW_QOS);
191 InitGetRequest(OC_HIGH_QOS);
192 InitPutRequest(OC_HIGH_QOS);
193 //InitPostRequest(OC_HIGH_QOS);
200 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
204 int InitPutRequest(OCQualityOfService qos)
206 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
207 std::ostringstream query;
208 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
209 << ":" << coapServerPort << coapServerResource;
210 return (InvokeOCDoResource(query, OC_REST_PUT,
211 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
214 int InitPostRequest(OCQualityOfService qos)
216 OCStackResult result;
217 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
218 std::ostringstream query;
219 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
220 << ":" << coapServerPort << coapServerResource;
222 // First POST operation (to create an LED instance)
223 result = InvokeOCDoResource(query, OC_REST_POST,
224 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
226 if (OC_STACK_OK != result)
228 // Error can happen if for example, network connectivity is down
229 OC_LOG(INFO, TAG, "First POST call did not succeed");
232 // Second POST operation (to create an LED instance)
233 result = InvokeOCDoResource(query, OC_REST_POST,
234 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
236 if (OC_STACK_OK != result)
238 OC_LOG(INFO, TAG, "Second POST call did not succeed");
241 // This POST operation will update the original resourced /a/led
242 return (InvokeOCDoResource(query, OC_REST_POST,
243 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
244 postReqCB, NULL, 0));
247 int InitGetRequest(OCQualityOfService qos)
249 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
250 std::ostringstream query;
251 query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
252 << ":" << coapServerPort << coapServerResource;
254 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
255 OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
262 OCCallbackData cbData;
263 char szQueryUri[MAX_URI_LENGTH] = { 0 };
265 if (UNICAST_DISCOVERY)
267 char ipv4addr[IPV4_ADDR_SIZE];
268 OC_LOG(INFO, TAG, "Enter IPv4 address:port of the Server hosting secure resource"\
269 "(Ex: 11.12.13.14:1234)\n");
270 if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
272 //Strip newline char from ipv4addr
273 StripNewLineChar(ipv4addr);
274 snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
278 OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
279 return OC_STACK_INVALID_PARAM;
281 method = OC_REST_GET;
285 //Send discovery request on Wifi and Ethernet interface
286 discoveryReqConnType = CT_DEFAULT;
287 OICStrcpy(szQueryUri, sizeof(szQueryUri), MULTICAST_DISCOVERY_QUERY);
288 method = OC_REST_DISCOVER;
291 cbData.cb = discoveryReqCB;
292 cbData.context = NULL;
295 /* Start a discovery query*/
296 OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
297 (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
300 ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
301 discoveryReqConnType, OC_LOW_QOS,
303 if (ret != OC_STACK_OK)
305 OC_LOG(ERROR, TAG, "OCStack resource error");
310 FILE* client_fopen(const char *path, const char *mode)
313 return fopen(CRED_FILE, mode);
316 int main(int argc, char* argv[])
319 struct timespec timeout;
321 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
326 UNICAST_DISCOVERY = atoi(optarg);
329 TEST_CASE = atoi(optarg);
332 CONN_TYPE = atoi(optarg);
340 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
341 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS)||
342 (CONN_TYPE < CT_ADAPTER_DEFAULT || CONN_TYPE >= MAX_CT))
349 if(CONN_TYPE == CT_ADAPTER_DEFAULT || CONN_TYPE == CT_IP)
351 discoveryReqConnType = CT_DEFAULT;
355 OC_LOG(INFO, TAG, "Using Default Connectivity type");
360 // Initialize Persistent Storage for SVR database
361 OCPersistentStorage ps = {};
362 ps.open = client_fopen;
367 OCRegisterPersistentStorageHandler(&ps);
369 /* Initialize OCStack*/
370 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
372 OC_LOG(ERROR, TAG, "OCStack init error");
379 timeout.tv_nsec = 100000000L;
381 // Break from loop with Ctrl+C
382 OC_LOG(INFO, TAG, "Entering occlient main loop...");
383 signal(SIGINT, handleSigInt);
386 if (OCProcess() != OC_STACK_OK)
388 OC_LOG(ERROR, TAG, "OCStack process error");
392 nanosleep(&timeout, NULL);
394 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
396 if (OCStop() != OC_STACK_OK)
398 OC_LOG(ERROR, TAG, "OCStack stop error");
404 std::string getPortTBServer(OCClientResponse * clientResponse)
406 if(!clientResponse) return "";
407 std::ostringstream ss;
408 ss << clientResponse->devAddr.port;
412 int parseClientResponse(OCClientResponse * clientResponse)
414 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
416 // Initialize all global variables
417 coapServerResource.clear();
418 coapServerPort.clear();
419 coapServerIP.clear();
420 coapSecureResource = 0;
424 coapServerResource.assign(res->uri);
425 OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
429 coapSecureResource = 1;
432 OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
434 std::ostringstream ss;
436 coapServerPort = ss.str();
437 std::cout<<"PORT: "<<coapServerPort;
439 // If we discovered a secure resource, exit from here
440 if (coapSecureResource)
448 coapServerIP = clientResponse->devAddr.addr;
450 if(coapServerPort.length() == 0 || coapServerPort == "0")
452 coapServerPort = getPortTBServer(clientResponse);
453 OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());