json.c 2.28 KB
#include "json.h"

char* prepare_json_statement(char** data, uint32_t nObservations)
{
	unsigned int i, length, observation_length;
	char *json_statement, *str_aux, *str_aux2;
	length = 17;
	str_aux = join_strings("{\"observations\":[","",length,0,JOIN_NO_FREE);
	for(i = 0; i < nObservations; i++)
	{
		str_aux2 = prepare_observation(data[i],strlen(data[i]));
		observation_length = strlen(str_aux2);
		str_aux = join_strings(str_aux,str_aux2,length,observation_length,JOIN_FREE_MEM); //FREES DATA FROM SENSORS!!!
		length += observation_length;
	}
	length--; //REMOVE LAST ','
	json_statement = join_strings(str_aux,"]}",length,2,JOIN_NO_FREE);
	chHeapFree(str_aux);
	return json_statement;
}

char* prepare_observation(char* observation, uint32_t length)
{
	char *json_data, *str_aux, *str_aux2;
	int value_length = find_next_index(observation,length,','); //EXPECTS FORMATTING!!!
	int timestamp_length = length - (value_length + 1);
	char *value = (char*) chHeapAlloc(NULL,value_length+1);
	char *timestamp = (char*) chHeapAlloc(NULL,timestamp_length+1);
	strncpy(value,observation,value_length);
	strncpy(timestamp,observation+(value_length+1),timestamp_length);
	value[value_length] = '\0';
	timestamp[timestamp_length] = '\0';
	str_aux = join_strings("{\"value\":\"",value,10,value_length,JOIN_NO_FREE);
	str_aux2 = join_strings(str_aux,"\",\"timestamp\":\"",10+value_length,15,JOIN_NO_FREE);
	str_aux2 = join_strings(str_aux2,timestamp,25+value_length,timestamp_length,JOIN_FREE_MEM);
	json_data = join_strings(str_aux2,"\"},",25+value_length+timestamp_length,3,JOIN_NO_FREE);
	chHeapFree(str_aux);
	chHeapFree(str_aux2);
	chHeapFree(value);
	return json_data;
}

uint8_t send_json(char* statement, uint32_t length)
{
	//CHECK CONNECTIVITY
		//RETURN JSON_COMM_ERROR
	//PREPARE HTTP POST
	//SEND POST
		//RETURN JSON_OTHER_ERROR
	//RETURN JSON_POST_OK
}

uint32_t find_next_index(char* string, uint32_t length, char delimiter)
{
	unsigned int i;
	for(i = 0; i < length; i++)
	{
		if(string[i] == delimiter)
		{
			return i;
		}
	}
	return -1;
}

char* join_strings(char* str1, char* str2, uint32_t len1, uint32_t len2, uint8_t free_mem)
{
	char* str = (char*) chHeapAlloc(NULL,len1+len2+1);
	strncpy(str,str1,len1);
	str[len1] = '\0';
	strncat(str,str2,len2);
	if(free_mem)
	{
		free(str1);
		free(str2);
	}
	return str; 
}