Fix merge issues, Group action feature omit.
[platform/upstream/iotivity.git] / resource / csdk / stack / src / oicgroup.c
1 //******************************************************************
2 //
3 // Copyright 2014 Samsung Electronics All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
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 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
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.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #define _POSIX_C_SOURCE 200112L
22
23 #include <string.h>
24
25 #include "oicgroup.h"
26 #include "cJSON.h"
27 #include "ocmalloc.h"
28 #include "occollection.h"
29 #include "logger.h"
30 #include "timer.h"
31
32 #ifndef WITH_ARDUINO
33 #include <pthread.h>
34 #endif
35
36 #define TAG PCF("OICGROUP")
37
38 #define DESC_DELIMITER          "\""
39 #define ACTION_DELIMITER        "*"
40 #define ATTR_DELIMITER          "|"
41 #define ATTR_ASSIGN             "="
42
43 // Definitions for operations related to actions
44 #define DO_ACTION               "DoAction"
45 #define GET_ACTIONSET           "GetActionSet"
46 #define ACTIONSET               "ActionSet"
47 #define DELETE_ACTIONSET        "DelActionSet"
48
49 #define OIC_ACTION_PREFIX               "{\"oc\":[{\"rep\":{"
50 #define VARIFY_POINTER_NULL(pointer, result, toExit) \
51     if(pointer == NULL) \
52     {\
53         result = OC_STACK_NO_MEMORY;\
54         goto toExit;\
55     }
56 #define VARIFY_PARAM_NULL(pointer, result, toExit) \
57     if(pointer == NULL)\
58     {\
59         result = OC_STACK_INVALID_PARAM;\
60         goto exit;\
61     }
62
63 #define OCFREE(pointer) \
64     { \
65         OCFree(pointer); \
66         pointer = NULL; \
67     }
68
69 #ifndef WITH_ARDUINO
70 pthread_mutex_t lock;
71 #endif
72
73 enum ACTION_TYPE
74 {
75     NONE = 0, SCHEDULED, RECURSIVE
76 };
77
78 typedef struct scheduledresourceinfo
79 {
80     OCResource *resource;
81     OCActionSet *actionset;
82
83     int timer_id;
84
85     OCServerRequest *ehRequest;
86
87     time_t time;
88     struct scheduledresourceinfo* next;
89 } ScheduledResourceInfo;
90
91 ScheduledResourceInfo *scheduleResourceList = NULL;
92
93 void AddScheduledResource(ScheduledResourceInfo **head,
94         ScheduledResourceInfo* add)
95 {
96     OC_LOG(INFO, TAG, PCF("AddScheduledResource Entering..."));
97
98 #ifndef WITH_ARDUINO
99     pthread_mutex_lock(&lock);
100 #endif
101     ScheduledResourceInfo *tmp = NULL;
102
103     if (*head != NULL)
104     {
105         tmp = *head;
106
107         while (tmp->next)
108         {
109             tmp = tmp->next;
110         }
111         tmp->next = add;
112     }
113     else
114     {
115         *head = add;
116     }
117 #ifndef WITH_ARDUINO
118     pthread_mutex_unlock(&lock);
119 #endif
120 }
121
122 ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
123 {
124     OC_LOG(INFO, TAG, PCF("GetScheduledResource Entering..."));
125
126 #ifndef WITH_ARDUINO
127     pthread_mutex_lock(&lock);
128 #endif
129
130     time_t t_now;
131
132     ScheduledResourceInfo *tmp = NULL;
133     tmp = head;
134
135 #ifndef WITH_ARDUINO
136     time(&t_now);
137 #else
138     t_now = now();
139 #endif
140
141     if (tmp)
142     {
143         while (tmp)
144         {
145             time_t diffTm = 0;
146 #ifndef WITH_ARDUINO
147             diffTm = timespec_diff(tmp->time, t_now);
148 #else
149             diffTm = timespec_diff(tmp->time, t_now);
150 #endif
151
152             if (diffTm <= (time_t) 0)
153             {
154                 OC_LOG(INFO, TAG, PCF("return Call INFO."));
155                 goto exit;
156             }
157
158             tmp = tmp->next;
159         }
160     }
161
162     exit:
163 #ifndef WITH_ARDUINO
164     pthread_mutex_unlock(&lock);
165 #endif
166     if (tmp == NULL)
167     {
168         OC_LOG(INFO, TAG, PCF("Cannot Find Call Info."));
169     }
170     return tmp;
171 }
172
173 ScheduledResourceInfo* GetScheduledResourceByActionSetName(ScheduledResourceInfo *head, char *setName)
174 {
175     OC_LOG(INFO, TAG, PCF("GetScheduledResourceByActionSetName Entering..."));
176
177 #ifndef WITH_ARDUINO
178     pthread_mutex_lock(&lock);
179 #endif
180     ScheduledResourceInfo *tmp = NULL;
181     tmp = head;
182
183     if (tmp)
184     {
185         while (tmp)
186         {
187             if (strcmp(tmp->actionset->actionsetName, setName) == 0)
188             {
189                 OC_LOG(INFO, TAG, PCF("return Call INFO."));
190                 goto exit;
191             }
192             tmp = tmp->next;
193         }
194     }
195
196 exit:
197 #ifndef WITH_ARDUINO
198     pthread_mutex_unlock(&lock);
199 #endif
200     if (tmp == NULL)
201     {
202         OC_LOG(INFO, TAG, PCF("Cannot Find Call Info."));
203     }
204     return tmp;
205 }
206
207 void RemoveScheduledResource(ScheduledResourceInfo **head,
208         ScheduledResourceInfo* del)
209 {
210 #ifndef WITH_ARDUINO
211     pthread_mutex_lock(&lock);
212 #endif
213     OC_LOG(INFO, TAG, PCF("RemoveScheduledResource Entering..."));
214     ScheduledResourceInfo *tmp = NULL;
215
216     if (del == NULL)
217     {
218         return;
219     }
220
221     if (*head == del)
222     {
223         *head = (*head)->next;
224     }
225     else
226     {
227         tmp = *head;
228         while (tmp->next && (tmp->next != del))
229         {
230             tmp = tmp->next;
231         }
232         if (tmp->next)
233         {
234             tmp->next = del->next;
235         }
236     }
237
238     OCFREE(del)
239 #ifndef WITH_ARDUINO
240     pthread_mutex_unlock(&lock);
241 #endif
242 }
243
244 typedef struct aggregatehandleinfo
245 {
246     OCServerRequest *ehRequest;
247     OCDoHandle required;
248     OCResource *collResource;
249
250     struct aggregatehandleinfo *next;
251 } ClientRequestInfo;
252
253 ClientRequestInfo *clientRequstList = NULL;
254
255 void AddClientRequestInfo(ClientRequestInfo **head, ClientRequestInfo* add)
256 {
257     ClientRequestInfo *tmp = NULL;
258
259     if (*head != NULL)
260     {
261         tmp = *head;
262
263         while (tmp->next)
264         {
265             tmp = tmp->next;
266         }
267         tmp->next = add;
268     }
269     else
270     {
271         *head = add;
272     }
273 }
274
275 ClientRequestInfo* GetClientRequestInfo(ClientRequestInfo *head,
276         OCDoHandle handle)
277 {
278     ClientRequestInfo *tmp = NULL;
279
280     tmp = head;
281
282     if (tmp)
283     {
284         while (tmp)
285         {
286             if (tmp->required == handle)
287             {
288                 break;
289             }
290
291             tmp = tmp->next;
292         }
293
294         return tmp;
295     }
296     return NULL;
297 }
298
299 void RemoveClientRequestInfo(ClientRequestInfo **head, ClientRequestInfo* del)
300 {
301     ClientRequestInfo *tmp = NULL;
302
303     if (del == NULL)
304         return;
305
306     if (*head == del)
307     {
308         *head = (*head)->next;
309     }
310     else
311     {
312         tmp = *head;
313         while (tmp->next && (tmp->next != del))
314         {
315             tmp = tmp->next;
316         }
317         if (tmp->next)
318         {
319             tmp->next = del->next;
320         }
321     }
322 }
323
324 void AddCapability(OCCapability** head, OCCapability* node)
325 {
326     OCCapability *pointer = *head;
327     if (NULL == pointer)
328     {
329         *head = node;
330     }
331     else
332     {
333         while (pointer->next != NULL)
334         {
335             pointer = pointer->next;
336         }
337
338         pointer->next = node;
339     }
340 }
341
342 void AddAction(OCAction** head, OCAction* node)
343 {
344     OCAction *pointer = *head;
345     if (NULL == pointer)
346     {
347         *head = node;
348     }
349     else
350     {
351
352         while (pointer->next != NULL)
353         {
354             pointer = pointer->next;
355         }
356
357         pointer->next = node;
358     }
359 }
360
361 OCStackResult AddActionSet(OCActionSet **head, OCActionSet* node)
362 {
363     OCActionSet *pointer = *head;
364     OCActionSet *prev = NULL;
365     if(node == NULL)
366     {
367         return OC_STACK_ERROR;
368     }
369     if (NULL == pointer)
370     {
371         *head = node;
372     }
373     else
374     {
375         prev = pointer;
376         while (pointer != NULL)
377         {
378             // check the uniqeness of actionsetname.
379             if (strcmp(pointer->actionsetName, node->actionsetName) == 0)
380             {
381                 return OC_STACK_ERROR;
382             }
383
384             prev = pointer;
385             pointer = pointer->next;
386         }
387
388         prev->next = node;
389     }
390
391     return OC_STACK_OK;
392 }
393
394 void DeleteCapability(OCCapability *del)
395 {
396     OCFREE(del->capability)
397     del->capability = NULL;
398     OCFREE(del->status)
399     del->status = NULL;
400     OCFREE(del)
401 }
402
403 void DeleteAction(OCAction** action)
404 {
405     OCCapability* pointer = (*action)->head;
406     OCCapability* pDel = NULL;
407
408     while (pointer)
409     {
410         pDel = pointer;
411         pointer = pointer->next;
412
413         DeleteCapability(pDel);
414     }
415     OCFREE((*action)->resourceUri)
416     (*action)->next = NULL;
417     OCFREE(*action)
418 }
419
420 void DeleteActionSet(OCActionSet** actionset)
421 {
422     if(*actionset == NULL)
423         return;
424
425     OCAction* pointer = (*actionset)->head;
426     OCAction* pDel = NULL;
427
428     while (pointer)
429     {
430         pDel = pointer;
431         pointer = pointer->next;
432
433         DeleteAction(&pDel);
434     }
435     //    (*actionset)->head = NULL;
436     OCFREE((*actionset)->actionsetName)
437     OCFREE(*actionset)
438 }
439
440 OCStackResult FindAndDeleteActionSet(OCResource **resource,
441         const char * actionsetName)
442 {
443     if (*resource != NULL)
444     {
445         OCActionSet *pointer = NULL;
446         OCActionSet *pDel = NULL;
447
448         pointer = (*resource)->actionsetHead;
449
450         if (pointer == NULL)
451         {
452             return OC_STACK_ERROR;
453         }
454         else
455         {
456             if (strcmp(pointer->actionsetName, actionsetName) == 0)
457             {
458                 if (pointer->next != NULL)
459                     (*resource)->actionsetHead = pointer->next;
460                 else
461                     (*resource)->actionsetHead = NULL;
462
463                 DeleteActionSet(&pointer);
464             }
465             else if (pointer->next != NULL)
466             {
467                 while (pointer)
468                 {
469                     if (pointer->next != NULL)
470                     {
471                         if (strcmp(pointer->next->actionsetName, actionsetName)
472                                 == 0)
473                         {
474                             pDel = pointer->next;
475                             pointer->next = pointer->next->next;
476
477                             DeleteActionSet(&pDel);
478                         }
479                     }
480                     pointer = pointer->next;
481                 }
482             }
483
484             return OC_STACK_OK;
485         }
486
487     }
488     return OC_STACK_ERROR;
489 }
490
491 OCStackResult DeleteActionSets(OCResource** resource)
492 {
493     OCActionSet *pointer = (*resource)->actionsetHead;
494     OCActionSet *pDel = pointer;
495
496     while (pointer)
497     {
498         pDel = pointer;
499         pointer = pointer->next;
500
501         DeleteActionSet(&pDel);
502         pDel->next = NULL;
503     }
504
505     (*resource)->actionsetHead = NULL;
506     return OC_STACK_OK;
507 }
508
509 OCStackResult GetActionSet(const char *actionName, OCActionSet *head,
510         OCActionSet** actionset)
511 {
512     OCActionSet *pointer = head;
513
514     while (pointer)
515     {
516         if (strcmp(pointer->actionsetName, actionName) == 0)
517         {
518             *actionset = pointer;
519             return OC_STACK_OK;
520         }
521
522         pointer = pointer->next;
523     }
524
525     return OC_STACK_ERROR;
526
527 }
528
529 OCStackResult ExtractKeyValueFromRequest(char *request, char **key,
530         char **value)
531 {
532     OCStackResult result = OC_STACK_OK;
533     size_t length = 0;
534
535     char* pRequest = (char *) request + strlen(OIC_ACTION_PREFIX);
536     char* iterToken, *iterTokenPtr;
537
538     iterToken = (char *) strtok_r(pRequest, ":", &iterTokenPtr);
539     length = strlen(iterToken) + 1;
540
541     *key = (char *) OCMalloc(length);
542     VARIFY_POINTER_NULL(*key, result, exit)
543
544     strncpy(*key, iterToken + 1, length);
545     ((*key)[((length - 1) - 2)]) = '\0';
546
547     iterToken = (char *) strtok_r(NULL, "}", &iterTokenPtr);
548     length = strlen(iterToken) + 1;
549
550     *value = (char *) OCMalloc(length);
551     VARIFY_POINTER_NULL(*value, result, exit)
552
553     strncpy(*value, iterToken + 1, length);
554     ((*value)[((length - 1) - 2)]) = '\0';
555
556 exit:
557     if (result != OC_STACK_OK)
558     {
559         OCFREE(*key)
560         OCFREE(*value)
561     }
562
563     return result;
564 }
565
566 OCStackResult ExtractActionSetNameAndDelaytime(char *pChar, char **setName,
567         long int *pa)
568 {
569     char *token, *tokenPtr;
570     OCStackResult result = OC_STACK_OK;
571
572     token = (char*) strtok_r(pChar, ACTION_DELIMITER, &tokenPtr);
573     *setName = (char *) OCMalloc(strlen(token) + 1);
574     VARIFY_POINTER_NULL(*setName, result, exit)
575     VARIFY_PARAM_NULL(token, result, exit)
576     strncpy(*setName, token, strlen(token) + 1);
577
578     token = strtok_r(NULL, ACTION_DELIMITER, &tokenPtr);
579     VARIFY_POINTER_NULL(pa, result, exit)
580     VARIFY_PARAM_NULL(token, result, exit)
581     *pa = atoi(token);
582
583     return OC_STACK_OK;
584
585 exit:
586     OCFREE(*setName);
587     return result;
588 }
589
590 OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
591 {
592     OCStackResult result = OC_STACK_OK;
593
594     char *iterToken = NULL, *iterTokenPtr = NULL;
595     char *descIterToken = NULL, *descIterTokenPtr = NULL;
596     char *attrIterToken = NULL, *attrIterTokenPtr = NULL;
597     char *desc = NULL, *attr = NULL;
598     char *key = NULL, *value = NULL;
599
600     OCAction *action = NULL;
601     OCCapability *capa = NULL;
602
603     OC_LOG(INFO, TAG, PCF("Build ActionSet Instance."));
604
605     *set = (OCActionSet*) OCMalloc(sizeof(OCActionSet));
606     VARIFY_POINTER_NULL(*set, result, exit)
607
608     iterToken = (char *) strtok_r(actiondesc, ACTION_DELIMITER, &iterTokenPtr);
609
610     // ActionSet Name
611     memset(*set, 0, sizeof(OCActionSet));
612     (*set)->actionsetName = (char *) OCMalloc(strlen(iterToken) + 1);
613     VARIFY_POINTER_NULL((*set)->actionsetName, result, exit)
614     VARIFY_PARAM_NULL(iterToken, result, exit)
615     strncpy((*set)->actionsetName, iterToken, strlen(iterToken) + 1);
616
617     // Time info. for Scheduled/Recursive Group action.
618     // d is meant Day of the week.
619     // T is meant ActionType.
620     // yyyy-mm-dd hh:mm:ss d
621     iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
622     VARIFY_PARAM_NULL(iterToken, result, exit)
623 #ifndef WITH_ARDUINO
624     sscanf(iterToken, "%ld %d", &(*set)->timesteps, &(*set)->type);
625 #endif
626
627     OC_LOG_V(INFO, TAG, "ActionSet Name : %s", (*set)->actionsetName);
628
629     iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
630     while (iterToken)
631     {
632         desc = (char *) OCMalloc(strlen(iterToken) + 1);
633         VARIFY_POINTER_NULL(desc, result, exit)
634         VARIFY_PARAM_NULL(desc, result, exit)
635         strncpy(desc, iterToken, strlen(iterToken) + 1);
636         descIterToken = (char *) strtok_r(desc, ATTR_DELIMITER,
637                 &descIterTokenPtr);
638         while (descIterToken)
639         {
640             attr = (char *) OCMalloc(strlen(descIterToken) + 1);
641             VARIFY_POINTER_NULL(attr, result, exit)
642             VARIFY_PARAM_NULL(descIterToken, result, exit)
643             strncpy(attr, descIterToken, strlen(descIterToken) + 1);
644
645             attrIterToken = (char *) strtok_r(attr, ATTR_ASSIGN,
646                     &attrIterTokenPtr);
647             key = (char *) OCMalloc(strlen(attrIterToken) + 1);
648             VARIFY_POINTER_NULL(key, result, exit)
649             VARIFY_PARAM_NULL(attrIterToken, result, exit)
650             strncpy(key, attrIterToken, strlen(attrIterToken) + 1);
651
652             attrIterToken = (char *) strtok_r(NULL, ATTR_ASSIGN,
653                     &attrIterTokenPtr);
654             value = (char *) OCMalloc(strlen(attrIterToken) + 1);
655             VARIFY_POINTER_NULL(value, result, exit)
656             VARIFY_PARAM_NULL(attrIterToken, result, exit)
657             strncpy(value, attrIterToken, strlen(attrIterToken) + 1);
658
659             if (strcmp(key, "uri") == 0)
660             {
661                 OC_LOG(INFO, TAG, PCF("Build OCAction Instance."));
662
663                 action = (OCAction*) OCMalloc(sizeof(OCAction));
664                 VARIFY_POINTER_NULL(action, result, exit)
665                 memset(action, 0, sizeof(OCAction));
666                 action->resourceUri = (char *) OCMalloc(strlen(value) + 1);
667                 VARIFY_POINTER_NULL(action->resourceUri, result, exit)
668                 VARIFY_PARAM_NULL(value, result, exit)
669                 strncpy(action->resourceUri, value, strlen(value) + 1);
670             }
671             else
672             {
673                 if ((key != NULL) && (value != NULL))
674                 {
675                     OC_LOG(INFO, TAG, PCF("Build OCCapability Instance."));
676
677                     capa = (OCCapability*) OCMalloc(sizeof(OCCapability));
678                     VARIFY_POINTER_NULL(capa, result, exit)
679                     memset(capa, 0, sizeof(OCCapability));
680
681                     capa->capability = (char *) OCMalloc(strlen(key) + 1);
682                     VARIFY_POINTER_NULL(capa->capability, result, exit)
683                     VARIFY_PARAM_NULL(key, result, exit)
684                     strncpy(capa->capability, key, strlen(key) + 1);
685
686                     capa->status = (char *) OCMalloc(strlen(value) + 1);
687                     VARIFY_POINTER_NULL(capa->status, result, exit)
688                     VARIFY_PARAM_NULL(value, result, exit)
689                     strncpy(capa->status, value, strlen(value) + 1);
690
691                     VARIFY_POINTER_NULL(action, result, exit)
692
693                     AddCapability(&action->head, capa);
694                 }
695             }
696
697             OCFREE(key)
698             OCFREE(value)
699             OCFREE(attr)
700
701             descIterToken = (char *) strtok_r(NULL, ATTR_DELIMITER,
702                     &descIterTokenPtr);
703         }
704
705         AddAction(&(*set)->head, action);
706         iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
707         OCFREE(desc);
708     }
709
710     return OC_STACK_OK;
711 exit:
712     OCFREE(attr)
713     OCFREE(desc)
714     OCFREE(capa)
715     OCFREE(action)
716     OCFREE(*set)
717     OCFREE(key)
718     OCFREE(value)
719     OCFREE(attr)
720
721     return result;
722 }
723
724 OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
725 {
726     char temp[1024] = { 0 };
727     int remaining = 1023;
728
729     OCAction *action = actionset->head;
730
731     if (remaining >= strlen(actionset->actionsetName) + 1)
732     {
733         strcat(temp, actionset->actionsetName);
734         remaining -= strlen(actionset->actionsetName);
735         strcat(temp, ACTION_DELIMITER);
736         remaining--;
737     }
738     else
739     {
740         return OC_STACK_ERROR;
741     }
742
743     while (action != NULL)
744     {
745         strcat(temp, "uri=");
746         remaining -= strlen("uri=");
747         strcat(temp, action->resourceUri);
748         remaining -= strlen(action->resourceUri);
749         strcat(temp, "|");
750         remaining--;
751
752         OCCapability *capas = action->head;
753         while (capas != NULL)
754         {
755             strcat(temp, capas->capability);
756             remaining -= strlen(capas->capability);
757             strcat(temp, "=");
758             remaining--;
759             strcat(temp, capas->status);
760             remaining -= strlen(capas->capability);
761
762             capas = capas->next;
763             if (capas != NULL)
764             {
765                 strcat(temp, "|");
766             }
767         }
768
769         action = action->next;
770         if (action != NULL)
771         {
772             strcat(temp, ACTION_DELIMITER);
773             remaining--;
774         }
775     }
776
777     *desc = (char *) OCMalloc(1024 - remaining);
778     strcpy(*desc, temp);
779
780     return OC_STACK_OK;
781 }
782
783 OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
784         OCClientResponse* clientResponse)
785 {
786     OC_LOG(INFO, TAG, PCF("Entering BuildActionJSON"));
787
788     ClientRequestInfo *info = GetClientRequestInfo(clientRequstList, handle);
789
790     if (info)
791     {
792         int idx;
793
794         unsigned char *responseJson;
795         responseJson = (unsigned char *) OCMalloc(
796                 (unsigned int) (strlen((char *) clientResponse->resJSONPayload)
797                         + 1));
798
799         // We need the body of response.
800         // Copy the body from the response
801         strcpy((char *) responseJson,
802                 ((char *) clientResponse->resJSONPayload + OC_JSON_PREFIX_LEN));
803         idx = strlen((char *) responseJson) - OC_JSON_SUFFIX_LEN;
804         // And insert NULL at the end of body.
805         (responseJson[idx]) = 0;
806
807         OCEntityHandlerResponse response = { 0 };
808         response.ehResult = OC_EH_OK;
809         response.payload = (char*)responseJson;
810         response.payloadSize = (unsigned int) strlen((char *) responseJson) + 1;
811         response.persistentBufferFlag = 0;
812         response.requestHandle = (OCRequestHandle) info->ehRequest;
813         response.resourceHandle = (OCResourceHandle) info->collResource;
814
815         OCDoResponse(&response);
816
817         RemoveClientRequestInfo(&clientRequstList, info);
818         OCFREE(info)
819         OCFREE(responseJson)
820     }
821
822     return OC_STACK_KEEP_TRANSACTION;
823 }
824
825 void ActionSetCD(void *context)
826 {
827 }
828
829 OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr,
830         uint16_t *remaining)
831 {
832     OCStackResult ret = OC_STACK_ERROR;
833     cJSON *json;
834     cJSON *body;
835
836     char *jsonStr;
837     uint16_t jsonLen;
838
839     OC_LOG(INFO, TAG, PCF("Entering BuildActionJSON"));
840     json = cJSON_CreateObject();
841
842     cJSON_AddItemToObject(json, "rep", body = cJSON_CreateObject());
843
844     OCCapability* pointerCapa = action->head;
845     while (pointerCapa)
846     {
847         cJSON_AddStringToObject(body, pointerCapa->capability,
848                 pointerCapa->status);
849         pointerCapa = pointerCapa->next;
850     }
851
852     jsonStr = cJSON_PrintUnformatted(json);
853
854     jsonLen = strlen(jsonStr);
855     if (jsonLen < *remaining)
856     {
857         strcat((char*) bufferPtr, jsonStr);
858         *remaining -= jsonLen;
859         bufferPtr += jsonLen;
860         ret = OC_STACK_OK;
861     }
862
863     cJSON_Delete(json);
864     free(jsonStr);
865
866     return ret;
867 }
868
869 unsigned int GetNumOfTargetResource(OCAction *actionset)
870 {
871     int numOfResource = 0;
872
873     OCAction *pointerAction = actionset;
874
875     while (pointerAction != NULL)
876     {
877         numOfResource++;
878         pointerAction = pointerAction->next;
879     }
880
881     return numOfResource;
882 }
883
884
885 #define DEFAULT_CONTEXT_VALUE 0x99
886
887 OCStackResult SendAction(OCDoHandle *handle, const char *targetUri,
888         const unsigned char *action)
889 {
890     OCCallbackData cbdata = { 0 };
891     cbdata.cb = &ActionSetCB;
892     cbdata.cd = NULL;
893     cbdata.context = (void*)DEFAULT_CONTEXT_VALUE;
894
895     return OCDoResource(handle, OC_REST_PUT, targetUri,
896     NULL, (char *) action, OC_ETHERNET, OC_NA_QOS, &cbdata, NULL, 0);
897 }
898
899 OCStackResult DoAction(OCResource* resource, OCActionSet* actionset,
900         OCServerRequest* requestHandle)
901 {
902     OCStackResult result = OC_STACK_ERROR;
903     OCAction *pointerAction = actionset->head;
904
905     while (pointerAction != NULL)
906     {
907         unsigned char actionDesc[MAX_RESPONSE_LENGTH] = { 0 };
908         unsigned char* actionDescPtr = actionDesc;
909         uint16_t remaining = MAX_RESPONSE_LENGTH;
910
911         strncpy((char *) actionDescPtr, (const char *) OC_JSON_PREFIX,
912                 strlen((const char *) OC_JSON_PREFIX) + 1);
913         BuildActionJSON(pointerAction, actionDescPtr, &remaining);
914         strncat((char *) actionDescPtr, (const char *) OC_JSON_SUFFIX,
915                 strlen((const char *) OC_JSON_SUFFIX));
916
917         ClientRequestInfo *info = (ClientRequestInfo *) OCMalloc(
918                 sizeof(ClientRequestInfo));
919         memset(info, 0, sizeof(ClientRequestInfo));
920
921         info->collResource = resource;
922         info->ehRequest = requestHandle;
923
924         result = SendAction(&info->required, pointerAction->resourceUri,
925                 actionDescPtr);
926         if (result != OC_STACK_OK)
927         {
928             return result;
929         }
930
931         AddClientRequestInfo(&clientRequstList, info);
932
933         pointerAction = pointerAction->next;
934     }
935
936     return result;
937 }
938
939 void DoScheduledGroupAction()
940 {
941     OC_LOG(INFO, TAG, PCF("DoScheduledGroupAction Entering..."));
942     ScheduledResourceInfo* info = GetScheduledResource(scheduleResourceList);
943
944     if (info == NULL)
945     {
946         OC_LOG(INFO, TAG, PCF("Target resource is NULL"));
947         goto exit;
948     }
949     else if (info->resource == NULL)
950     {
951         OC_LOG(INFO, TAG, PCF("Target resource is NULL"));
952         goto exit;
953     }
954     else if (info->actionset == NULL)
955     {
956         OC_LOG(INFO, TAG, PCF("Target ActionSet is NULL"));
957         goto exit;
958     }
959     else if (info->ehRequest == NULL)
960     {
961         OC_LOG(INFO, TAG, PCF("Target ActionSet is NULL"));
962         goto exit;
963     }
964 #ifndef WITH_ARDUINO
965     pthread_mutex_lock(&lock);
966 #endif
967     DoAction(info->resource, info->actionset, info->ehRequest);
968 #ifndef WITH_ARDUINO
969     pthread_mutex_unlock(&lock);
970 #endif
971
972     if (info->actionset->type == RECURSIVE)
973     {
974         ScheduledResourceInfo *schedule;
975         schedule = (ScheduledResourceInfo *) OCMalloc(
976                 sizeof(ScheduledResourceInfo));
977
978         if (schedule)
979         {
980             OC_LOG(INFO, TAG, PCF("Building New Call Info."));
981             memset(schedule, 0, sizeof(ScheduledResourceInfo));
982
983             if (info->actionset->timesteps > 0)
984             {
985 #ifndef WITH_ARDUINO
986                 pthread_mutex_lock(&lock);
987 #endif
988                 schedule->resource = info->resource;
989                 schedule->actionset = info->actionset;
990                 schedule->ehRequest = info->ehRequest;
991
992                 schedule->time = registerTimer(info->actionset->timesteps,
993                         &schedule->timer_id,
994                         &DoScheduledGroupAction);
995
996                 OC_LOG(INFO, TAG, PCF("Reregisteration."));
997 #ifndef WITH_ARDUINO
998                 pthread_mutex_unlock(&lock);
999 #endif
1000                 AddScheduledResource(&scheduleResourceList, schedule);
1001             }
1002         }
1003     }
1004
1005     RemoveScheduledResource(&scheduleResourceList, info);
1006
1007     exit:
1008
1009     return;
1010 }
1011
1012 OCStackResult BuildCollectionGroupActionJSONResponse(
1013         OCMethod method/*OCEntityHandlerFlag flag*/, OCResource *resource,
1014         OCEntityHandlerRequest *ehRequest)
1015 {
1016     OCStackResult stackRet = OC_STACK_ERROR;
1017
1018     OC_LOG(INFO, TAG, PCF("Group Action is requested."));
1019     // if (stackRet == OC_STACK_OK)
1020     {
1021         char *doWhat = NULL;
1022         char *details = NULL;
1023
1024         size_t bufferLength = 0;
1025         unsigned char buffer[MAX_RESPONSE_LENGTH] = { 0 };
1026         unsigned char *bufferPtr = NULL;
1027
1028         bufferPtr = buffer;
1029
1030         OCResource * collResource = (OCResource *) ehRequest->resource;
1031
1032         char *jsonResponse;
1033
1034         ExtractKeyValueFromRequest((char *) ehRequest->reqJSONPayload, &doWhat,
1035                 &details);
1036
1037         cJSON *json;
1038         cJSON *format;
1039
1040         if (method == OC_REST_PUT)
1041         {
1042             json = cJSON_CreateObject();
1043             cJSON_AddStringToObject(json, "href", resource->uri);
1044             cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
1045
1046             OC_LOG(INFO, TAG, PCF("Group Action[PUT]."));
1047
1048             if (strcmp(doWhat, ACTIONSET) == 0)
1049             {
1050                 OCActionSet *actionSet = NULL;
1051                 stackRet = BuildActionSetFromString(&actionSet, details);
1052
1053                 if(stackRet == OC_STACK_OK)
1054                 {
1055                     if (actionSet != NULL)
1056                     {
1057                         stackRet = AddActionSet(&resource->actionsetHead,
1058                                 actionSet);
1059                         if (stackRet == OC_STACK_ERROR)
1060                         {
1061                             if(actionSet != NULL)
1062                             {
1063                                 DeleteActionSet( &actionSet );
1064                             }
1065                             OC_LOG(INFO, TAG, PCF("Duplicated ActionSet "));
1066                         }
1067                     }
1068                 }
1069                 else
1070                 {
1071                     stackRet = OC_STACK_ERROR;
1072                 }
1073
1074             }
1075             else if (strcmp(doWhat, DELETE_ACTIONSET) == 0)
1076             {
1077                 if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
1078                 {
1079                     stackRet = OC_STACK_OK;
1080                 }
1081                 else
1082                 {
1083                     stackRet = OC_STACK_ERROR;
1084                 }
1085             }
1086
1087             jsonResponse = cJSON_Print(json);
1088             cJSON_Delete(json);
1089
1090             strcat((char *) bufferPtr, jsonResponse);
1091
1092             bufferLength = strlen((const char *) buffer);
1093             if (bufferLength > 0)
1094             {
1095                 OCEntityHandlerResponse response = { 0 };
1096                 if(stackRet == OC_STACK_OK)
1097                     response.ehResult = OC_EH_OK;
1098                 else
1099                     response.ehResult = OC_EH_ERROR;
1100                 response.payload = (char*)buffer;
1101                 response.payloadSize = bufferLength + 1;
1102                 response.persistentBufferFlag = 0;
1103                 response.requestHandle =
1104                         (OCRequestHandle) ehRequest->requestHandle;
1105                 response.resourceHandle = (OCResourceHandle) collResource;
1106                 stackRet = OCDoResponse(&response);
1107             }
1108         }
1109
1110         if (method == OC_REST_POST)
1111         {
1112             OCActionSet *actionset = NULL;
1113
1114             json = cJSON_CreateObject();
1115             cJSON_AddStringToObject(json, "href", resource->uri);
1116
1117             if ((strcmp(doWhat, DO_ACTION) == 0)
1118                     || (strcmp(doWhat, "DoScheduledAction") == 0))
1119             {
1120                 char *pActionsetName = NULL;
1121                 long int delay = -1;
1122
1123                 if (strcmp(doWhat, "DoScheduledAction") == 0)
1124                 {
1125                     stackRet = ExtractActionSetNameAndDelaytime(details,
1126                             &pActionsetName, &delay);
1127
1128                     OCFREE(details)
1129                     details = pActionsetName;
1130                 }
1131                 else
1132                 {
1133                     stackRet = OC_STACK_OK;
1134                 }
1135
1136                 if (stackRet == OC_STACK_OK)
1137                 {
1138                     if (GetActionSet(details, resource->actionsetHead,
1139                             &actionset) != OC_STACK_OK)
1140                     {
1141                         OC_LOG(INFO, TAG, PCF("ERROR"));
1142                         stackRet = OC_STACK_ERROR;
1143                     }
1144
1145                     if (actionset == NULL)
1146                     {
1147                         OC_LOG(INFO, TAG, PCF("Cannot Find ActionSet"));
1148                         stackRet = OC_STACK_ERROR;
1149                     }
1150                     else
1151                     {
1152                         OC_LOG(INFO, TAG, PCF("Group Action[POST]."));
1153                         if (actionset->type == NONE)
1154                         {
1155                             OC_LOG_V(INFO, TAG, "Execute ActionSet : %s",
1156                                     actionset->actionsetName);
1157                             unsigned int num = GetNumOfTargetResource(
1158                                     actionset->head);
1159
1160                             ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
1161                                     HandleAggregateResponse;
1162                             ((OCServerRequest *) ehRequest->requestHandle)->numResponses =
1163                                     num + 1;
1164
1165                             DoAction(resource, actionset,
1166                                     (OCServerRequest*) ehRequest->requestHandle);
1167                             stackRet = OC_STACK_OK;
1168                         }
1169                         else
1170                         {
1171                             OC_LOG_V(INFO, TAG, "Execute Scheduled ActionSet : %s",
1172                                     actionset->actionsetName);
1173
1174                             delay =
1175                                     (delay == -1 ? actionset->timesteps : delay);
1176
1177                             ScheduledResourceInfo *schedule;
1178                             schedule = (ScheduledResourceInfo *) OCMalloc(
1179                                     sizeof(ScheduledResourceInfo));
1180
1181                             if (schedule)
1182                             {
1183                                 OC_LOG(INFO, TAG, PCF("Building New Call Info."));
1184                                 memset(schedule, 0,
1185                                         sizeof(ScheduledResourceInfo));
1186
1187                                 schedule->resource = resource;
1188                                 schedule->actionset = actionset;
1189                                 schedule->ehRequest =
1190                                         (OCServerRequest*) ehRequest->requestHandle;
1191
1192                                 if (delay > 0)
1193                                 {
1194                                     OC_LOG_V(INFO, TAG, "delay_time is %lf seconds.",
1195                                             actionset->timesteps);
1196
1197                                     schedule->time = registerTimer(delay,
1198                                             &schedule->timer_id,
1199                                             &DoScheduledGroupAction);
1200
1201                                     AddScheduledResource(&scheduleResourceList,
1202                                             schedule);
1203                                     stackRet = OC_STACK_OK;
1204                                 }
1205                                 else
1206                                 {
1207                                     stackRet = OC_STACK_ERROR;
1208                                 }
1209                             }
1210                         }
1211                     }
1212                 }
1213             }
1214             else if (strcmp(doWhat, "CancelAction") == 0)
1215             {
1216                 ScheduledResourceInfo *info =
1217                         GetScheduledResourceByActionSetName(scheduleResourceList, details);
1218
1219                 if(info != NULL)
1220                 {
1221                     unregisterTimer(info->timer_id);
1222
1223                     RemoveScheduledResource(&scheduleResourceList, info);
1224                     stackRet = OC_STACK_OK;
1225                 }
1226                 else
1227                 {
1228                     stackRet = OC_STACK_ERROR;
1229                 }
1230             }
1231
1232             else if (strcmp(doWhat, GET_ACTIONSET) == 0)
1233             {
1234                 char *plainText = NULL;
1235                 OCActionSet *actionset = NULL;
1236
1237                 cJSON_AddItemToObject(json, "rep", format =
1238                         cJSON_CreateObject());
1239                 GetActionSet(details, resource->actionsetHead, &actionset);
1240                 if (actionset != NULL)
1241                 {
1242                     BuildStringFromActionSet(actionset, &plainText);
1243
1244                     if (plainText != NULL)
1245                     {
1246                         cJSON_AddStringToObject(format, ACTIONSET, plainText);
1247                     }
1248
1249                     stackRet = OC_STACK_OK;
1250                 }
1251             }
1252
1253
1254             jsonResponse = cJSON_Print(json);
1255             cJSON_Delete(json);
1256
1257             strcat((char *) bufferPtr, jsonResponse);
1258
1259             bufferLength = strlen((const char *) buffer);
1260             if (bufferLength > 0)
1261             {
1262                 OCEntityHandlerResponse response = { 0 };
1263                 if(stackRet == OC_STACK_OK)
1264                     response.ehResult = OC_EH_OK;
1265                 else
1266                     response.ehResult = OC_EH_ERROR;
1267                 response.payload = (char *)buffer;
1268                 response.payloadSize = bufferLength + 1;
1269                 response.persistentBufferFlag = 0;
1270                 response.requestHandle =
1271                         (OCRequestHandle) ehRequest->requestHandle;
1272                 response.resourceHandle = (OCResourceHandle) collResource;
1273                 stackRet = OCDoResponse(&response);
1274             }
1275         }
1276
1277         OCFREE(doWhat)
1278         OCFREE(details)
1279     }
1280
1281     return stackRet;
1282 }