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 //string length of "/a/led/" + std::numeric_limits<int>::digits10 + '\0'"
34 const int URI_MAXSIZE = 17;
36 volatile sig_atomic_t gQuitFlag = 0;
38 static LEDResource LED;
39 // This variable determines instance number of the LED resource.
40 // Used by POST method to create a new instance of LED resource.
41 static int gCurrLedInstance = 0;
42 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
43 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
45 char *gResourceUri= (char *)"/a/led";
47 static uint16_t OC_WELL_KNOWN_PORT = 5683;
49 //This function takes the request as an input and returns the response
51 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
53 cJSON *json = cJSON_CreateObject();
56 LEDResource *currLEDResource = &LED;
58 if (ehRequest->resource == gLedInstance[0].handle)
60 currLEDResource = &gLedInstance[0];
61 gResourceUri = (char *) "a/led/0";
63 else if (ehRequest->resource == gLedInstance[1].handle)
65 currLEDResource = &gLedInstance[1];
66 gResourceUri = (char *) "a/led/1";
69 if(OC_REST_PUT == ehRequest->method)
71 cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
72 currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
74 currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
75 cJSON_Delete(putJson);
78 cJSON_AddStringToObject(json,"href",gResourceUri);
79 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
80 cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
81 cJSON_AddNumberToObject(format, "power", currLEDResource->power);
83 jsonResponse = cJSON_Print(json);
88 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
90 OCEntityHandlerResult ehResult;
91 char *getResp = constructJsonResponse(ehRequest);
93 if (maxPayloadSize > strlen ((char *)getResp))
95 strncpy(payload, getResp, strlen((char *)getResp));
100 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
102 ehResult = OC_EH_ERROR;
110 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
112 OCEntityHandlerResult ehResult;
113 char *putResp = constructJsonResponse(ehRequest);
115 if (maxPayloadSize > strlen ((char *)putResp))
117 strncpy(payload, putResp, strlen((char *)putResp));
122 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
124 ehResult = OC_EH_ERROR;
132 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
134 char *respPLPost_led = NULL;
137 OCEntityHandlerResult ehResult;
140 * The entity handler determines how to process a POST request.
141 * Per the REST paradigm, POST can also be used to update representation of existing
142 * resource or create a new resource.
143 * In the sample below, if the POST is for /a/led then a new instance of the LED
144 * resource is created with default representation (if representation is included in
145 * POST payload it can be used as initial values) as long as the instance is
146 * lesser than max new instance count. Once max instance count is reached, POST on
147 * /a/led updated the representation of /a/led (just like PUT)
150 if (ehRequest->resource == LED.handle)
152 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
154 // Create new LED instance
155 char newLedUri[URI_MAXSIZE ];
156 snprintf(newLedUri, URI_MAXSIZE, "/a/led/%d", gCurrLedInstance);
158 json = cJSON_CreateObject();
160 cJSON_AddStringToObject(json,"href",gResourceUri);
161 cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
162 cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
164 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
166 OC_LOG (INFO, TAG, "Created new LED instance");
167 gLedInstance[gCurrLedInstance].state = 0;
168 gLedInstance[gCurrLedInstance].power = 0;
170 respPLPost_led = cJSON_Print(json);
177 respPLPost_led = constructJsonResponse(ehRequest);
182 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
184 if (ehRequest->resource == gLedInstance[i].handle)
188 respPLPost_led = constructJsonResponse(ehRequest);
193 respPLPost_led = constructJsonResponse(ehRequest);
199 if ((respPLPost_led != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_led)))
201 strncpy(payload, respPLPost_led, strlen((char *)respPLPost_led));
206 OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
208 ehResult = OC_EH_ERROR;
211 free(respPLPost_led);
216 OCEntityHandlerResult
217 OCEntityHandlerCb (OCEntityHandlerFlag flag,
218 OCEntityHandlerRequest *entityHandlerRequest)
220 OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
222 OCEntityHandlerResult ehResult = OC_EH_ERROR;
223 OCEntityHandlerResponse response;
224 char payload[MAX_RESPONSE_LENGTH] = {0};
226 if (flag & OC_INIT_FLAG)
228 OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
231 if (flag & OC_REQUEST_FLAG)
233 OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
234 if (entityHandlerRequest)
236 if (OC_REST_GET == entityHandlerRequest->method)
238 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
239 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
241 else if (OC_REST_PUT == entityHandlerRequest->method)
243 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
244 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
246 else if (OC_REST_POST == entityHandlerRequest->method)
248 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
249 ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
253 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
254 entityHandlerRequest->method);
257 if (ehResult == OC_EH_OK)
259 // Format the response. Note this requires some info about the request
260 response.requestHandle = entityHandlerRequest->requestHandle;
261 response.resourceHandle = entityHandlerRequest->resource;
262 response.ehResult = ehResult;
263 response.payload = (unsigned char *)payload;
264 response.payloadSize = strlen(payload);
265 response.numSendVendorSpecificHeaderOptions = 0;
266 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
267 memset(response.resourceUri, 0, sizeof(response.resourceUri));
268 // Indicate that response is NOT in a persistent buffer
269 response.persistentBufferFlag = 0;
272 if (OCDoResponse(&response) != OC_STACK_OK)
274 OC_LOG(ERROR, TAG, "Error sending response");
275 ehResult = OC_EH_ERROR;
283 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
284 void handleSigInt(int signum)
286 if (signum == SIGINT)
292 int main(int argc, char* argv[])
294 uint8_t addr[20] = {0};
295 uint8_t* paddr = NULL;
296 uint16_t port = OC_WELL_KNOWN_PORT;
297 uint8_t ifname[] = "eth0";
299 OC_LOG(DEBUG, TAG, "OCServer is starting...");
300 /*Get Ip address on defined interface and initialize coap on it with random port number
301 * this port number will be used as a source port in all coap communications*/
302 if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
303 sizeof(addr)) == ERR_SUCCESS)
305 OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
309 if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK)
311 OC_LOG(ERROR, TAG, "OCStack init error");
316 * Declare and create the example resource: LED
318 createLEDResource(gResourceUri, &LED, false, 0);
320 // Break from loop with Ctrl-C
321 OC_LOG(INFO, TAG, "Entering ocserver main loop...");
322 signal(SIGINT, handleSigInt);
325 if (OCProcess() != OC_STACK_OK)
327 OC_LOG(ERROR, TAG, "OCStack process error");
334 OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
336 if (OCStop() != OC_STACK_OK)
338 OC_LOG(ERROR, TAG, "OCStack process error");
344 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
348 OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
352 ledResource->state = resourceState;
353 ledResource->power= resourcePower;
354 OCStackResult res = OCCreateResource(&(ledResource->handle),
359 OC_DISCOVERABLE|OC_OBSERVABLE);
360 OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));