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 UnicastDiscovery = 0;
38 static int TestCase = 0;
39 static int ConnType = 0;
41 static char DISCOVERY_QUERY[] = "%s/oic/res";
42 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
43 static OCDevAddr endpoint;
45 static std::string coapServerResource;
46 static int coapSecureResource;
47 static OCConnectivityType ocConnType;
49 //Secure Virtual Resource database for Iotivity Client application
50 //It contains Client's Identity and the PSK credentials
51 //of other devices which the client trusts
52 static char CRED_FILE[] = "oic_svr_db_client.json";
57 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
58 void handleSigInt(int signum)
66 OCPayload* putPayload()
68 OCRepPayload* payload = OCRepPayloadCreate();
72 std::cout << "Failed to create put payload object"<<std::endl;
76 OCRepPayloadSetPropInt(payload, "power", 15);
77 OCRepPayloadSetPropBool(payload, "state", true);
79 return (OCPayload*) payload;
82 static void PrintUsage()
84 OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
85 OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
86 OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
87 OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
88 " Initiate Nonconfirmable Get/Put/Post Requests");
89 OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
90 OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
91 OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
94 OCStackResult InvokeOCDoResource(std::ostringstream &query,
96 const OCDevAddr *dest,
97 OCQualityOfService qos,
98 OCClientResponseHandler cb,
99 OCHeaderOption * options, uint8_t numOptions)
102 OCCallbackData cbData;
105 cbData.context = NULL;
108 ret = OCDoResource(NULL, method, query.str().c_str(), dest,
109 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
110 ocConnType, qos, &cbData, options, numOptions);
112 if (ret != OC_STACK_OK)
114 OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
120 OCStackApplicationResult putReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
122 OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
126 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
127 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
128 OIC_LOG(INFO, TAG, ("=============> Put Response"));
130 return OC_STACK_DELETE_TRANSACTION;
133 OCStackApplicationResult postReqCB(void *, OCDoHandle, OCClientResponse *clientResponse)
135 OIC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
139 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
140 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
141 OIC_LOG(INFO, TAG, ("=============> Post Response"));
143 return OC_STACK_DELETE_TRANSACTION;
146 OCStackApplicationResult getReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
148 OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
152 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
153 OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
154 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
155 OIC_LOG(INFO, TAG, ("=============> Get Response"));
157 return OC_STACK_DELETE_TRANSACTION;
160 // This is a function called back when a device is discovered
161 OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
162 OCClientResponse * clientResponse)
164 OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
168 OIC_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 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
178 ocConnType = clientResponse->connType;
179 endpoint = clientResponse->devAddr;
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 (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
204 int InitPutRequest(OCQualityOfService qos)
206 OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
207 std::ostringstream query;
208 query << coapServerResource;
209 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
210 return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
211 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
214 int InitPostRequest(OCQualityOfService qos)
216 OCStackResult result;
217 OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
218 std::ostringstream query;
219 query << coapServerResource;
220 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
222 // First POST operation (to create an LED instance)
223 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
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 OIC_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, &endpoint,
234 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
236 if (OC_STACK_OK != result)
238 OIC_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, &endpoint,
243 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
244 postReqCB, NULL, 0));
247 int InitGetRequest(OCQualityOfService qos)
249 OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
250 std::ostringstream query;
251 query << coapServerResource;
252 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
254 return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
255 ((qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS),
262 OCCallbackData cbData;
264 char ipaddr[100] = { '\0' };
266 if (UnicastDiscovery)
268 OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
269 OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
270 OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
272 if (fgets(ipaddr, sizeof (ipaddr), stdin))
274 StripNewLineChar(ipaddr); //Strip newline char from ipaddr
278 OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
279 return OC_STACK_INVALID_PARAM;
282 snprintf(queryUri, sizeof (queryUri), DISCOVERY_QUERY, ipaddr);
284 cbData.cb = discoveryReqCB;
285 cbData.context = NULL;
288 /* Start a discovery query*/
289 OIC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
290 (UnicastDiscovery) ? "Unicast" : "Multicast",
293 ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
294 OC_LOW_QOS, &cbData, NULL, 0);
295 if (ret != OC_STACK_OK)
297 OIC_LOG(ERROR, TAG, "OCStack resource error");
302 FILE* client_fopen(const char *path, const char *mode)
305 return fopen(CRED_FILE, mode);
308 int main(int argc, char* argv[])
311 struct timespec timeout;
313 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
318 UnicastDiscovery = atoi(optarg);
321 TestCase = atoi(optarg);
324 ConnType = atoi(optarg);
332 if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
333 (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS)||
334 (ConnType < CT_ADAPTER_DEFAULT || ConnType >= MAX_CT))
341 if(ConnType == CT_ADAPTER_DEFAULT || ConnType == CT_IP)
343 discoveryReqConnType = CT_DEFAULT;
347 OIC_LOG(INFO, TAG, "Using Default Connectivity type");
352 // Initialize Persistent Storage for SVR database
353 OCPersistentStorage ps = { client_fopen, fread, fwrite, fclose, unlink };
354 OCRegisterPersistentStorageHandler(&ps);
356 /* Initialize OCStack*/
357 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
359 OIC_LOG(ERROR, TAG, "OCStack init error");
366 timeout.tv_nsec = 100000000L;
368 // Break from loop with Ctrl+C
369 OIC_LOG(INFO, TAG, "Entering occlient main loop...");
370 signal(SIGINT, handleSigInt);
373 if (OCProcess() != OC_STACK_OK)
375 OIC_LOG(ERROR, TAG, "OCStack process error");
379 nanosleep(&timeout, NULL);
381 OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
383 if (OCStop() != OC_STACK_OK)
385 OIC_LOG(ERROR, TAG, "OCStack stop error");
391 int parseClientResponse(OCClientResponse * clientResponse)
393 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
395 // Initialize all global variables
396 coapServerResource.clear();
397 coapSecureResource = 0;
401 coapServerResource.assign(res->uri);
402 OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
406 endpoint.port = res->port;
407 coapSecureResource = 1;
410 OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
412 // If we discovered a secure resource, exit from here
413 if (coapSecureResource)