OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest) { OCRepPayload* payload = OCRepPayloadCreate(); if (!payload) { OC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload"); return NULL; } if (ehRequest->resource == g_prov.handle) { OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_PROV); OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PS, g_prov.ps); OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TNT, g_prov.tnt); OCRepPayloadSetPropString(payload, OC_RSRVD_ES_TNN, g_prov.tnn); OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CD, g_prov.cd); } else if (ehRequest->requestHandle == g_net.handle) { OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET); OCRepPayloadSetPropInt(payload, "ant", g_net.ant[0]); } return payload; }
// This is the entity handler for the registered resource. // This is invoked by OCStack whenever it recevies a request for this resource. OCEntityHandlerResult SensorOCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest, void *callbackParam) { OCEntityHandlerResult ehRet = OC_EH_OK; OCEntityHandlerResponse response = {0}; OCRepPayload* payload = OCRepPayloadCreate(); if(!payload) { OC_LOG(ERROR, TAG, ("Failed to allocate Payload")); return OC_EH_ERROR; } if(entityHandlerRequest && (flag & OC_REQUEST_FLAG)) { OC_LOG (INFO, TAG, ("Flag includes OC_REQUEST_FLAG")); if(OC_REST_GET == entityHandlerRequest->method) { //sensor_get(); OCRepPayloadSetUri(payload, "/grove/sensor"); OCRepPayloadSetPropDouble(payload, "temperature", sensor.temp); OCRepPayloadSetPropInt(payload, "light", sensor.light); OCRepPayloadSetPropInt(payload, "sound", sensor.sound); } else if(OC_REST_PUT == entityHandlerRequest->method) { OC_LOG(ERROR, TAG, ("Un-supported request for Sensor: PUT")); } if (ehRet == OC_EH_OK) { // Format the response. Note this requires some info about the request response.requestHandle = entityHandlerRequest->requestHandle; response.resourceHandle = entityHandlerRequest->resource; response.ehResult = ehRet; response.payload = (OCPayload*) payload; response.numSendVendorSpecificHeaderOptions = 0; memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions); memset(response.resourceUri, 0, sizeof response.resourceUri); // Indicate that response is NOT in a persistent buffer response.persistentBufferFlag = 0; // Send the response if (OCDoResponse(&response) != OC_STACK_OK) { OC_LOG(ERROR, TAG, "Error sending response"); ehRet = OC_EH_ERROR; } } } if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG)) { if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) { OC_LOG (INFO, TAG, ("Received OC_OBSERVE_REGISTER from client")); gLightUnderObservation = 1; } else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) { OC_LOG (INFO, TAG, ("Received OC_OBSERVE_DEREGISTER from client")); gLightUnderObservation = 0; } } OCRepPayloadDestroy(payload); return ehRet; }
/** * @brief Called when a REST GET is request * * @param OCBaseResource base resource attributes * * @return result of the entityHandler */ OCEntityHandlerResult getRequest(OCBaseResourceT *resource, OCRepPayload *payload) { // Get the attributes and set them. OCAttributeT *current = resource->attribute; while(current != NULL) { // Check type switch(current->value.dataType) { case INT: OCRepPayloadSetPropInt(payload, current->name, current->value.data.i);// *((int*)current->value.data)); break; case DOUBLE: OCRepPayloadSetPropDouble(payload, current->name, current->value.data.d);// *((double*)current->value.data)); break; case STRING: OCRepPayloadSetPropString(payload, current->name, current->value.data.str);// *((char**)current->value.data)); break; case BOOL: OCRepPayloadSetPropBool(payload, current->name, current->value.data.b);// *((bool*)current->value.data)); break; } current = current->next; } return OC_EH_OK; }
TEST_F(CborByteStringTest, ByteStringArraySetGetTest ) { OCRepPayloadSetUri(payload_in, "/a/quake_sensor"); OCRepPayloadSetPropInt(payload_in, "scale", 4); size_t dimensions_in[MAX_REP_ARRAY_DEPTH] = { 3, 0, 0}; uint8_t binval1[] = {0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}; uint8_t binval2[] = {0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29}; uint8_t binval3[] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}; OCByteString quakedata_in[3] = {{binval1, sizeof(binval1)}, {binval2, sizeof(binval2)}, {binval3, sizeof(binval3)}}; EXPECT_EQ(true, OCRepPayloadSetByteStringArray(payload_in, "quakedata", quakedata_in, dimensions_in)); OCByteString* quakedata_out = NULL; size_t dimensions_out[MAX_REP_ARRAY_DEPTH] = {0}; ASSERT_EQ(true, OCRepPayloadGetByteStringArray(payload_in, "quakedata", &quakedata_out, dimensions_out)); for(size_t i = 0; i < dimensions_in[0]; i++) { EXPECT_EQ(quakedata_in[i].len, quakedata_out[i].len); EXPECT_EQ(0, memcmp(quakedata_in[i].bytes, quakedata_out[i].bytes, quakedata_in[i].len)); } // Cleanup for(size_t i = 0; i < dimensions_out[0]; i++) { OICFree(quakedata_out[i].bytes); } OICFree(quakedata_out); }
OCStackResult SendPingMessage(KeepAliveEntry_t *entry) { VERIFY_NON_NULL(entry, FATAL, OC_STACK_INVALID_PARAM); // Send ping message. OCCallbackData pingData = { .context = NULL, .cb = PingRequestCallback }; OCDevAddr devAddr = { .adapter = OC_ADAPTER_TCP }; CopyEndpointToDevAddr(&(entry->remoteAddr), &devAddr); OCRepPayload *payload = OCRepPayloadCreate(); if (!payload) { OIC_LOG(ERROR, TAG, "Failed to allocate Payload"); return OC_STACK_ERROR; } payload->base.type = PAYLOAD_TYPE_REPRESENTATION; OCRepPayloadSetPropInt(payload, INTERVAL, entry->interval); OCDoResource(NULL, OC_REST_PUT, KEEPALIVE_RESOURCE_URI, &devAddr, (OCPayload *) payload, CT_ADAPTER_TCP, OC_LOW_QOS, &pingData, NULL, 0); // Update timeStamp with time sent ping message for next ping message. entry->timeStamp = OICGetCurrentTime(TIME_IN_US); entry->sentPingMsg = true; OIC_LOG_V(DEBUG, TAG, "Client sent ping message, interval [%d]", entry->interval); return OC_STACK_OK; }
NSResult NSSetMessagePayload(NSMessage *msg, OCRepPayload** msgPayload) { NS_LOG(DEBUG, "NSSetMessagePayload - IN"); *msgPayload = msg->extraInfo != NULL ? msg->extraInfo : OCRepPayloadCreate(); if (!*msgPayload) { NS_LOG(ERROR, "Failed to allocate payload"); return NS_ERROR; } OCRepPayloadSetUri(*msgPayload, NS_COLLECTION_MESSAGE_URI); OCRepPayloadSetPropInt(*msgPayload, NS_ATTRIBUTE_MESSAGE_ID, msg->messageId); OCRepPayloadSetPropString(*msgPayload, NS_ATTRIBUTE_PROVIDER_ID, msg->providerId); NSDuplicateSetPropertyInt(msgPayload, NS_ATTRIBUTE_TYPE, msg->type); NSDuplicateSetPropertyInt(msgPayload, NS_ATTRIBUTE_TTL, msg->ttl); NSDuplicateSetPropertyString(msgPayload, NS_ATTRIBUTE_DATETIME, msg->dateTime); NSDuplicateSetPropertyString(msgPayload, NS_ATTRIBUTE_TITLE, msg->title); NSDuplicateSetPropertyString(msgPayload, NS_ATTRIBUTE_TEXT, msg->contentText); NSDuplicateSetPropertyString(msgPayload, NS_ATTRIBUTE_SOURCE, msg->sourceName); NSDuplicateSetPropertyString(msgPayload, NS_ATTRIBUTE_TOPIC_NAME, msg->topic); if (msg->mediaContents) { NSDuplicateSetPropertyString(msgPayload, NS_ATTRIBUTE_ICON_IMAGE, msg->mediaContents->iconImage); } NS_LOG(DEBUG, "NSSetMessagePayload - OUT"); return NS_OK; }
TEST_F(CborByteStringTest, ByteStringArrayConvertParseTest ) { OCRepPayloadSetUri(payload_in, "/a/quake_sensor"); OCRepPayloadSetPropInt(payload_in, "scale", 4); size_t dimensions_in[MAX_REP_ARRAY_DEPTH] = { 3, 0, 0}; uint8_t binval1[] = {0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}; uint8_t binval2[] = {0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29}; uint8_t binval3[] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}; OCByteString quakedata_in[3] = {{binval1, sizeof(binval1)}, {binval2, sizeof(binval2)}, {binval3, sizeof(binval3)}}; EXPECT_EQ(true, OCRepPayloadSetByteStringArray(payload_in, "quakedata", quakedata_in, dimensions_in)); // Convert OCPayload to CBOR uint8_t *payload_cbor = NULL; size_t payload_cbor_size = 0; EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload*) payload_in, &payload_cbor, &payload_cbor_size)); #ifdef CBOR_BIN_STRING_DEBUG FILE *fp = fopen("binstringarr.cbor", "wb+"); if (fp) { fwrite(payload_cbor, 1, payload_cbor_size, fp); fclose(fp); } #endif //CBOR_BIN_STRING_DEBUG // Parse CBOR back to OCPayload OCPayload* payload_out = NULL; EXPECT_EQ(OC_STACK_OK, OCParsePayload(&payload_out, PAYLOAD_TYPE_REPRESENTATION, payload_cbor, payload_cbor_size)); OCByteString* quakedata_out = NULL; size_t dimensions_out[MAX_REP_ARRAY_DEPTH] = {0}; ASSERT_EQ(true, OCRepPayloadGetByteStringArray((OCRepPayload*)payload_out, "quakedata", &quakedata_out, dimensions_out)); for(size_t i = 0; i < dimensions_in[0]; i++) { EXPECT_EQ(quakedata_in[i].len, quakedata_out[i].len); EXPECT_EQ(0, memcmp(quakedata_in[i].bytes, quakedata_out[i].bytes, quakedata_in[i].len)); } // Cleanup OICFree(payload_cbor); for(size_t i = 0; i < dimensions_out[0]; i++) { OICFree(quakedata_out[i].bytes); } OICFree(quakedata_out); OCPayloadDestroy((OCPayload*)payload_out); }
//This function takes the request as an input and returns the response //in JSON format. OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest) { LEDResource *currLEDResource = &LED; OC_LOG(INFO, TAG, "Entering constructResponse"); if (ehRequest->resource == gLedInstance[0].handle) { OC_LOG(INFO, TAG, "handle 0"); currLEDResource = &gLedInstance[0]; gResourceUri = const_cast<char *>("a/led/0"); } else if (ehRequest->resource == gLedInstance[1].handle) { OC_LOG(INFO, TAG, "handle 1"); currLEDResource = &gLedInstance[1]; gResourceUri = const_cast<char *>("a/led/1"); } if(OC_REST_PUT == ehRequest->method) { if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION) { OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation")); return nullptr; } OCRepPayload *putPayload = reinterpret_cast<OCRepPayload*> (ehRequest->payload); int64_t power; bool state; if (OCRepPayloadGetPropBool(putPayload, "state", &state)) { currLEDResource->state = state; } if (OCRepPayloadGetPropInt (putPayload, "power", &power)) { currLEDResource->power = power; } } OCRepPayload *response = OCRepPayloadCreate(); if (!response) { OC_LOG_V(ERROR, TAG, "Memory allocation for response payload failed."); } OCRepPayloadSetUri (response, gResourceUri); OCRepPayloadSetPropBool(response, "state", currLEDResource->state); OCRepPayloadSetPropInt(response, "power", currLEDResource->power); return response; }
NSResult NSSetSyncPayload(NSSyncInfo *sync, OCRepPayload** syncPayload) { NS_LOG(DEBUG, "NSSetSyncPayload - IN"); *syncPayload = OCRepPayloadCreate(); if (!*syncPayload) { NS_LOG(ERROR, "Failed to allocate payload"); return NS_ERROR; } OCRepPayloadSetUri(*syncPayload, NS_COLLECTION_SYNC_URI); OCRepPayloadSetPropString(*syncPayload, NS_ATTRIBUTE_PROVIDER_ID, sync->providerId); OCRepPayloadSetPropInt(*syncPayload, NS_ATTRIBUTE_MESSAGE_ID, sync->messageId); OCRepPayloadSetPropInt(*syncPayload, NS_ATTRIBUTE_STATE, sync->state); NS_LOG(DEBUG, "NSSetSyncPayload - OUT"); return NS_OK; }
OCPayload* putPayload() { OCRepPayload* payload = OCRepPayloadCreate(); if(!payload) { std::cout << "Failed to create put payload object"<<std::endl; std::exit(1); } OCRepPayloadSetPropInt(payload, "power", 42); OCRepPayloadSetPropBool(payload, "state", true); return (OCPayload*) payload; }
OCRepPayload* getPayload(const char* uri, int64_t brightness) { OCRepPayload* payload = OCRepPayloadCreate(); if(!payload) { OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload")); return nullptr; } OCRepPayloadSetUri(payload, uri); OCRepPayloadSetPropInt(payload, "brightness", brightness); return payload; }
OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest) { OCRepPayload* payload = OCRepPayloadCreate(); if (!payload) { OIC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload"); return NULL; } if (ehRequest->resource == gProvResource.handle) { OIC_LOG(INFO, ES_RH_TAG, "constructResponse prov res"); OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_PROV); OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PS, gProvResource.ps); OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TNT, gProvResource.tnt); } else if (ehRequest->requestHandle == gNetResource.handle) { OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET); OCRepPayloadSetPropInt(payload, "ant", gNetResource.ant[0]); } return payload; }
OCRepPayload* getPayload(const char* uri, int64_t power, bool state) { OCRepPayload* payload = OCRepPayloadCreate(); if(!payload) { OIC_LOG(ERROR, TAG, "Failed to allocate Payload"); return NULL; } OCRepPayloadSetUri(payload, uri); OCRepPayloadSetPropBool(payload, "state", state); OCRepPayloadSetPropInt(payload, "power", power); return payload; }
TEST_F(CborByteStringTest, ByteStringConvertParseTest) { OCRepPayloadSetUri(payload_in, "/a/quake_sensor"); OCRepPayloadSetPropInt(payload_in, "scale", 4); uint8_t binval[] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x0, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF}; OCByteString quakedata_in = { binval, sizeof(binval)}; // Set ByteString in Payload EXPECT_EQ(true, OCRepPayloadSetPropByteString(payload_in, "quakedata", quakedata_in)); // Convert OCPayload to CBOR uint8_t *payload_cbor = NULL; size_t payload_cbor_size = 0; EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload*) payload_in, &payload_cbor, &payload_cbor_size)); #ifdef CBOR_BIN_STRING_DEBUG FILE *fp = fopen("binstring.cbor", "wb+"); if (fp) { fwrite(payload_cbor, 1, payload_cbor_size, fp); fclose(fp); } #endif //CBOR_BIN_STRING_DEBUG // Parse CBOR back to OCPayload OCPayload* payload_out = NULL; EXPECT_EQ(OC_STACK_OK, OCParsePayload(&payload_out, PAYLOAD_TYPE_REPRESENTATION, payload_cbor, payload_cbor_size)); OCByteString quakedata_out = {NULL, 0}; ASSERT_EQ(true, OCRepPayloadGetPropByteString((OCRepPayload*)payload_out, "quakedata", &quakedata_out)); // Compare input and output data EXPECT_EQ(quakedata_in.len, quakedata_out.len); EXPECT_EQ(0, memcmp(quakedata_in.bytes, quakedata_out.bytes, quakedata_in.len)); // Cleanup OICFree(payload_cbor); OICFree(quakedata_out.bytes); OCPayloadDestroy((OCPayload*)payload_out); }
TEST_F(CborByteStringTest, ByteStringSetGetTest) { OCRepPayloadSetUri(payload_in, "/a/quake_sensor"); OCRepPayloadSetPropInt(payload_in, "scale", 4); uint8_t binval[] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x0, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF}; OCByteString quakedata_in = { binval, sizeof(binval)}; EXPECT_EQ(true, OCRepPayloadSetPropByteString(payload_in, "quakedata", quakedata_in)); OCByteString quakedata_out = { NULL, 0}; ASSERT_EQ(true, OCRepPayloadGetPropByteString(payload_in, "quakedata", &quakedata_out)); EXPECT_EQ(quakedata_in.len, quakedata_out.len); EXPECT_EQ(0, memcmp(quakedata_in.bytes, quakedata_out.bytes, quakedata_in.len)); // Cleanup OICFree(quakedata_out.bytes); }
OCEntityHandlerResult UpnpRenderingControl::processPutRequest(OCEntityHandlerRequest *ehRequest, string uri, string resourceType, OCRepPayload *payload) { (void) uri; if (!ehRequest || !ehRequest->payload || ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION) { throw "Incoming payload is NULL or not a representation"; } OCRepPayload *input = reinterpret_cast<OCRepPayload *>(ehRequest->payload); if (!input) { throw "PUT payload is null"; } if (UPNP_OIC_TYPE_AUDIO == resourceType) { //TODO use async version with callback GError *error = NULL; // set mute bool muteValue = false; if (OCRepPayloadGetPropBool(input, mutePropertyName, &muteValue)) { DEBUG_PRINT("New " << mutePropertyName << ": " << (muteValue ? "true" : "false")); if (! gupnp_service_proxy_send_action(m_proxy, setMuteAction, &error, // IN args instanceIdParamName, G_TYPE_UINT, defaultInstanceID, channelParamName, G_TYPE_STRING, defaultChannel, desiredMuteParamName, G_TYPE_BOOLEAN, muteValue, NULL, // OUT args (none) NULL)) { ERROR_PRINT(setMuteAction << " action failed"); if (error) { DEBUG_PRINT("Error message: " << error->message); g_error_free(error); } return OC_EH_ERROR; } if (!OCRepPayloadSetPropBool(payload, mutePropertyName, muteValue)) { throw "Failed to set mute value in payload"; } DEBUG_PRINT(mutePropertyName << ": " << (muteValue ? "true" : "false")); } // set volume int64_t volumeValue = 0; if (OCRepPayloadGetPropInt(input, volumePropertyName, &volumeValue)) { DEBUG_PRINT("New " << volumePropertyName << ": " << volumeValue); int upnpVolumeValue = volumeValue; if (! gupnp_service_proxy_send_action(m_proxy, setVolumeAction, &error, // IN args instanceIdParamName, G_TYPE_UINT, defaultInstanceID, channelParamName, G_TYPE_STRING, defaultChannel, desiredVolumeParamName, G_TYPE_UINT, upnpVolumeValue, NULL, // OUT args (none) NULL)) { ERROR_PRINT(setVolumeAction << " action failed"); if (error) { DEBUG_PRINT("Error message: " << error->message); g_error_free(error); } return OC_EH_ERROR; } if (!OCRepPayloadSetPropInt(payload, volumePropertyName, volumeValue)) { throw "Failed to set volume value in payload"; } DEBUG_PRINT(volumePropertyName << ": " << volumeValue); } } else { throw "Failed due to unknown resource type"; } return OC_EH_OK; }
void things_set_int_value(struct things_representation_s *rep, char *key, int64_t value) { OCRepPayloadSetPropInt(rep->payload, key, value); }
void CHPJsonToRepPayload(cJSON* rootJSon, OCRepPayload* payload) { cJSON* dataJson = rootJSon->child; while (dataJson) { switch (dataJson->type) { case cJSON_String: OCRepPayloadSetPropString(payload, dataJson->string, dataJson->valuestring); break; case cJSON_Number: if (dataJson->valueint == dataJson->valuedouble) { OCRepPayloadSetPropInt(payload, dataJson->string, dataJson->valueint); } else { OCRepPayloadSetPropDouble(payload, dataJson->string, dataJson->valuedouble); } break; case cJSON_False: OCRepPayloadSetPropBool(payload, dataJson->string, false); break; case cJSON_True: OCRepPayloadSetPropBool(payload, dataJson->string, true); break; case cJSON_Object: { OCRepPayload* childPayload = OCRepPayloadCreate(); CHPJsonToRepPayload(dataJson,childPayload); OCRepPayloadSetPropObject(payload, dataJson->string,childPayload ); break; } case cJSON_Array: { int size = cJSON_GetArraySize(dataJson); size_t dimensions[MAX_REP_ARRAY_DEPTH]; dimensions[0] = size; dimensions[1] = dimensions[2] = 0; int i = 0; int type = cJSON_IsReference; int numType = 0; // int:1, double:2 const int intType = 1; const int doubleType = 2; int64_t intArray[size]; double doubleArray[size]; char* strArray[size]; OCRepPayload* objPayloadArray[size]; for (; i < size ; ++i) { cJSON* subitem = cJSON_GetArrayItem(dataJson, i); if (subitem == NULL) { continue; } if ((type != cJSON_IsReference) && (type != subitem->type)) { continue; } else { type = subitem->type; switch (type) { case cJSON_Number: if (subitem->valueint == subitem->valuedouble) { numType = intType; intArray[i] = (int64_t) subitem->valueint; } else { numType = doubleType; doubleArray[i] = subitem->valuedouble; } break; case cJSON_String: strArray[i] = subitem->valuestring; break; case cJSON_Object: objPayloadArray[i] = OCRepPayloadCreate(); CHPJsonToRepPayload(subitem,objPayloadArray[i]); break; default: OIC_LOG(ERROR, TAG, "wrong ArrayType in JsonToRepPayload()"); break; } } } switch (type) { case cJSON_Number: if (numType == intType) { OCRepPayloadSetIntArray(payload, dataJson->string,(const int64_t*)intArray, dimensions); } else if (numType == doubleType) { OCRepPayloadSetDoubleArray(payload, dataJson->string, (const double*)doubleArray, dimensions); } break; case cJSON_String: OCRepPayloadSetStringArray(payload, dataJson->string, (const char**)strArray, dimensions); break; case cJSON_Object: OCRepPayloadSetPropObjectArray(payload, dataJson->string, (const OCRepPayload**)objPayloadArray, dimensions); break; default: OIC_LOG(ERROR, TAG, "wrong ArrayType in JsonToRepPayload()"); break; } break; } } dataJson = dataJson->next; } }
OCEntityHandlerResult BuzzerOCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest, void *callbackParam) { OCEntityHandlerResult ehRet = OC_EH_OK; OCEntityHandlerResponse response = {0}; OCRepPayload* payload = OCRepPayloadCreate(); if(!payload) { OC_LOG(ERROR, TAG, ("Failed to allocate Payload")); return OC_EH_ERROR; } if(entityHandlerRequest && (flag & OC_REQUEST_FLAG)) { OC_LOG (INFO, TAG, ("Flag includes OC_REQUEST_FLAG")); if(OC_REST_GET == entityHandlerRequest->method) { OCRepPayloadSetUri(payload, "/grove/buzzer"); OCRepPayloadSetPropInt(payload, "tone", buzzer.tone); } else if(OC_REST_PUT == entityHandlerRequest->method) { int64_t tone; OC_LOG(INFO, TAG, ("PUT request")); OCRepPayload *rep = (OCRepPayload *)entityHandlerRequest->payload; OCRepPayloadGetPropInt(rep, "tone", &tone); if(tone > 1915) tone = 1915; else if(tone < 956) tone = 956; buzzer.tone = (int)tone; OC_LOG_V(INFO, TAG, "Buzzer tone: %d", buzzer.tone); buzzer_put(); OCRepPayloadSetPropInt(payload, "tone", buzzer.tone); } if (ehRet == OC_EH_OK) { // Format the response. Note this requires some info about the request response.requestHandle = entityHandlerRequest->requestHandle; response.resourceHandle = entityHandlerRequest->resource; response.ehResult = ehRet; response.payload = (OCPayload*) payload; response.numSendVendorSpecificHeaderOptions = 0; memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions); memset(response.resourceUri, 0, sizeof response.resourceUri); // Indicate that response is NOT in a persistent buffer response.persistentBufferFlag = 0; // Send the response if (OCDoResponse(&response) != OC_STACK_OK) { OC_LOG(ERROR, TAG, "Error sending response"); ehRet = OC_EH_ERROR; } } } if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG)) { if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) { OC_LOG (INFO, TAG, ("Received OC_OBSERVE_REGISTER from client")); gLightUnderObservation = 1; } else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) { OC_LOG (INFO, TAG, ("Received OC_OBSERVE_DEREGISTER from client")); gLightUnderObservation = 0; } } OCRepPayloadDestroy(payload); return ehRet; }
static bool add_property_in_post_req_msg(st_things_set_request_message_s *req_msg, OCRepPayload *req_payload, things_attribute_info_s *prop) { RET_FALSE_IF_PARAM_IS_NULL(TAG, req_msg); RET_FALSE_IF_PARAM_IS_NULL(TAG, req_msg->rep); RET_FALSE_IF_PARAM_IS_NULL(TAG, req_msg->rep->payload); RET_FALSE_IF_PARAM_IS_NULL(TAG, req_payload); RET_FALSE_IF_PARAM_IS_NULL(TAG, prop); OCRepPayload *resp_payload = req_msg->rep->payload; THINGS_LOG_D(TAG, "Property Key is %s", prop->key); THINGS_LOG_D(TAG, "Property type is %d", prop->type); // Based on the property type, call appropriate methods to copy // the property from request payload to request representation. bool result = false; switch (prop->type) { case BOOL_ID: { bool value = false; if (OCRepPayloadGetPropBool(req_payload, prop->key, &value)) { result = OCRepPayloadSetPropBool(resp_payload, prop->key, value); if (!result) { THINGS_LOG_E(TAG, "Failed to set the boolean value of '%s' in request message.", prop->key); } } else { THINGS_LOG_E(TAG, "Failed to get the boolean value of '%s' for request message.", prop->key); } } break; case INT_ID: { int64_t value = 0; if (OCRepPayloadGetPropInt(req_payload, prop->key, &value)) { result = OCRepPayloadSetPropInt(resp_payload, prop->key, value); if (!result) { THINGS_LOG_E(TAG, "Failed to set the integer value of '%s' in request message", prop->key); } } else { THINGS_LOG_E(TAG, "Failed to get the integer value of '%s' for request message", prop->key); } } break; case DOUBLE_ID: { double value = 0.0; if (OCRepPayloadGetPropDouble(req_payload, prop->key, &value)) { result = OCRepPayloadSetPropDouble(resp_payload, prop->key, value); if (!result) { THINGS_LOG_E(TAG, "Failed to set the double value of '%s' in request message", prop->key); } } else { THINGS_LOG_E(TAG, "Failed to get the double value of '%s' for request message", prop->key); } } break; case STRING_ID: { char *value = NULL; if (OCRepPayloadGetPropString(req_payload, prop->key, &value)) { result = OCRepPayloadSetPropString(resp_payload, prop->key, value); if (!result) { THINGS_LOG_E(TAG, "Failed to set the string value of '%s' in request message", prop->key); } things_free(value); } else { THINGS_LOG_E(TAG, "Failed to get the string value of '%s' for request message", prop->key); } } break; case OBJECT_ID: { OCRepPayload *value = NULL; if (OCRepPayloadGetPropObject(req_payload, prop->key, &value)) { result = OCRepPayloadSetPropObject(resp_payload, prop->key, value); if (!result) { THINGS_LOG_E(TAG, "Failed to set the object value of '%s' in request message", prop->key); } OCRepPayloadDestroy(value); } else { THINGS_LOG_E(TAG, "Failed to get the object value of '%s' for request message", prop->key); } } break; case BYTE_ID: { OCByteString byte_value; if (OCRepPayloadGetPropByteString(req_payload, prop->key, &byte_value)) { result = OCRepPayloadSetPropByteString(resp_payload, prop->key, byte_value); if (!result) { THINGS_LOG_E(TAG, "Failed to set the byte string value of '%s' in request message", prop->key); } things_free(byte_value.bytes); } else { THINGS_LOG_E(TAG, "Failed to get the byte string value of '%s' for request message", prop->key); } } break; case INT_ARRAY_ID: { int64_t *value = NULL; size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 }; if (OCRepPayloadGetIntArray(req_payload, prop->key, &value, dimensions)) { result = OCRepPayloadSetIntArray(resp_payload, prop->key, value, dimensions); if (!result) { THINGS_LOG_E(TAG, "Failed to set the integer array value of '%s' in request message", prop->key); } things_free(value); } else { THINGS_LOG_E(TAG, "Failed to get the integer array value of '%s' for request message", prop->key); } } break; case DOUBLE_ARRAY_ID: { double *value = NULL; size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 }; if (OCRepPayloadGetDoubleArray(req_payload, prop->key, &value, dimensions)) { result = OCRepPayloadSetDoubleArray(resp_payload, prop->key, value, dimensions); if (!result) { THINGS_LOG_E(TAG, "Failed to set the double array value of '%s' in request message", prop->key); } things_free(value); } else { THINGS_LOG_E(TAG, "Failed to get the double array value of '%s' for request message", prop->key); } } break; case STRING_ARRAY_ID: { char **value = NULL; size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 }; if (OCRepPayloadGetStringArray(req_payload, prop->key, &value, dimensions)) { result = OCRepPayloadSetStringArray(resp_payload, prop->key, value, dimensions); if (!result) { THINGS_LOG_E(TAG, "Failed to set the string array value of '%s' in request message", prop->key); } size_t len = calcDimTotal(dimensions); things_free_str_array(value, len); } else { THINGS_LOG_E(TAG, "Failed to get the string array value of '%s' for request message", prop->key); } } break; case OBJECT_ARRAY_ID: { OCRepPayload **value = NULL; size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 }; if (OCRepPayloadGetPropObjectArray(req_payload, prop->key, &value, dimensions)) { result = OCRepPayloadSetPropObjectArray(resp_payload, prop->key, value, dimensions); if (!result) { THINGS_LOG_E(TAG, "Failed to set the object array value of '%s' in request message", prop->key); } size_t len = calcDimTotal(dimensions); for (size_t index = 0; index < len; index++) { OCRepPayloadDestroy(value[index]); } things_free(value); } else { THINGS_LOG_E(TAG, "Failed to get the object array value of '%s' for request message", prop->key); } } break; default: THINGS_LOG_E(TAG, "Invalid property type (%d).", prop->type); break; } return result; }
static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue *objMap) { if (!outPayload) { return false; } bool err = false; if (cbor_value_is_map(objMap)) { if (!*outPayload) { *outPayload = OCRepPayloadCreate(); if(!*outPayload) { return CborErrorOutOfMemory; } } OCRepPayload* curPayload = *outPayload; size_t len; CborValue repMap; err = err || cbor_value_enter_container(objMap, &repMap); while(!err && cbor_value_is_valid(&repMap)) { char* name; err = err || cbor_value_dup_text_string(&repMap, &name, &len, NULL); err = err || cbor_value_advance(&repMap); CborType type = cbor_value_get_type(&repMap); switch(type) { case CborNullType: err = !OCRepPayloadSetNull(curPayload, name); break; case CborIntegerType: { int64_t intval = 0; err = err || cbor_value_get_int64(&repMap, &intval); if (!err) { err = !OCRepPayloadSetPropInt(curPayload, name, intval); } } break; case CborDoubleType: { double doubleval = 0; err = err || cbor_value_get_double(&repMap, &doubleval); if (!err) { err = !OCRepPayloadSetPropDouble(curPayload, name, doubleval); } } break; case CborBooleanType: { bool boolval = false; err = err || cbor_value_get_boolean(&repMap, &boolval); if (!err) { err = !OCRepPayloadSetPropBool(curPayload, name, boolval); } } break; case CborTextStringType: { char* strval = NULL; err = err || cbor_value_dup_text_string(&repMap, &strval, &len, NULL); if (!err) { err = !OCRepPayloadSetPropStringAsOwner(curPayload, name, strval); } } break; case CborByteStringType: { uint8_t* bytestrval = NULL; err = err || cbor_value_dup_byte_string(&repMap, &bytestrval, &len, NULL); if (!err) { OCByteString tmp = {.bytes = bytestrval, .len = len}; err = !OCRepPayloadSetPropByteStringAsOwner(curPayload, name, &tmp); } } break; case CborMapType: { OCRepPayload *pl = NULL; err = err || OCParseSingleRepPayload(&pl, &repMap); if (!err) { err = !OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl); } } break; case CborArrayType: err = err || OCParseArray(curPayload, name, &repMap); break; default: OC_LOG_V(ERROR, TAG, "Parsing rep property, unknown type %d", repMap.type); err = true; } if (type != CborMapType && cbor_value_is_valid(&repMap)) { err = err || cbor_value_advance(&repMap); } OICFree(name); } err = err || cbor_value_leave_container(objMap, &repMap); if(err) { OCRepPayloadDestroy(*outPayload); *outPayload = NULL; } }
static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue* repParent) { if (!outPayload) { return false; } *outPayload = OCRepPayloadCreate(); OCRepPayload* curPayload = *outPayload; bool err = false; if(!*outPayload) { return CborErrorOutOfMemory; } size_t len; CborValue curVal; err = err || cbor_value_map_find_value(repParent, OC_RSRVD_HREF, &curVal); if(cbor_value_is_valid(&curVal)) { err = err || cbor_value_dup_text_string(&curVal, &curPayload->uri, &len, NULL); } err = err || cbor_value_map_find_value(repParent, OC_RSRVD_PROPERTY, &curVal); if(cbor_value_is_valid(&curVal)) { CborValue insidePropValue = {0}; err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_RESOURCE_TYPE, &insidePropValue); if(cbor_value_is_text_string(&insidePropValue)) { char* allRt = NULL; err = err || cbor_value_dup_text_string(&insidePropValue, &allRt, &len, NULL); char* savePtr; if (allRt) { char* curPtr = strtok_r(allRt, " ", &savePtr); while (curPtr) { char* trimmed = InPlaceStringTrim(curPtr); if (trimmed[0] != '\0') { OCRepPayloadAddResourceType(curPayload, curPtr); } curPtr = strtok_r(NULL, " ", &savePtr); } } OICFree(allRt); } err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_INTERFACE, &insidePropValue); if(cbor_value_is_text_string(&insidePropValue)) { char* allIf = NULL; err = err || cbor_value_dup_text_string(&insidePropValue, &allIf, &len, NULL); char* savePtr; if (allIf) { char* curPtr = strtok_r(allIf, " ", &savePtr); while (curPtr) { char* trimmed = InPlaceStringTrim(curPtr); if (trimmed[0] != '\0') { OCRepPayloadAddInterface(curPayload, curPtr); } curPtr = strtok_r(NULL, " ", &savePtr); } } OICFree(allIf); } } err = err || cbor_value_map_find_value(repParent, OC_RSRVD_REPRESENTATION, &curVal); if(cbor_value_is_map(&curVal)) { CborValue repMap; err = err || cbor_value_enter_container(&curVal, &repMap); while(!err && cbor_value_is_valid(&repMap)) { char* name; err = err || cbor_value_dup_text_string(&repMap, &name, &len, NULL); err = err || cbor_value_advance(&repMap); int64_t intval = 0; bool boolval = false; char* strval = NULL; double doubleval = 0; OCRepPayload* pl; switch(cbor_value_get_type(&repMap)) { case CborNullType: err = !OCRepPayloadSetNull(curPayload, name); break; case CborIntegerType: err = err || cbor_value_get_int64(&repMap, &intval); if (!err) { err = !OCRepPayloadSetPropInt(curPayload, name, intval); } break; case CborDoubleType: err = err || cbor_value_get_double(&repMap, &doubleval); if (!err) { err = !OCRepPayloadSetPropDouble(curPayload, name, doubleval); } break; case CborBooleanType: err = err || cbor_value_get_boolean(&repMap, &boolval); if (!err) { err = !OCRepPayloadSetPropBool(curPayload, name, boolval); } break; case CborTextStringType: err = err || cbor_value_dup_text_string(&repMap, &strval, &len, NULL); if (!err) { err = !OCRepPayloadSetPropStringAsOwner(curPayload, name, strval); } break; case CborMapType: err = err || OCParseSingleRepPayload(&pl, &repMap); if (!err) { err = !OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl); } break; case CborArrayType: err = err || OCParseArray(curPayload, name, &repMap); break; default: OC_LOG_V(ERROR, TAG, "Parsing rep property, unknown type %d", repMap.type); err = true; } err = err || cbor_value_advance(&repMap); OICFree(name); } err = err || cbor_value_leave_container(&curVal, &repMap); } if(err) { OCRepPayloadDestroy(*outPayload); *outPayload = NULL; } return err; }
static int _icd_state_value_from_gvariant(OCRepPayload *repr, GVariantIter *iter) { int ret; char *key; GVariant *var; const char *str_value; OCRepPayload *repr_value; struct icd_state_list_s value_list = {0}; while (g_variant_iter_loop(iter, "{sv}", &key, &var)) { if (g_variant_is_of_type(var, G_VARIANT_TYPE_BOOLEAN)) { OCRepPayloadSetPropBool(repr, key, g_variant_get_boolean(var)); } else if (g_variant_is_of_type(var, G_VARIANT_TYPE_INT32)) { OCRepPayloadSetPropInt(repr, key, g_variant_get_int32(var)); } else if (g_variant_is_of_type(var, G_VARIANT_TYPE_DOUBLE)) { OCRepPayloadSetPropDouble(repr, key, g_variant_get_double(var)); } else if (g_variant_is_of_type(var, G_VARIANT_TYPE_STRING)) { str_value = g_variant_get_string(var, NULL); if (NULL == str_value) { ERR("g_variant_get_string() Fail"); _icd_payload_state_list_destroy(&value_list); return IOTCON_ERROR_OUT_OF_MEMORY; } if (IC_STR_EQUAL == strcmp(IC_STR_NULL, str_value)) OCRepPayloadSetNull(repr, key); else OCRepPayloadSetPropString(repr, key, str_value); } else if (g_variant_is_of_type(var, G_VARIANT_TYPE("ay"))) { OCByteString byte_value; byte_value.bytes = (uint8_t*)g_variant_get_data(var); byte_value.len = g_variant_get_size(var); OCRepPayloadSetPropByteString(repr, key, byte_value); } else if (g_variant_is_of_type(var, G_VARIANT_TYPE("a{sv}"))) { GVariantIter state_iter; repr_value = OCRepPayloadCreate(); g_variant_iter_init(&state_iter, var); ret = _icd_state_value_from_gvariant(repr_value, &state_iter); if (IOTCON_ERROR_NONE != ret) { ERR("_icd_state_value_from_gvariant() Fail(%d)", ret); _icd_payload_state_list_destroy(&value_list); OCRepPayloadDestroy(repr_value); return ret; } OCRepPayloadSetPropObjectAsOwner(repr, key, repr_value); } else if (g_variant_is_of_type(var, G_VARIANT_TYPE_ARRAY)) { memset(&value_list, 0, sizeof(struct icd_state_list_s)); ret = _icd_state_list_from_gvariant(var, &value_list, 0); if (IOTCON_ERROR_NONE != ret) { ERR("_icd_state_list_from_gvariant() Fail(%d)", ret); _icd_payload_state_list_destroy(&value_list); return ret; } ret = _icd_state_array_from_list(repr, &value_list, key); if (IOTCON_ERROR_NONE != ret) { ERR("_icd_state_array_from_list() Fail(%d)", ret); _icd_payload_state_list_destroy(&value_list); return ret; } } else { ERR("Invalid type(%s)", g_variant_get_type_string(var)); return IOTCON_ERROR_INVALID_TYPE; } } return IOTCON_ERROR_NONE; }
/** * @brief Called when a REST PUT is request * * @param OCBaseResource base resource attributes * * @return result of the entityHandler */ OCEntityHandlerResult putRequest(OCEntityHandlerRequest *ehRequest, OCRepPayload* payload, OCBaseResourceT *resource) { // Set the new states OCRepPayload* inputPayload = (OCRepPayload*)(ehRequest->payload); OCAttributeT *current = resource->attribute; while(current != NULL) { switch(current->value.dataType) { case INT: { int64_t value(0); if(OCRepPayloadGetPropInt(inputPayload, current->name, &value)) { //OIC_LOG_V(DEBUG, TAG, "PUT: Type is int: %i", (int) value); //*((int*)current->value.data) = (int) value; current->value.data.i = value; } OCRepPayloadSetPropInt(payload, current->name, value); break; } case DOUBLE: { double value(0); if(OCRepPayloadGetPropDouble(inputPayload, current->name, &value)) { //OIC_LOG_V(DEBUG, TAG, "PUT: type is double: &d", value); //*((double*)current->value.data) = value; current->value.data.d = value; } OCRepPayloadSetPropDouble(payload, current->name, value); break; } case STRING: { char* value(""); if(OCRepPayloadGetPropString(inputPayload, current->name, &value)) { //OIC_LOG_V(DEBUG, TAG, "PUT: type is string: %s", value); //*((char**)current->value.data) = value; current->value.data.str = value; } OCRepPayloadSetPropString(payload, current->name, value); } case BOOL: { bool value(false); if(OCRepPayloadGetPropBool(inputPayload, current->name, &value)) { //OIC_LOG_V(DEBUG, TAG, "PUT: Type is bool: %s", value ? "true" : "false"); //*((bool*)current->value.data) = value; current->value.data.b = value; } OCRepPayloadSetPropBool(payload, current->name, value); break; } } current = current->next; } // Set the output pins if(resource->OCIOhandler) { OIC_LOG_V(DEBUG, TAG, "Value of underObservation is: %s", resource->underObservation ? "true" : "false"); resource->OCIOhandler(resource->attribute, OUTPUT, resource->handle, &resource->underObservation); } else { OIC_LOG(ERROR, TAG, "Resource OutputHandler has not been set"); } OIC_LOG(DEBUG, TAG, "Leaving putRequest"); return OC_EH_OK; }
OCEntityHandlerResult UpnpRenderingControl::processGetRequest(string uri, OCRepPayload *payload, string resourceType) { if (payload == NULL) { throw "payload is null"; } (void) resourceType; //TODO use async version with callback bool muteValue = false; int upnpVolumeValue = 0; GError *error = NULL; // get mute if (! gupnp_service_proxy_send_action(m_proxy, getMuteAction, &error, // IN args instanceIdParamName, G_TYPE_UINT, defaultInstanceID, channelParamName, G_TYPE_STRING, defaultChannel, NULL, // OUT args currentMuteParamName, G_TYPE_BOOLEAN, &muteValue, NULL)) { ERROR_PRINT(getMuteAction << " action failed"); if (error) { DEBUG_PRINT("Error message: " << error->message); g_error_free(error); } return OC_EH_ERROR; } if (!OCRepPayloadSetPropBool(payload, mutePropertyName, muteValue)) { throw "Failed to set mute value in payload"; } DEBUG_PRINT(mutePropertyName << ": " << (muteValue ? "true" : "false")); // get volume if (! gupnp_service_proxy_send_action(m_proxy, getVolumeAction, &error, // IN args instanceIdParamName, G_TYPE_UINT, defaultInstanceID, channelParamName, G_TYPE_STRING, defaultChannel, NULL, // OUT args currentVolumeParamName, G_TYPE_UINT, &upnpVolumeValue, NULL)) { ERROR_PRINT(getVolumeAction << " action failed"); if (error) { DEBUG_PRINT("Error message: " << error->message); g_error_free(error); } return OC_EH_ERROR; } int64_t volumeValue = upnpVolumeValue; if (!OCRepPayloadSetPropInt(payload, volumePropertyName, volumeValue)) { throw "Failed to set volume value in payload"; } DEBUG_PRINT(volumePropertyName << ": " << volumeValue); return UpnpService::processGetRequest(uri, payload, resourceType); }
NSResult NSSendSync(NSSyncInfo *sync) { NS_LOG(DEBUG, "NSSendSync - IN"); OCObservationId obArray[255] = { 0, }; int obCount = 0; int i; OCResourceHandle rHandle; if (NSPutSyncResource(sync, &rHandle) != NS_OK) { NS_LOG(ERROR, PCF("Fail to put sync resource")); return NS_ERROR; } NSCacheElement * it = consumerSubList->head; while (it) { NSCacheSubData * subData = (NSCacheSubData *) it->data; NS_LOG_V(INFO_PRIVATE, "sync subData->id = %s", subData->id); NS_LOG_V(DEBUG, "subData->messageId = %d", subData->messageObId); NS_LOG_V(DEBUG, "subData->cloud_messageId = %d", subData->remote_messageObId); NS_LOG_V(DEBUG, "subData->syncId = %d", subData->syncObId); NS_LOG_V(DEBUG, "subData->cloud_syncId = %d", subData->remote_syncObId); NS_LOG_V(DEBUG, "subData->isWhite = %d", subData->isWhite); if (subData->isWhite) { if (subData->syncObId != 0) { obArray[obCount++] = subData->syncObId; } #if (defined WITH_CLOUD) if (subData->remote_syncObId != 0) { obArray[obCount++] = subData->remote_syncObId; } #endif } it = it->next; } OCRepPayload* payload = NULL; if (NSSetSyncPayload(sync, &payload) != NS_OK) { NS_LOG(ERROR, "Failed to allocate payload"); return NS_ERROR; } #ifdef WITH_MQ if (NSGetMQServerInfo()) { OCRepPayload* MQPayload = OCRepPayloadClone(payload); NSMessageType MQType = 0; if (sync->state == NS_SYNC_READ) { MQType = NS_MESSAGE_READ; } else if (sync->state == NS_SYNC_DELETED) { MQType = NS_MESSAGE_DELETED; } OCRepPayloadSetPropInt(MQPayload, NS_ATTRIBUTE_TYPE, (int64_t) MQType); NSProviderPublishTopic(MQPayload, NSProviderPublishMQResponseCB); } #endif for (i = 0; i < obCount; ++i) { NS_LOG(DEBUG, "-------------------------------------------------------message\n"); NS_LOG_V(DEBUG, "Sync WhiteList[%d] = %d", i, obArray[i]); NS_LOG(DEBUG, "-------------------------------------------------------message\n"); } OCStackResult ocstackResult = OCNotifyListOfObservers(rHandle, obArray, obCount, payload, OC_LOW_QOS); NS_LOG_V(DEBUG, "Sync ocstackResult = %d", ocstackResult); if (ocstackResult != OC_STACK_OK) { NS_LOG(ERROR, "fail to send Sync"); OCRepPayloadDestroy(payload); return NS_ERROR; } OCRepPayloadDestroy(payload); NS_LOG(DEBUG, "NSSendSync - OUT"); return NS_OK; }
OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest, void *callbackParam) { OCEntityHandlerResult ehRet = OC_EH_OK; OCEntityHandlerResponse response = {0}; OCRepPayload* payload = OCRepPayloadCreate(); if(!payload) { //OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload")); return OC_EH_ERROR; } if(entityHandlerRequest && (flag & OC_REQUEST_FLAG)) { //OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG")); if(OC_REST_GET == entityHandlerRequest->method) { OCRepPayloadSetUri(payload, "/iotar/speaker"); OCRepPayloadSetPropInt(payload, "state", speaker.state); OCRepPayloadSetPropInt(payload, "volume",speaker.volume); OCRepPayloadSetPropInt(payload, "time", speaker.time); OCRepPayloadSetPropInt(payload, "present_song",speaker.present_song); OCRepPayloadSetPropInt(payload, "next_song", speaker.next_song); } else if(OC_REST_PUT == entityHandlerRequest->method) { //OC_LOG_V(DEBUG, TAG, "put \n"); //풋 올때 데이터 어떻게 받지?? OCRepPayload* pay = (OCRepPayload*) entityHandlerRequest-> payload; int64_t order = 0; int64_t temp = 0; char in[10]; OCRepPayloadGetPropInt(pay, "order", &order); if(order == 30){ //재생 OCRepPayloadGetPropInt(pay, "temp", &temp); makeString('a', temp, (char*)&in); speaker.present_song = temp; Serial1.println(in); millis_prv = millis(); save_time = 0; speaker.state = 1; }else if(order == 31){ //볼륨 설정 OCRepPayloadGetPropInt(pay, "temp", &temp); makeString('v', temp, (char*)&in); speaker.volume = temp; Serial1.println(in); }else if(order == 32){ //다음 노래 설정 OCRepPayloadGetPropInt(pay, "temp", &temp); makeString('d', temp, (char*)&in); speaker.next_song = temp; Serial1.println(in); }else if(order == 33){ // 현재 아무일 안하고 있으면 0, 재생중 1, 일시정지 2. 로 세팅. Serial1.println('x'); }else if(order == 34) { //정지. Serial1.println('s'); }else if(order == 35) { // +1 볼륨. speaker.volume++; if(speaker.volume >= 100){ speaker.volume = 100; } makeString('v', speaker.volume, (char*)&in); Serial1.println(in); }else if(order == 36) { // -1 볼륨. speaker.volume--; if(speaker.volume < 1){ speaker.volume = 1; } makeString('v', speaker.volume, (char*)&in); Serial1.println(in); }else if(order == 37){ // 일시정지, 일시정지 풀기. Serial1.println('p'); if(speaker.state == 1){ speaker.state = 2; save_time = speaker.time+2; }else{ speaker.state = 1; millis_prv = millis(); } }else if(order == 38){ //다음노래 재생 speaker.present_song++; if(speaker.present_song > MAX_SONG){ speaker.present_song = 1; } makeString('a', speaker.present_song, (char*)&in); Serial1.println(in); millis_prv = millis(); save_time = 0; speaker.state = 1; }else if(order == 39){ // 이전 노래 재생 speaker.present_song--; if(speaker.present_song < 1){ speaker.present_song = MAX_SONG; } makeString('a', speaker.present_song, (char*)&in); Serial1.println(in); millis_prv = millis(); save_time = 0; speaker.state = 1; } OCRepPayloadSetUri(payload, "/iotar/speaker"); OCRepPayloadSetPropInt(payload, "time", speaker.time); } if (ehRet == OC_EH_OK) { // Format the response. Note this requires some info about the request response.requestHandle = entityHandlerRequest->requestHandle; response.resourceHandle = entityHandlerRequest->resource; response.ehResult = ehRet; response.payload = (OCPayload*) payload; response.numSendVendorSpecificHeaderOptions = 0; memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions); memset(response.resourceUri, 0, sizeof response.resourceUri); // Indicate that response is NOT in a persistent buffer response.persistentBufferFlag = 0; // Send the response if (OCDoResponse(&response) != OC_STACK_OK) { // OC_LOG(ERROR, TAG, "Error sending response"); ehRet = OC_EH_ERROR; } } } if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG)) { if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) { // OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client")); gLightUnderObservation = 1; } else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) { // OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client")); gLightUnderObservation = 0; } } OCRepPayloadDestroy(payload); return ehRet; }
// This is the entity handler for the registered resource. // This is invoked by OCStack whenever it recevies a request for this resource. OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest, void *callbackParam) { OCEntityHandlerResult ehRet = OC_EH_OK; OCEntityHandlerResponse response = {0}; OCRepPayload* payload = OCRepPayloadCreate(); if(!payload) { OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload")); return OC_EH_ERROR; } if(entityHandlerRequest && (flag & OC_REQUEST_FLAG)) { OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG")); if(OC_REST_GET == entityHandlerRequest->method) { OCRepPayloadSetUri(payload, "/a/light"); OCRepPayloadSetPropBool(payload, "state", true); OCRepPayloadSetPropInt(payload, "power", 10); } else if(OC_REST_PUT == entityHandlerRequest->method) { //Do something with the 'put' payload OCRepPayloadSetUri(payload, "/a/light"); OCRepPayloadSetPropBool(payload, "state", false); OCRepPayloadSetPropInt(payload, "power", 0); } if (ehRet == OC_EH_OK) { // Format the response. Note this requires some info about the request response.requestHandle = entityHandlerRequest->requestHandle; response.resourceHandle = entityHandlerRequest->resource; response.ehResult = ehRet; response.payload = (OCPayload*) payload; response.numSendVendorSpecificHeaderOptions = 0; memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions); memset(response.resourceUri, 0, sizeof response.resourceUri); // Indicate that response is NOT in a persistent buffer response.persistentBufferFlag = 0; // Send the response if (OCDoResponse(&response) != OC_STACK_OK) { OC_LOG(ERROR, TAG, "Error sending response"); ehRet = OC_EH_ERROR; } } } if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG)) { if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) { OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client")); gLightUnderObservation = 1; } else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) { OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client")); } } return ehRet; }
static CborError OCParseSingleRepPayload(OCRepPayload **outPayload, CborValue *objMap, bool isRoot) { CborError err = CborUnknownError; char *name = NULL; bool res; VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid Parameter outPayload"); VERIFY_PARAM_NON_NULL(TAG, objMap, "Invalid Parameter objMap"); if (cbor_value_is_map(objMap)) { if (!*outPayload) { *outPayload = OCRepPayloadCreate(); if (!*outPayload) { return CborErrorOutOfMemory; } } OCRepPayload *curPayload = *outPayload; size_t len = 0; CborValue repMap; err = cbor_value_enter_container(objMap, &repMap); VERIFY_CBOR_SUCCESS(TAG, err, "Failed entering repMap"); while (!err && cbor_value_is_valid(&repMap)) { if (cbor_value_is_text_string(&repMap)) { err = cbor_value_dup_text_string(&repMap, &name, &len, NULL); VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding tag name in the map"); err = cbor_value_advance(&repMap); VERIFY_CBOR_SUCCESS(TAG, err, "Failed advancing rootMap"); if (name && isRoot && ((0 == strcmp(OC_RSRVD_HREF, name)) || (0 == strcmp(OC_RSRVD_RESOURCE_TYPE, name)) || (0 == strcmp(OC_RSRVD_INTERFACE, name)))) { err = cbor_value_advance(&repMap); OICFree(name); continue; } } CborType type = cbor_value_get_type(&repMap); switch (type) { case CborNullType: res = OCRepPayloadSetNull(curPayload, name); break; case CborIntegerType: { int64_t intval = 0; err = cbor_value_get_int64(&repMap, &intval); VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting int value"); res = OCRepPayloadSetPropInt(curPayload, name, intval); } break; case CborDoubleType: { double doubleval = 0; err = cbor_value_get_double(&repMap, &doubleval); VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting double value"); res = OCRepPayloadSetPropDouble(curPayload, name, doubleval); } break; case CborBooleanType: { bool boolval = false; err = cbor_value_get_boolean(&repMap, &boolval); VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting boolean value"); res = OCRepPayloadSetPropBool(curPayload, name, boolval); } break; case CborTextStringType: { char *strval = NULL; err = cbor_value_dup_text_string(&repMap, &strval, &len, NULL); VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting string value"); res = OCRepPayloadSetPropStringAsOwner(curPayload, name, strval); } break; case CborByteStringType: { uint8_t* bytestrval = NULL; err = cbor_value_dup_byte_string(&repMap, &bytestrval, &len, NULL); VERIFY_CBOR_SUCCESS(TAG, err, "Failed getting byte string value"); OCByteString tmp = {.bytes = bytestrval, .len = len}; res = OCRepPayloadSetPropByteStringAsOwner(curPayload, name, &tmp); } break; case CborMapType: { OCRepPayload *pl = NULL; err = OCParseSingleRepPayload(&pl, &repMap, false); VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting parse single rep"); res = OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl); } break; case CborArrayType: err = OCParseArray(curPayload, name, &repMap); break; default: OIC_LOG_V(ERROR, TAG, "Parsing rep property, unknown type %d", repMap.type); res = false; } if (type != CborArrayType) { err = (CborError) !res; } VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting value"); if (type != CborMapType && cbor_value_is_valid(&repMap)) { err = cbor_value_advance(&repMap); VERIFY_CBOR_SUCCESS(TAG, err, "Failed advance repMap"); } OICFree(name); name = NULL; } if (cbor_value_is_container(objMap)) { err = cbor_value_leave_container(objMap, &repMap); VERIFY_CBOR_SUCCESS(TAG, err, "Failed to leave container"); } return err; } exit: OICFree(name); OCRepPayloadDestroy(*outPayload); *outPayload = NULL; return err; }