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"
32 volatile sig_atomic_t gQuitFlag = 0;
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];
41 char *gResourceUri= (char *)"/a/led";
43 static uint16_t OC_WELL_KNOWN_PORT = 5683;
45 //This function takes the request as an input and returns the response
47 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
49 cJSON *json = cJSON_CreateObject();
52 LEDResource *currLEDResource = &LED;
54 if (ehRequest->resource == gLedInstance[0].handle)
56 currLEDResource = &gLedInstance[0];
57 gResourceUri = (char *) "a/led/0";
59 else if (ehRequest->resource == gLedInstance[1].handle)
61 currLEDResource = &gLedInstance[1];
62 gResourceUri = (char *) "a/led/1";
65 if(OC_REST_PUT == ehRequest->method)
67 cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
68 currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
70 currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
71 cJSON_Delete(putJson);
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);
79 jsonResponse = cJSON_Print(json);
84 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
86 OCEntityHandlerResult ehResult;
87 char *getResp = constructJsonResponse(ehRequest);
89 if (maxPayloadSize > strlen ((char *)getResp))
91 strncpy(payload, getResp, strlen((char *)getResp));
96 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
98 ehResult = OC_EH_ERROR;
106 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
108 OCEntityHandlerResult ehResult;
109 char *putResp = constructJsonResponse(ehRequest);
111 if (maxPayloadSize > strlen ((char *)putResp))
113 strncpy(payload, putResp, strlen((char *)putResp));
118 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
120 ehResult = OC_EH_ERROR;
128 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
130 char *respPLPost_led = NULL;
133 OCEntityHandlerResult ehResult;
136 * The entity handler determines how to process a POST request.
137 * Per the REST paradigm, POST can also be used to update representation of existing
138 * resource or create a new resource.
139 * In the sample below, if the POST is for /a/led then a new instance of the LED
140 * resource is created with default representation (if representation is included in
141 * POST payload it can be used as initial values) as long as the instance is
142 * lesser than max new instance count. Once max instance count is reached, POST on
143 * /a/led updated the representation of /a/led (just like PUT)
146 if (ehRequest->resource == LED.handle)
148 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
150 // Create new LED instance
151 char newLedUri[15] = "/a/led/";
152 sprintf (newLedUri + strlen(newLedUri), "%d", gCurrLedInstance);
154 json = cJSON_CreateObject();
156 cJSON_AddStringToObject(json,"href",gResourceUri);
157 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
158 cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
160 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
162 OC_LOG (INFO, TAG, "Created new LED instance");
163 gLedInstance[gCurrLedInstance].state = 0;
164 gLedInstance[gCurrLedInstance].power = 0;
166 respPLPost_led = cJSON_Print(json);
173 respPLPost_led = constructJsonResponse(ehRequest);
178 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
180 if (ehRequest->resource == gLedInstance[i].handle)
184 respPLPost_led = constructJsonResponse(ehRequest);
189 respPLPost_led = constructJsonResponse(ehRequest);
195 if ((respPLPost_led != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_led)))
197 strncpy(payload, respPLPost_led, strlen((char *)respPLPost_led));
202 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
204 ehResult = OC_EH_ERROR;
207 free(respPLPost_led);
212 OCEntityHandlerResult
213 OCEntityHandlerCb (OCEntityHandlerFlag flag,
214 OCEntityHandlerRequest *entityHandlerRequest)
216 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
218 OCEntityHandlerResult ehResult = OC_EH_ERROR;
219 OCEntityHandlerResponse response;
220 char payload[MAX_RESPONSE_LENGTH] = {0};
222 if (flag & OC_INIT_FLAG)
224 OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
227 if (flag & OC_REQUEST_FLAG)
229 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
230 if (entityHandlerRequest)
232 if (OC_REST_GET == entityHandlerRequest->method)
234 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
235 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
237 else if (OC_REST_PUT == entityHandlerRequest->method)
239 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
240 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
242 else if (OC_REST_POST == entityHandlerRequest->method)
244 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
245 ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
249 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
250 entityHandlerRequest->method);
253 if (ehResult == OC_EH_OK)
255 // Format the response. Note this requires some info about the request
256 response.requestHandle = entityHandlerRequest->requestHandle;
257 response.resourceHandle = entityHandlerRequest->resource;
258 response.ehResult = ehResult;
259 response.payload = (unsigned char *)payload;
260 response.payloadSize = strlen(payload);
261 response.numSendVendorSpecificHeaderOptions = 0;
262 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
263 memset(response.resourceUri, 0, sizeof(response.resourceUri));
264 // Indicate that response is NOT in a persistent buffer
265 response.persistentBufferFlag = 0;
268 if (OCDoResponse(&response) != OC_STACK_OK)
270 OC_LOG(ERROR, TAG, "Error sending response");
271 ehResult = OC_EH_ERROR;
279 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
280 void handleSigInt(int signum)
282 if (signum == SIGINT)
288 int main(int argc, char* argv[])
290 uint8_t addr[20] = {0};
291 uint8_t* paddr = NULL;
292 uint16_t port = OC_WELL_KNOWN_PORT;
293 uint8_t ifname[] = "eth0";
295 OC_LOG(DEBUG, TAG, "OCServer is starting...");
296 /*Get Ip address on defined interface and initialize coap on it with random port number
297 * this port number will be used as a source port in all coap communications*/
298 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
299 sizeof(addr)) == ERR_SUCCESS)
301 OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
305 if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK)
307 OC_LOG(ERROR, TAG, "OCStack init error");
312 * Declare and create the example resource: LED
314 createLEDResource(gResourceUri, &LED, false, 0);
316 // Break from loop with Ctrl-C
317 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
318 signal(SIGINT, handleSigInt);
321 if (OCProcess() != OC_STACK_OK)
323 OC_LOG(ERROR, TAG, "OCStack process error");
330 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
332 if (OCStop() != OC_STACK_OK)
334 OC_LOG(ERROR, TAG, "OCStack process error");
340 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
344 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
348 ledResource->state = resourceState;
349 ledResource->power= resourcePower;
350 OCStackResult res = OCCreateResource(&(ledResource->handle),
355 OC_DISCOVERABLE|OC_OBSERVABLE);
356 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));