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 /** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
38 #include "platform_features.h"
41 #include "occlientbasicops.h"
42 #include "ocpayload.h"
43 #include "payload_logging.h"
44 #include "oic_string.h"
47 #define TAG "occlientbasicops"
48 static int UnicastDiscovery = 0;
49 static int TestCase = 0;
50 static int ConnType = 0;
51 static int DevOwner = 0;
53 static char DISCOVERY_QUERY[] = "%s/oic/res";
54 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
55 static OCDevAddr endpoint;
57 static std::string coapServerResource;
58 static int coapSecureResource;
59 static OCConnectivityType ocConnType;
61 //Secure Virtual Resource database for Iotivity Client application
62 //It contains Client's Identity and the PSK credentials
63 //of other devices which the client trusts
64 static char CRED_FILE_DEVOWNER[] = "oic_svr_db_client_devowner.dat";
65 static char CRED_FILE_NONDEVOWNER[] = "oic_svr_db_client_nondevowner.dat";
70 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
71 void handleSigInt(int signum)
79 OCPayload* putPayload()
81 OCRepPayload* payload = OCRepPayloadCreate();
85 std::cout << "Failed to create put payload object"<<std::endl;
89 OCRepPayloadSetPropInt(payload, "power", 15);
90 OCRepPayloadSetPropBool(payload, "state", true);
92 return (OCPayload*) payload;
95 static void PrintUsage()
97 OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
98 OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
99 OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
100 OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
101 " Initiate Nonconfirmable Get/Put/Post Requests");
102 OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
103 OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
104 OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
105 OIC_LOG(INFO, TAG, "-d 0 : Client as Device Owner");
106 OIC_LOG(INFO, TAG, "-d 1 : Client as Non Device Owner");
109 OCStackResult InvokeOCDoResource(std::ostringstream &query,
111 const OCDevAddr *dest,
112 OCQualityOfService qos,
113 OCClientResponseHandler cb,
114 OCHeaderOption * options, uint8_t numOptions)
117 OCCallbackData cbData;
120 cbData.context = NULL;
123 ret = OCDoResource(NULL, method, query.str().c_str(), dest,
124 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
125 ocConnType, qos, &cbData, options, numOptions);
127 if (ret != OC_STACK_OK)
129 OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
135 OCStackApplicationResult putReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
137 OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
141 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
142 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
143 OIC_LOG(INFO, TAG, ("=============> Put Response"));
145 return OC_STACK_DELETE_TRANSACTION;
148 OCStackApplicationResult postReqCB(void *, OCDoHandle, OCClientResponse *clientResponse)
150 OIC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
154 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
155 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
156 OIC_LOG(INFO, TAG, ("=============> Post Response"));
158 return OC_STACK_DELETE_TRANSACTION;
161 OCStackApplicationResult getReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
163 OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
167 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
168 OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
169 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
170 OIC_LOG(INFO, TAG, ("=============> Get Response"));
172 return OC_STACK_DELETE_TRANSACTION;
175 // This is a function called back when a device is discovered
176 OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
177 OCClientResponse * clientResponse)
179 OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
183 OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
185 "Device =============> Discovered @ %s:%d",
186 clientResponse->devAddr.addr,
187 clientResponse->devAddr.port);
189 if (clientResponse->result == OC_STACK_OK)
191 OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
193 ocConnType = clientResponse->connType;
194 endpoint = clientResponse->devAddr;
196 if (parseClientResponse(clientResponse) != -1)
200 case TEST_NON_CON_OP:
201 InitGetRequest(OC_LOW_QOS);
202 InitPutRequest(OC_LOW_QOS);
203 //InitPostRequest(OC_LOW_QOS);
206 InitGetRequest(OC_HIGH_QOS);
207 InitPutRequest(OC_HIGH_QOS);
208 //InitPostRequest(OC_HIGH_QOS);
215 return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
219 int InitPutRequest(OCQualityOfService qos)
221 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
222 std::ostringstream query;
223 query << coapServerResource;
224 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
225 return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
226 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
229 int InitPostRequest(OCQualityOfService qos)
231 OCStackResult result;
233 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
234 std::ostringstream query;
235 query << coapServerResource;
236 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
238 // First POST operation (to create an LED instance)
239 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
240 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
242 if (OC_STACK_OK != result)
244 // Error can happen if for example, network connectivity is down
245 OIC_LOG(INFO, TAG, "First POST call did not succeed");
248 // Second POST operation (to create an LED instance)
249 result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
250 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
252 if (OC_STACK_OK != result)
254 OIC_LOG(INFO, TAG, "Second POST call did not succeed");
257 // This POST operation will update the original resourced /a/led
258 return (InvokeOCDoResource(query, OC_REST_POST, &endpoint,
259 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
260 postReqCB, NULL, 0));
263 int InitGetRequest(OCQualityOfService qos)
265 OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
266 std::ostringstream query;
267 query << coapServerResource;
268 endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
270 return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
271 ((qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS),
278 OCCallbackData cbData;
280 char ipaddr[100] = { '\0' };
282 if (UnicastDiscovery)
284 OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
285 OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
286 OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
288 if (fgets(ipaddr, sizeof (ipaddr), stdin))
290 StripNewLineChar(ipaddr); //Strip newline char from ipaddr
294 OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
295 return OC_STACK_INVALID_PARAM;
298 snprintf(queryUri, sizeof (queryUri), DISCOVERY_QUERY, ipaddr);
300 cbData.cb = discoveryReqCB;
301 cbData.context = NULL;
304 /* Start a discovery query*/
305 OIC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
306 (UnicastDiscovery) ? "Unicast" : "Multicast",
309 ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
310 OC_LOW_QOS, &cbData, NULL, 0);
311 if (ret != OC_STACK_OK)
313 OIC_LOG(ERROR, TAG, "OCStack resource error");
318 FILE* client_fopen_devowner(const char *path, const char *mode)
321 return fopen(CRED_FILE_DEVOWNER, mode);
324 FILE* client_fopen_nondevowner(const char *path, const char *mode)
327 return fopen(CRED_FILE_NONDEVOWNER, mode);
329 int main(int argc, char* argv[])
332 struct timespec timeout;
333 OCPersistentStorage ps;
335 while ((opt = getopt(argc, argv, "u:t:c:d:")) != -1)
340 UnicastDiscovery = atoi(optarg);
343 TestCase = atoi(optarg);
346 ConnType = atoi(optarg);
349 DevOwner = atoi(optarg);
357 if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
358 (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS)||
359 (ConnType < CT_ADAPTER_DEFAULT || ConnType >= MAX_CT))
366 if(ConnType == CT_ADAPTER_DEFAULT || ConnType == CT_IP)
368 discoveryReqConnType = CT_DEFAULT;
372 OIC_LOG(INFO, TAG, "Using Default Connectivity type");
377 // Initialize Persistent Storage for SVR database
379 ps = { client_fopen_devowner, fread, fwrite, fclose, unlink };
381 ps = { client_fopen_nondevowner, fread, fwrite, fclose, unlink };
382 OCRegisterPersistentStorageHandler(&ps);
384 /* Initialize OCStack*/
385 if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
387 OIC_LOG(ERROR, TAG, "OCStack init error");
394 timeout.tv_nsec = 100000000L;
396 // Break from loop with Ctrl+C
397 OIC_LOG(INFO, TAG, "Entering occlient main loop...");
398 signal(SIGINT, handleSigInt);
401 if (OCProcess() != OC_STACK_OK)
403 OIC_LOG(ERROR, TAG, "OCStack process error");
407 nanosleep(&timeout, NULL);
409 OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
411 if (OCStop() != OC_STACK_OK)
413 OIC_LOG(ERROR, TAG, "OCStack stop error");
419 int parseClientResponse(OCClientResponse * clientResponse)
421 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
423 // Initialize all global variables
424 coapServerResource.clear();
425 coapSecureResource = 0;
429 coapServerResource.assign(res->uri);
430 OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
434 endpoint.port = res->port;
435 coapSecureResource = 1;
438 OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
440 // If we discovered a secure resource, exit from here
441 if (coapSecureResource)