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"
32 #define TAG "occlientbasicops"
33 static int UNICAST_DISCOVERY = 0;
34 static int TEST_CASE = 0;
35 static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
36 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
37 static std::string coapServerIP = "255.255.255.255";
38 static std::string coapServerPort = "5683";
39 static std::string coapServerResource = "/a/led";
43 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
44 void handleSigInt(int signum)
52 static void PrintUsage()
54 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
55 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
56 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
57 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
58 " Initiate Nonconfirmable Get/Put/Post Requests");
59 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
62 OCStackResult InvokeOCDoResource(std::ostringstream &query,
63 OCMethod method, OCQualityOfService qos,
64 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
67 OCCallbackData cbData;
71 cbData.context = NULL;
74 ret = OCDoResource(&handle, method, query.str().c_str(), 0,
75 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
76 qos, &cbData, options, numOptions);
78 if (ret != OC_STACK_OK)
80 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
86 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
88 OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
92 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
93 OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
95 return OC_STACK_DELETE_TRANSACTION;
98 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
100 OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
104 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
105 OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
106 clientResponse->resJSONPayload);
108 return OC_STACK_DELETE_TRANSACTION;
111 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
113 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
117 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
118 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
119 OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
120 clientResponse->resJSONPayload);
122 if(clientResponse->rcvdVendorSpecificHeaderOptions &&
123 clientResponse->numRcvdVendorSpecificHeaderOptions)
125 OC_LOG (INFO, TAG, "Received vendor specific options");
127 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
128 for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
130 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
132 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
133 ((OCHeaderOption)rcvdOptions[i]).optionID );
134 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
135 ((OCHeaderOption)rcvdOptions[i]).optionLength);
139 return OC_STACK_DELETE_TRANSACTION;
142 // This is a function called back when a device is discovered
143 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
144 OCClientResponse * clientResponse)
146 uint8_t remoteIpAddr[4];
147 uint16_t remotePortNu;
149 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
153 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
155 OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
156 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
157 OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
160 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
161 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
162 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
164 parseClientResponse(clientResponse);
168 case TEST_NON_CON_OP:
169 InitGetRequest(OC_LOW_QOS);
171 //InitPostRequest(OC_LOW_QOS);
174 InitGetRequest(OC_HIGH_QOS);
176 //InitPostRequest(OC_HIGH_QOS);
181 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
187 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
188 std::ostringstream query;
189 query << "coaps://" << coapServerIP << ":" << "5684" << coapServerResource;
190 return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
193 int InitPostRequest(OCQualityOfService qos)
195 OCStackResult result;
196 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
197 std::ostringstream query;
198 query << "coaps://" << coapServerIP << ":" << "5684" << coapServerResource;
200 // First POST operation (to create an LED instance)
201 result = InvokeOCDoResource(query, OC_REST_POST,
202 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
204 if (OC_STACK_OK != result)
206 // Error can happen if for example, network connectivity is down
207 OC_LOG(INFO, TAG, "First POST call did not succeed");
210 // Second POST operation (to create an LED instance)
211 result = InvokeOCDoResource(query, OC_REST_POST,
212 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
214 if (OC_STACK_OK != result)
216 OC_LOG(INFO, TAG, "Second POST call did not succeed");
219 // This POST operation will update the original resourced /a/led
220 return (InvokeOCDoResource(query, OC_REST_POST,
221 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
222 postReqCB, NULL, 0));
225 int InitGetRequest(OCQualityOfService qos)
227 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
228 std::ostringstream query;
229 query << "coaps://" << coapServerIP << ":" << "5684" << coapServerResource;
231 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
232 OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
238 OCCallbackData cbData;
240 /* Start a discovery query*/
241 char szQueryUri[64] = { 0 };
242 if (UNICAST_DISCOVERY)
244 strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
248 strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
250 cbData.cb = discoveryReqCB;
251 cbData.context = NULL;
253 ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
254 if (ret != OC_STACK_OK)
256 OC_LOG(ERROR, TAG, "OCStack resource error");
261 int main(int argc, char* argv[])
263 uint8_t addr[20] = {0};
264 uint8_t* paddr = NULL;
265 uint16_t port = USE_RANDOM_PORT;
266 uint8_t ifname[] = "eth0";
268 struct timespec timeout;
270 while ((opt = getopt(argc, argv, "u:t:")) != -1)
275 UNICAST_DISCOVERY = atoi(optarg);
278 TEST_CASE = atoi(optarg);
286 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
287 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
294 /*Get Ip address on defined interface and initialize coap on it with random port number
295 * this port number will be used as a source port in all coap communications*/
296 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
297 sizeof(addr)) == ERR_SUCCESS)
299 OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
303 /* Initialize OCStack*/
304 if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK)
306 OC_LOG(ERROR, TAG, "OCStack init error");
313 timeout.tv_nsec = 100000000L;
315 // Break from loop with Ctrl+C
316 OC_LOG(INFO, TAG, "Entering occlient main loop...");
317 signal(SIGINT, handleSigInt);
320 if (OCProcess() != OC_STACK_OK)
322 OC_LOG(ERROR, TAG, "OCStack process error");
326 nanosleep(&timeout, NULL);
329 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
331 if (OCStop() != OC_STACK_OK)
333 OC_LOG(ERROR, TAG, "OCStack stop error");
339 std::string getIPAddrTBServer(OCClientResponse * clientResponse)
341 if(!clientResponse) return "";
342 if(!clientResponse->addr) return "";
343 uint8_t a, b, c, d = 0;
344 if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
346 char ipaddr[16] = {'\0'};
347 // ostringstream not working correctly here, hence snprintf
348 snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
349 return std::string (ipaddr);
353 std::string getPortTBServer(OCClientResponse * clientResponse)
355 if(!clientResponse) return "";
356 if(!clientResponse->addr) return "";
358 if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
359 std::ostringstream ss;
364 std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
369 void parseClientResponse(OCClientResponse * clientResponse)
371 coapServerIP = getIPAddrTBServer(clientResponse);
372 coapServerPort = getPortTBServer(clientResponse);
373 coapServerResource = getQueryStrForGetPut(clientResponse);