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 "ocserverbasicops.h"
35 static LEDResource LED;
36 // This variable determines instance number of the LED resource.
37 // Used by POST method to create a new instance of LED resource.
38 static int gCurrLedInstance = 0;
39 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
40 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
42 char *gResourceUri= (char *)"/a/led";
44 static uint16_t OC_WELL_KNOWN_PORT = 5683;
46 //File containing Server's Identity and the PSK credentials
47 //of other devices which the server trusts
48 //This can be generated using 'gen_sec_bin' application
49 static char CRED_FILE[] = "server_cred.bin";
51 //This function takes the request as an input and returns the response
53 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
55 cJSON *json = cJSON_CreateObject();
58 LEDResource *currLEDResource = &LED;
60 if (ehRequest->resource == gLedInstance[0].handle)
62 currLEDResource = &gLedInstance[0];
63 gResourceUri = (char *) "a/led/0";
65 else if (ehRequest->resource == gLedInstance[1].handle)
67 currLEDResource = &gLedInstance[1];
68 gResourceUri = (char *) "a/led/1";
71 if(OC_REST_PUT == ehRequest->method)
73 cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
74 currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
76 currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
77 cJSON_Delete(putJson);
80 cJSON_AddStringToObject(json,"href",gResourceUri);
81 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
82 cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
83 cJSON_AddNumberToObject(format, "power", currLEDResource->power);
85 jsonResponse = cJSON_Print(json);
90 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
91 char *payload, size_t maxPayloadSize)
93 OCEntityHandlerResult ehResult;
95 char *getResp = constructJsonResponse(ehRequest);
96 if (maxPayloadSize > strlen (getResp))
98 strcpy(payload, getResp);
103 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
105 ehResult = OC_EH_ERROR;
113 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
114 char *payload, size_t maxPayloadSize)
116 OCEntityHandlerResult ehResult;
118 char *putResp = constructJsonResponse(ehRequest);
119 if (maxPayloadSize > strlen (putResp))
121 strcpy(payload, putResp);
126 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
128 ehResult = OC_EH_ERROR;
136 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
137 char *payload, size_t maxPayloadSize)
139 char *respPLPost_led = NULL;
142 OCEntityHandlerResult ehResult;
145 * The entity handler determines how to process a POST request.
146 * Per the REST paradigm, POST can also be used to update representation of existing
147 * resource or create a new resource.
148 * In the sample below, if the POST is for /a/led then a new instance of the LED
149 * resource is created with default representation (if representation is included in
150 * POST payload it can be used as initial values) as long as the instance is
151 * lesser than max new instance count. Once max instance count is reached, POST on
152 * /a/led updated the representation of /a/led (just like PUT)
155 if (ehRequest->resource == LED.handle)
157 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
159 // Create new LED instance
160 char newLedUri[15] = "/a/led/";
161 int newLedUriLength = strlen(newLedUri);
162 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
164 json = cJSON_CreateObject();
166 cJSON_AddStringToObject(json,"href",gResourceUri);
167 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
168 cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
170 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
172 OC_LOG (INFO, TAG, "Created new LED instance");
173 gLedInstance[gCurrLedInstance].state = 0;
174 gLedInstance[gCurrLedInstance].power = 0;
176 respPLPost_led = cJSON_Print(json);
183 respPLPost_led = constructJsonResponse(ehRequest);
188 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
190 if (ehRequest->resource == gLedInstance[i].handle)
194 respPLPost_led = constructJsonResponse(ehRequest);
199 respPLPost_led = constructJsonResponse(ehRequest);
205 if ((respPLPost_led != NULL) && (maxPayloadSize > strlen (respPLPost_led)))
207 strcpy(payload, respPLPost_led);
212 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
214 ehResult = OC_EH_ERROR;
217 free(respPLPost_led);
222 OCEntityHandlerResult
223 OCEntityHandlerCb (OCEntityHandlerFlag flag,
224 OCEntityHandlerRequest *entityHandlerRequest)
226 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
228 OCEntityHandlerResult ehResult = OC_EH_ERROR;
229 OCEntityHandlerResponse response;
230 char payload[MAX_RESPONSE_LENGTH];
232 if (flag & OC_INIT_FLAG)
234 OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
237 if (flag & OC_REQUEST_FLAG)
239 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
240 if (entityHandlerRequest)
242 if (OC_REST_GET == entityHandlerRequest->method)
244 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
245 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload));
247 else if (OC_REST_PUT == entityHandlerRequest->method)
249 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
250 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload));
252 else if (OC_REST_POST == entityHandlerRequest->method)
254 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
255 ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload));
259 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
260 entityHandlerRequest->method);
263 if (ehResult == OC_EH_OK)
265 // Format the response. Note this requires some info about the request
266 response.requestHandle = entityHandlerRequest->requestHandle;
267 response.resourceHandle = entityHandlerRequest->resource;
268 response.ehResult = ehResult;
269 response.payload = (unsigned char *)payload;
270 response.payloadSize = strlen(payload);
271 response.numSendVendorSpecificHeaderOptions = 0;
272 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
273 memset(response.resourceUri, 0, sizeof(response.resourceUri));
274 // Indicate that response is NOT in a persistent buffer
275 response.persistentBufferFlag = 0;
278 if (OCDoResponse(&response) != OC_STACK_OK)
280 OC_LOG(ERROR, TAG, "Error sending response");
281 ehResult = OC_EH_ERROR;
289 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
290 void handleSigInt(int signum)
292 if (signum == SIGINT)
298 int main(int argc, char* argv[])
300 uint8_t addr[20] = {0};
301 uint8_t* paddr = NULL;
302 uint16_t port = OC_WELL_KNOWN_PORT;
303 uint8_t ifname[] = "eth0";
304 struct timespec timeout;
306 OC_LOG(DEBUG, TAG, "OCServer is starting...");
307 /*Get Ip address on defined interface and initialize coap on it with random port number
308 * this port number will be used as a source port in all coap communications*/
309 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
310 sizeof(addr)) == ERR_SUCCESS)
312 OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
316 if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK)
318 OC_LOG(ERROR, TAG, "OCStack init error");
323 * Read DTLS PSK credentials from persistent storage and
324 * set in the OC stack.
326 if (SetCredentials(CRED_FILE) != OC_STACK_OK)
328 OC_LOG(ERROR, TAG, "SetCredentials failed");
332 * Declare and create the example resource: LED
334 createLEDResource(gResourceUri, &LED, false, 0);
337 timeout.tv_nsec = 100000000L;
339 // Break from loop with Ctrl-C
340 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
341 signal(SIGINT, handleSigInt);
344 if (OCProcess() != OC_STACK_OK)
346 OC_LOG(ERROR, TAG, "OCStack process error");
349 nanosleep(&timeout, NULL);
352 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
354 if (OCStop() != OC_STACK_OK)
356 OC_LOG(ERROR, TAG, "OCStack process error");
362 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
366 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
370 ledResource->state = resourceState;
371 ledResource->power= resourcePower;
372 OCStackResult res = OCCreateResource(&(ledResource->handle),
377 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
378 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));