LWM2M Weather Station

Dependencies:   EthernetInterfaceUpdate mbed-rtos mbed nanoservice_client_1_12_X

resources/IPSO_illuminance.cpp

Committer:
michaeljkoster
Date:
2015-04-13
Revision:
3:12c28025d4a4

File content as of revision 3:12c28025d4a4:

// IPSO Illuminance sensor resource implementation

#include "mbed.h"
#include "nsdl_support.h"

#define ILLUM_RES_ID    "3301/0/5700"
#define ILLUM_RES_RT    "urn:X-ipso:illuminance"

extern Serial pc;
uint8_t illum_max_age = 0; 
uint8_t illum_content_type = 50;

AnalogIn illumSensor(A1);
int illum_percent;
char illumPctString[5];

/* Only GET method allowed */
static uint8_t illuminance_resource_cb(sn_coap_hdr_s *received_coap_ptr, sn_nsdl_addr_s *address, sn_proto_info_s * proto)
{
    sn_coap_hdr_s *coap_res_ptr = 0;
    illum_percent = illumSensor.read() * 100;
    sprintf(illumPctString,"%d", illum_percent);
    pc.printf("illum callback\r\n");
    pc.printf("illum percent %s\r\n", illumPctString);

    if(received_coap_ptr->msg_code == COAP_MSG_CODE_REQUEST_GET)
    {
        coap_res_ptr = sn_coap_build_response(received_coap_ptr, COAP_MSG_CODE_RESPONSE_CONTENT);

        coap_res_ptr->payload_len = strlen(illumPctString);
        coap_res_ptr->payload_ptr = (uint8_t*)illumPctString;
        
        coap_res_ptr->content_type_ptr = &illum_content_type;
        coap_res_ptr->content_type_len = sizeof(illum_content_type);
        
        coap_res_ptr->options_list_ptr = (sn_coap_options_list_s*)nsdl_alloc(sizeof(sn_coap_options_list_s));
        if(!coap_res_ptr->options_list_ptr)
            {
            pc.printf("cant alloc option list for max-age\r\n");
            coap_res_ptr->options_list_ptr = NULL; //FIXME report error and recover
            }
        memset(coap_res_ptr->options_list_ptr, 0, sizeof(sn_coap_options_list_s));
        coap_res_ptr->options_list_ptr->max_age_ptr = &illum_max_age;
        coap_res_ptr->options_list_ptr->max_age_len = sizeof(illum_max_age);

        sn_nsdl_send_coap_message(address, coap_res_ptr);
        nsdl_free(coap_res_ptr->options_list_ptr);
        coap_res_ptr->options_list_ptr = NULL;
        coap_res_ptr->content_type_ptr = NULL;// parser_release below tries to free this memory

    }

    sn_coap_parser_release_allocated_coap_msg_mem(coap_res_ptr);

    return 0;
}

int create_IPSO_illuminance_resource(sn_nsdl_resource_info_s *resource_ptr)
{
    nsdl_create_dynamic_resource(resource_ptr, sizeof(ILLUM_RES_ID)-1, (uint8_t*)ILLUM_RES_ID, sizeof(ILLUM_RES_RT)-1, (uint8_t*)ILLUM_RES_RT, 0, &illuminance_resource_cb, (SN_GRS_GET_ALLOWED));
    return 0;
}