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
10 // http://www.apache.org/licenses/LICENSE-2.0
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
18 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
34 #include "occlientbasicops.h"
36 static int UNICAST_DISCOVERY = 0;
37 static int TEST_CASE = 0;
39 static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
41 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
43 static std::string coapServerIP = "255.255.255.255";
44 static std::string coapServerPort = "5683";
45 static std::string coapServerResource = "/a/led";
48 //The following variable determines the interface (wifi, ethernet etc.)
49 //to be used for sending unicast messages. Default set to WIFI.
50 static OCConnectivityType CA_CONNTYPE = OC_WIFI;
51 static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oc/core";
57 typedef std::pair<bool, std::string> extract_result_t;
58 typedef std::string sid_t;
59 typedef std::set<std::string> SID_set_t;
62 void collateSIDs(const OCClientResponse * clientResponse, const std::string& server_ip);
64 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
65 void handleSigInt(int signum)
73 static void PrintUsage()
76 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
78 OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
80 OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
82 OC_LOG(INFO, TAG, "-c <0|1> : Send unicast messages over Ethernet or WIFI");
84 OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
85 OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
86 " Initiate Nonconfirmable Get/Put/Post Requests");
87 OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
90 OCStackResult InvokeOCDoResource(std::ostringstream &query,
91 OCMethod method, OCQualityOfService qos,
92 OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
95 OCCallbackData cbData;
99 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
103 ret = OCDoResource(&handle, method, query.str().c_str(), 0,
104 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
105 CA_CONNTYPE, qos, &cbData, options, numOptions);
107 ret = OCDoResource(&handle, method, query.str().c_str(), 0,
108 (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
109 qos, &cbData, options, numOptions);
112 if (ret != OC_STACK_OK)
114 OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
120 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
122 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
124 OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
129 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
130 OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
132 return OC_STACK_DELETE_TRANSACTION;
135 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
137 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
139 OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
144 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
145 OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
146 clientResponse->resJSONPayload);
148 return OC_STACK_DELETE_TRANSACTION;
151 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
153 if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
155 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
160 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
161 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
162 OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
163 clientResponse->resJSONPayload);
165 if(clientResponse->rcvdVendorSpecificHeaderOptions &&
166 clientResponse->numRcvdVendorSpecificHeaderOptions)
168 OC_LOG (INFO, TAG, "Received vendor specific options");
170 OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
171 for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
173 if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
175 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
176 ((OCHeaderOption)rcvdOptions[i]).optionID );
177 OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
178 ((OCHeaderOption)rcvdOptions[i]).optionLength);
182 return OC_STACK_DELETE_TRANSACTION;
185 // This is a function called back when a device is discovered
186 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
187 OCClientResponse * clientResponse)
189 uint8_t remoteIpAddr[4];
190 uint16_t remotePortNu;
192 if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
194 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
199 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
201 OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
202 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
203 OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
206 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
207 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
208 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
210 parseClientResponse(clientResponse);
212 collateSIDs(clientResponse, getIPAddrTBServer(clientResponse));
216 case TEST_NON_CON_OP:
217 InitGetRequest(OC_LOW_QOS);
219 InitPostRequest(OC_LOW_QOS);
222 InitGetRequest(OC_HIGH_QOS);
224 InitPostRequest(OC_HIGH_QOS);
232 return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
237 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
238 std::ostringstream query;
239 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
240 return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
243 int InitPostRequest(OCQualityOfService qos)
245 OCStackResult result;
246 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
247 std::ostringstream query;
248 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
250 // First POST operation (to create an LED instance)
251 result = InvokeOCDoResource(query, OC_REST_POST,
252 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
254 if (OC_STACK_OK != result)
256 // Error can happen if for example, network connectivity is down
257 OC_LOG(INFO, TAG, "First POST call did not succeed");
260 // Second POST operation (to create an LED instance)
261 result = InvokeOCDoResource(query, OC_REST_POST,
262 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
264 if (OC_STACK_OK != result)
266 OC_LOG(INFO, TAG, "Second POST call did not succeed");
269 // This POST operation will update the original resourced /a/led
270 return (InvokeOCDoResource(query, OC_REST_POST,
271 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
272 postReqCB, NULL, 0));
275 int InitGetRequest(OCQualityOfService qos)
277 OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
278 std::ostringstream query;
279 query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
281 return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
282 OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
288 OCCallbackData cbData;
290 /* Start a discovery query*/
291 char szQueryUri[64] = { 0 };
292 if (UNICAST_DISCOVERY)
294 strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
299 strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
301 strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
304 cbData.cb = discoveryReqCB;
305 cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
308 if (UNICAST_DISCOVERY)
310 ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, (CA_CONNTYPE),
311 OC_LOW_QOS, &cbData, NULL, 0);
315 ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
316 OC_LOW_QOS, &cbData, NULL, 0);
319 ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
321 if (ret != OC_STACK_OK)
323 OC_LOG(ERROR, TAG, "OCStack resource error");
328 int main(int argc, char* argv[])
330 uint8_t addr[20] = {0};
331 uint8_t* paddr = NULL;
332 uint16_t port = USE_RANDOM_PORT;
333 uint8_t ifname[] = "eth0";
337 while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
339 while ((opt = getopt(argc, argv, "u:t:")) != -1)
345 UNICAST_DISCOVERY = atoi(optarg);
348 TEST_CASE = atoi(optarg);
352 CA_CONNTYPE = OCConnectivityType(atoi(optarg));
361 if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
362 (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
369 /*Get Ip address on defined interface and initialize coap on it with random port number
370 * this port number will be used as a source port in all coap communications*/
371 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
372 sizeof(addr)) == ERR_SUCCESS)
374 OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
378 /* Initialize OCStack*/
379 if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK)
381 OC_LOG(ERROR, TAG, "OCStack init error");
387 // Break from loop with Ctrl+C
388 signal(SIGINT, handleSigInt);
392 if (OCProcess() != OC_STACK_OK)
394 OC_LOG(ERROR, TAG, "OCStack process error");
400 OC_LOG(INFO, TAG, "Exiting occlient main loop...");
402 if (OCStop() != OC_STACK_OK)
404 OC_LOG(ERROR, TAG, "OCStack stop error");
410 std::string getIPAddrTBServer(OCClientResponse * clientResponse)
412 if(!clientResponse) return "";
413 if(!clientResponse->addr) return "";
414 uint8_t a, b, c, d = 0;
415 if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
417 char ipaddr[16] = {'\0'};
418 // ostringstream not working correctly here, hence snprintf
419 snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
420 return std::string (ipaddr);
424 std::string getPortTBServer(OCClientResponse * clientResponse)
426 if(!clientResponse) return "";
427 if(!clientResponse->addr) return "";
429 if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
430 std::ostringstream ss;
435 std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
441 /* You could do this with the JSON parser of your choice, a regular expression, PEG
442 grammar, etc.. This "sample" version does not handle cases like escaping strings,
443 but shows a simple way you might approach the task with just the C++98 library: */
444 extract_result_t extract_value(const std::string& search_key, const std::string& input)
446 const std::string key('\"' + search_key + "\":\"");
448 const size_t key_mark = input.find(key);
449 const size_t key_edge = key_mark + key.length();
450 const size_t val_mark = input.find_first_of("\"", key_edge);
452 if(std::string::npos == key_mark || std::string::npos == val_mark) {
453 std::ostringstream os;
455 os << "extract_value(): \"" << search_key << "\" not found in input";
456 OC_LOG(ERROR, TAG, os.str().c_str());
458 return std::make_pair(false, "");
461 return std::make_pair(true, input.substr(key_edge, val_mark - key_edge));
464 extract_result_t parseSID(const OCClientResponse * const clientResponse)
466 const char* const& pl_in = reinterpret_cast<const char *>(clientResponse->resJSONPayload);
468 const std::string pl(pl_in, strlen(pl_in));
470 const extract_result_t sid = extract_value("sid", pl);
471 const extract_result_t uri = extract_value("href", pl);
472 //TODO-CA: It should be just enough to send the SID alone and not the combination
474 return std::make_pair(sid.first and uri.first, sid.second + ':' + uri.second);
477 void parseClientResponse(OCClientResponse * clientResponse)
479 coapServerIP = getIPAddrTBServer(clientResponse);
480 coapServerPort = getPortTBServer(clientResponse);
481 coapServerResource = getQueryStrForGetPut(clientResponse);
484 void collateSIDs(const OCClientResponse * clientResponse, const std::string& server_ip)
486 static SID_set_t sids;
488 const extract_result_t sid_result = parseSID(clientResponse);
490 if(false == sid_result.first)
493 const sid_t& sid = sid_result.second;
495 /* ...there's no need for an application to take any special action, but we can tell
496 if we've seen a resource before, regardless of the transport it arrive on: */
497 std::ostringstream msg;
499 if(not sids.insert(sid).second)
500 msg << "SID " << sid << " has been seen before.\n";
502 msg << "SID " << sid << " is new.\n";
504 OC_LOG(INFO, TAG, msg.str().c_str());