Implemented libcoap's tinyDTLS interface
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / secure / ocserverbasicops.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH 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 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <signal.h>
26 #include <pthread.h>
27 #include "ocstack.h"
28 #include "logger.h"
29 #include "cJSON.h"
30 #include "ocserverbasicops.h"
31
32 int gQuitFlag = 0;
33
34 static LEDResource LED;
35 // This variable determines instance number of the LED resource.
36 // Used by POST method to create a new instance of LED resource.
37 static int gCurrLedInstance = 0;
38 #define SAMPLE_MAX_NUM_POST_INSTANCE  2
39 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
40
41 char *gResourceUri= (char *)"/a/led";
42
43 static uint16_t OC_WELL_KNOWN_PORT = 5683;
44
45 //This function takes the request as an input and returns the response
46 //in JSON format.
47 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
48 {
49     cJSON *json = cJSON_CreateObject();
50     cJSON *format;
51     char *jsonResponse;
52     LEDResource *currLEDResource = &LED;
53
54     if (ehRequest->resource == gLedInstance[0].handle)
55     {
56         currLEDResource = &gLedInstance[0];
57         gResourceUri = (char *) "a/led/0";
58     }
59     else if (ehRequest->resource == gLedInstance[1].handle)
60     {
61         currLEDResource = &gLedInstance[1];
62         gResourceUri = (char *) "a/led/1";
63     }
64
65     if(OC_REST_PUT == ehRequest->method)
66     {
67         cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
68         currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
69                 "on") ? true:false);
70         currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
71         cJSON_Delete(putJson);
72     }
73
74     cJSON_AddStringToObject(json,"href",gResourceUri);
75     cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
76     cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
77     cJSON_AddNumberToObject(format, "power", currLEDResource->power);
78
79     jsonResponse = cJSON_Print(json);
80     cJSON_Delete(json);
81     return jsonResponse;
82 }
83
84 void ProcessGetRequest (OCEntityHandlerRequest *ehRequest)
85 {
86     char *getResp = constructJsonResponse(ehRequest);
87
88     if (ehRequest->resJSONPayloadLen > strlen ((char *)getResp))
89     {
90         strncpy((char *)ehRequest->resJSONPayload, getResp,
91                 strlen((char *)getResp));
92     }
93     else
94     {
95         OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
96                 ehRequest->resJSONPayloadLen);
97     }
98
99     free(getResp);
100 }
101
102 void ProcessPutRequest (OCEntityHandlerRequest *ehRequest)
103 {
104     char *putResp = constructJsonResponse(ehRequest);
105
106     if (ehRequest->resJSONPayloadLen > strlen ((char *)putResp))
107     {
108         strncpy((char *)ehRequest->resJSONPayload, putResp,
109                 strlen((char *)putResp));
110     }
111     else
112     {
113         OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
114                 ehRequest->resJSONPayloadLen);
115     }
116
117     free(putResp);
118 }
119
120 void ProcessPostRequest (OCEntityHandlerRequest *ehRequest)
121 {
122     char *respPLPost_led = NULL;
123     cJSON *json;
124     cJSON *format;
125
126     /*
127      * The entity handler determines how to process a POST request.
128      * Per the REST paradigm, POST can also be used to update representation of existing
129      * resource or create a new resource.
130      * In the sample below, if the POST is for /a/led then a new instance of the LED
131      * resource is created with default representation (if representation is included in
132      * POST payload it can be used as initial values) as long as the instance is
133      * lesser than max new instance count. Once max instance count is reached, POST on
134      * /a/led updated the representation of /a/led (just like PUT)
135      */
136
137     if (ehRequest->resource == LED.handle)
138     {
139         if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
140         {
141             // Create new LED instance
142             char newLedUri[15] = "/a/led/";
143             sprintf (newLedUri + strlen(newLedUri), "%d", gCurrLedInstance);
144
145             json = cJSON_CreateObject();
146
147             cJSON_AddStringToObject(json,"href",gResourceUri);
148             cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
149             cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
150
151             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
152             {
153                 OC_LOG (INFO, TAG, "Created new LED instance");
154                 gLedInstance[gCurrLedInstance].state = 0;
155                 gLedInstance[gCurrLedInstance].power = 0;
156                 gCurrLedInstance++;
157                 respPLPost_led = cJSON_Print(json);
158             }
159
160             cJSON_Delete(json);
161         }
162         else
163         {
164             respPLPost_led = constructJsonResponse(ehRequest);
165         }
166     }
167     else
168     {
169         for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
170         {
171             if (ehRequest->resource == gLedInstance[i].handle)
172             {
173                 if (i == 0)
174                 {
175                     respPLPost_led = constructJsonResponse(ehRequest);
176                     break;
177                 }
178                 else if (i == 1)
179                 {
180                     respPLPost_led = constructJsonResponse(ehRequest);
181                 }
182             }
183         }
184     }
185
186     if (respPLPost_led != NULL && ehRequest->resJSONPayloadLen > strlen ((char *)respPLPost_led))
187     {
188         strncpy((char *)ehRequest->resJSONPayload, respPLPost_led,
189                 strlen((char *)respPLPost_led));
190     }
191     else
192     {
193         OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
194                 ehRequest->resJSONPayloadLen);
195     }
196
197     free(respPLPost_led);
198 }
199
200 OCEntityHandlerResult
201 OCEntityHandlerCb (OCEntityHandlerFlag flag,
202         OCEntityHandlerRequest *entityHandlerRequest)
203 {
204     OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
205     if (flag & OC_INIT_FLAG)
206     {
207         OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
208     }
209     if (flag & OC_REQUEST_FLAG)
210     {
211         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
212         if (entityHandlerRequest)
213         {
214             if (OC_REST_GET == entityHandlerRequest->method)
215             {
216                 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
217                 ProcessGetRequest (entityHandlerRequest);
218             }
219             else if (OC_REST_PUT == entityHandlerRequest->method)
220             {
221                 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
222                 ProcessPutRequest (entityHandlerRequest);
223             }
224             else if (OC_REST_POST == entityHandlerRequest->method)
225             {
226                 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
227                 ProcessPostRequest (entityHandlerRequest);
228             }
229             else
230             {
231                 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
232                         entityHandlerRequest->method);
233             }
234         }
235     }
236     return OC_EH_OK;
237 }
238
239 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
240 void handleSigInt(int signum)
241 {
242     if (signum == SIGINT)
243     {
244         gQuitFlag = 1;
245     }
246 }
247
248 int main(int argc, char* argv[])
249 {
250     uint8_t addr[20] = {0};
251     uint8_t* paddr = NULL;
252     uint16_t port = OC_WELL_KNOWN_PORT;
253     uint8_t ifname[] = "eth0";
254     int opt;
255     struct timespec timeout;
256
257     OC_LOG(DEBUG, TAG, "OCServer is starting...");
258     /*Get Ip address on defined interface and initialize coap on it with random port number
259      * this port number will be used as a source port in all coap communications*/
260     if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
261                 sizeof(addr)) == ERR_SUCCESS)
262     {
263         OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
264         paddr = addr;
265     }
266
267     if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK)
268     {
269         OC_LOG(ERROR, TAG, "OCStack init error");
270         return 0;
271     }
272
273     /*
274      * Declare and create the example resource: LED
275      */
276     createLEDResource(gResourceUri, &LED, false, 0);
277
278     timeout.tv_sec  = 0;
279     timeout.tv_nsec = 100000000L;
280
281     // Break from loop with Ctrl-C
282     OC_LOG(INFO, TAG, "Entering ocserver main loop...");
283     signal(SIGINT, handleSigInt);
284     while (!gQuitFlag)
285     {
286         if (OCProcess() != OC_STACK_OK)
287         {
288             OC_LOG(ERROR, TAG, "OCStack process error");
289             return 0;
290         }
291         nanosleep(&timeout, NULL);
292         //sleep(2);
293     }
294
295     OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
296
297     if (OCStop() != OC_STACK_OK)
298     {
299         OC_LOG(ERROR, TAG, "OCStack process error");
300     }
301
302     return 0;
303 }
304
305 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
306 {
307     if (!uri)
308     {
309         OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
310         return -1;
311     }
312
313     ledResource->state = resourceState;
314     ledResource->power= resourcePower;
315     OCStackResult res = OCCreateResource(&(ledResource->handle),
316             "core.led",
317             "oc.mi.def",
318             uri,
319             OCEntityHandlerCb,
320             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
321     OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
322
323     return 0;
324 }