1 //******************************************************************
3 // Copyright 2015 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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
33 #include "cainterface.h"
35 #include "payload_logging.h"
36 #include "ocpayload.h"
40 #define DEFAULT_CONTEXT_VALUE 0x99
42 #define OPEN_DURATION "openDuration"
43 #define OPEN_ALARM "openAlarm"
45 static const char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
47 volatile sig_atomic_t gQuitFlag = 0;
48 OCPersistentStorage ps = {0, 0, 0, 0, 0};
49 static const char *gResourceUri = "/a/door";
50 uint8_t lightIpAddr[4] = {};
52 static bool isUpdated = false;
53 static std::string coapServerIP;
54 static std::string coapServerPort;
55 static std::string coapServerResource;
56 static OCConnectivityType ocConnType;
58 static std::string address;
60 static int coapSecureResource;
62 static const char CRED_FILE[] = "oic_svr_db_door.json";
64 CAEndpoint_t endpoint = {CA_DEFAULT_ADAPTER, CA_DEFAULT_FLAGS, 0, {0}, 0};
66 // myDoorState_t variable to store resource's state .
69 STATE_OPEN, /**< State is opened */
70 STATE_CLOSED /**< State is closed*/
73 //Structure to represent a door resource and its attributes
74 typedef struct DOORRESOURCE
76 OCResourceHandle handle;
77 myDoorState_t state; //ReadOnly, The state of the door (open or closed)"
78 char *openDuration; //ReadOnly, The time duration the door has been open
79 bool openAlarm ; //The state of the door open alarm
83 static DoorResource Door;
85 int parseClientResponse(OCClientResponse * clientResponse)
92 OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
94 // Initialize all global variables
95 coapServerResource.clear();
96 coapSecureResource = 0;
100 coapServerResource.assign(res->uri);
101 OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
105 endpoint.port = res->port;
106 coapSecureResource = 1;
109 OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
111 // If we discovered a secure resource, exit from here
112 if (coapSecureResource)
123 OCRepPayload* getPayload(const char* uri, int64_t state, char* openDuration, bool openAlarm)
125 OCRepPayload* payload = OCRepPayloadCreate();
128 OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
132 OCRepPayloadSetUri(payload, uri);
133 OCRepPayloadSetPropInt(payload, STATE, state);
134 OCRepPayloadSetPropString(payload, OPEN_DURATION, openDuration);
135 OCRepPayloadSetPropBool(payload, OPEN_ALARM, openAlarm);
140 //This function takes the request as an input and returns the response
141 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
143 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
145 OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
149 DoorResource *currdoorResource = &Door;
151 return getPayload(gResourceUri, currdoorResource->state, currdoorResource->openDuration, currdoorResource->openAlarm);
154 OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest,
155 OCRepPayload **payload)
157 OCEntityHandlerResult ehResult = OC_EH_ERROR;
159 OCRepPayload *getResp = constructResponse(ehRequest);
170 OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
171 OCEntityHandlerRequest *entityHandlerRequest,
172 void* /*callbackParam*/)
174 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
176 OCEntityHandlerResult ehResult = OC_EH_ERROR;
177 OCEntityHandlerResponse response;
180 if (!entityHandlerRequest)
182 OC_LOG (ERROR, TAG, "Invalid request pointer");
186 OCRepPayload* payload = nullptr;
188 if (flag & OC_REQUEST_FLAG)
190 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
192 if (entityHandlerRequest)
194 switch(entityHandlerRequest->method)
198 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
199 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
204 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
205 entityHandlerRequest->method);
206 ehResult = OC_EH_ERROR;
211 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
213 // Format the response. Note this requires some info about the request
214 response.requestHandle = entityHandlerRequest->requestHandle;
215 response.resourceHandle = entityHandlerRequest->resource;
216 response.ehResult = ehResult;
217 response.payload = reinterpret_cast<OCPayload*>(payload);
218 response.numSendVendorSpecificHeaderOptions = 0;
219 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
220 memset(response.resourceUri, 0, sizeof(response.resourceUri));
221 // Indicate that response is NOT in a persistent buffer
222 response.persistentBufferFlag = 0;
225 if (OCDoResponse(&response) != OC_STACK_OK)
227 OC_LOG(ERROR, TAG, "Error sending response");
228 ehResult = OC_EH_ERROR;
234 OCPayloadDestroy(response.payload);
239 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
240 void handleSigInt(int signum)
242 if (signum == SIGINT)
248 FILE *server_fopen(const char * /*path*/, const char *mode)
250 return fopen(CRED_FILE, mode);
253 void SetPersistentHandler(OCPersistentStorage *ps)
257 ps->open = server_fopen;
263 OCRegisterPersistentStorageHandler(ps);
268 * GetResult is returned result to string.
269 * @param result [IN] stack result
270 * @return converted OCStackResult as string for debugging
272 static const char *getResult(OCStackResult result)
277 return "OC_STACK_OK";
278 case OC_STACK_RESOURCE_CREATED:
279 return "OC_STACK_RESOURCE_CREATED";
280 case OC_STACK_RESOURCE_DELETED:
281 return "OC_STACK_RESOURCE_DELETED";
282 case OC_STACK_INVALID_URI:
283 return "OC_STACK_INVALID_URI";
284 case OC_STACK_INVALID_QUERY:
285 return "OC_STACK_INVALID_QUERY";
286 case OC_STACK_INVALID_IP:
287 return "OC_STACK_INVALID_IP";
288 case OC_STACK_INVALID_PORT:
289 return "OC_STACK_INVALID_PORT";
290 case OC_STACK_INVALID_CALLBACK:
291 return "OC_STACK_INVALID_CALLBACK";
292 case OC_STACK_INVALID_METHOD:
293 return "OC_STACK_INVALID_METHOD";
294 case OC_STACK_NO_MEMORY:
295 return "OC_STACK_NO_MEMORY";
296 case OC_STACK_COMM_ERROR:
297 return "OC_STACK_COMM_ERROR";
298 case OC_STACK_INVALID_PARAM:
299 return "OC_STACK_INVALID_PARAM";
300 case OC_STACK_NOTIMPL:
301 return "OC_STACK_NOTIMPL";
302 case OC_STACK_NO_RESOURCE:
303 return "OC_STACK_NO_RESOURCE";
304 case OC_STACK_RESOURCE_ERROR:
305 return "OC_STACK_RESOURCE_ERROR";
306 case OC_STACK_SLOW_RESOURCE:
307 return "OC_STACK_SLOW_RESOURCE";
308 case OC_STACK_NO_OBSERVERS:
309 return "OC_STACK_NO_OBSERVERS";
310 case OC_STACK_UNAUTHORIZED_REQ:
311 return "OC_STACK_UNAUTHORIZED_REQ";
313 case OC_STACK_PRESENCE_STOPPED:
314 return "OC_STACK_PRESENCE_STOPPED";
317 return "OC_STACK_ERROR";
325 * CreateDoorResource creates a new door resource by calling the OCCreateResource() method.
326 * @param uri [IN] uri
327 * @param doorResource [IN] info of resource
328 * @return ::OC_STACK_OK on success, some other value upon failure.
330 int createDoorResource (const char *uri, DoorResource *doorResource)
334 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
338 doorResource->state = STATE_CLOSED; //1:closed , 0: open
339 char str[] = "10min";
340 doorResource->openDuration = str;
341 doorResource->openAlarm = false;
342 OCStackResult res = OCCreateResource(&(doorResource->handle),
344 OC_RSRVD_INTERFACE_DEFAULT,
348 OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
350 OC_LOG_V(INFO, TAG, "Created Door resource with result: %s", getResult(res));
354 OCStackApplicationResult putReqCB(void * ctx, OCDoHandle /*handle*/, OCClientResponse *clientResponse)
356 if (ctx == (void *)DEFAULT_CONTEXT_VALUE)
358 OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
363 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
364 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
365 OC_LOG_PAYLOAD(INFO, clientResponse->payload);
366 if ((OCSecurityPayload*)clientResponse->payload)
368 OC_LOG_V(INFO, TAG, "=============> Put Response",
369 ((OCSecurityPayload*)clientResponse->payload)->securityData);
372 return OC_STACK_DELETE_TRANSACTION;
375 OCStackApplicationResult getReqCB(void * /*ctx*/, OCDoHandle /*handle*/, OCClientResponse *clientResponse)
377 OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
381 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
382 OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
383 OC_LOG_PAYLOAD(INFO, clientResponse->payload);
384 if ((OCSecurityPayload*)clientResponse->payload)
386 OC_LOG(INFO, TAG, PCF("=============> Get Response"));
389 return OC_STACK_DELETE_TRANSACTION;
392 // This is a function called back when a device is discovered
393 OCStackApplicationResult discoveryReqCB(void* /*ctx*/, OCDoHandle /*handle*/,
394 OCClientResponse * clientResponse)
396 OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
400 OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
402 "Device =============> Discovered @ %s:%d",
403 clientResponse->devAddr.addr,
404 clientResponse->devAddr.port);
406 if (clientResponse->result == OC_STACK_OK)
408 OC_LOG_PAYLOAD(INFO, clientResponse->payload);
409 ocConnType = clientResponse->connType;
410 parseClientResponse(clientResponse);
414 return OC_STACK_KEEP_TRANSACTION;
422 static bool initFlag = false;
425 OC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
426 OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
427 OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
434 // Local function to send get request of light resource
435 void SendGetRequest()
438 OC_LOG(INFO, TAG, "Send Get REQ to Light server");
442 char szQueryUri[64] = { '\0'};
444 OCCallbackData cbData;
445 cbData.cb = getReqCB;
446 cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
448 OC_LOG_V(INFO, TAG, "Get payload from Door sample = /a/light ");
449 snprintf(szQueryUri, sizeof(szQueryUri), "coaps://%s/a/light", const_cast<char*> (address.c_str())); // lightPortNu);
450 ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, NULL, ocConnType, OC_LOW_QOS,
452 if (ret != OC_STACK_OK)
454 OC_LOG(ERROR, TAG, "OCStack resource error");
459 void *input_function(void * /*data*/)
462 char szQueryUri[64] = { 0 };
464 OCCallbackData cbData;
465 cbData.cb = discoveryReqCB;
466 cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
469 strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
478 if (isUpdated == false)
480 OC_LOG(INFO, TAG, "isUpdated is false...");
481 OCDoResource(&handle, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
488 if (isUpdated == true)
490 OC_LOG(INFO, TAG, "isUpdated is true...");
504 static void PrintUsage()
506 OC_LOG(INFO, TAG, "*******************************************");
507 OC_LOG(INFO, TAG, "Input D or d to discover Resources");
508 OC_LOG(INFO, TAG, "Input G or g to initiate Get Request");
509 OC_LOG(INFO, TAG, "Input Q or q to exit");
510 OC_LOG(INFO, TAG, "*******************************************");
516 OC_LOG(INFO, TAG, "OCServer is starting...");
517 SetPersistentHandler(&ps);
519 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
521 OC_LOG(ERROR, TAG, "OCStack init error");
526 * Declare and create the example resource: Door
528 createDoorResource(gResourceUri, &Door);
531 //select ciphersuite for certificates
532 CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
534 struct timespec timeout;
536 timeout.tv_nsec = 100000000L;
538 // Break from loop with Ctrl-C
539 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
540 signal(SIGINT, handleSigInt);
543 thr_id = pthread_create(&p_thread, NULL, input_function, (void *)NULL);
546 OC_LOG(ERROR, TAG, "create thread error");
553 if (OCProcess() != OC_STACK_OK)
555 OC_LOG(ERROR, TAG, "OCStack process error");
560 nanosleep(&timeout, NULL);
563 pthread_join(p_thread, NULL);
565 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
567 if (OCStop() != OC_STACK_OK)
569 OC_LOG(ERROR, TAG, "OCStack process error");