buffer.c 2.62 KB
#include "buffer.h"
#include "globals.h"

char** put_message(char* info, char** buf,uint32_t *index, uint32_t *buf_len){

uint32_t i,len;
len=*buf_len;
if(len==*index)
{  
	printf("Joining buffer...\r\n");
	char** buffer=join_buf(buf, buf_len);
	printf("Joined buffer...\r\n");
	buffer[*index]=chHeapAlloc(NULL,strlen(info)+1);
	printf("Memory allocated...\r\n");
	strcpy(buffer[*index],info);
	printf("Data copied...\r\n");
	i=*index+1;
	*index = i;
	return buffer;
}
else
{
	printf("WTF in put_message\r\n");
	buf[*index] = chHeapAlloc(NULL,strlen(info)+1);
	buf[*index]=info;	
	i=*index+1;
	*index = i;
	return buf;
}

}

int check_memory(){

	printf("Memòria disponible en bytes segons:\r\n");
	
	int mem_free=libwismart_GetMemFree_Ram().free;
	//printf("- free_core:    %d     %d\r\n", mem_free, MAX_RAM-mem_free);
	printf("- free:         %d     %d\r\n", libwismart_GetMemFree_Ram().free, MAX_RAM- libwismart_GetMemFree_Ram().free);
	
	
	//int mem_free=20000;
	int mem=MAX_RAM-mem_free;
	printf("mem ocupada=%d\r\n",mem);
	if(mem>=HARD_LIMIT)
	{
		return HARD_REACHED;
	}
	else if(mem >= SOFT_LIMIT){
		return SOFT_REACHED;
	}
	return MEMORY_OK;
}

int send(char** buf, uint32_t *index, uint32_t *size_buf, char *provider_ID, char *sensor_ID){
	printf("abans del JSON statement\r\n");
	printf("index= %d \r\n",*index);
	char* statement=prepare_json_observation_statement(buf, *index);
	uint32_t size = strlen(statement);
	if(buf==NULL)
	{	return 2;	}
	printf("abans del JSON\r\n");
	uint8_t res=send_json(statement, size, provider_ID, sensor_ID);
	chHeapFree(statement);
	int i;
	printf("JSON_POST_OK ?  %d\r\n",res == JSON_POST_OK);
	if(res==JSON_POST_OK){
		for(i=0;i<*index;i++)
		{
			chHeapFree(buf[i]);
		}
		printf("djfkhvldkfjhdñkfgv\r\n");
		if(buf!=NULL)
			chHeapFree(buf);
			
		printf(" posant la mida i l'index a 0\r\n");
		*index=0;
		*size_buf=0;
	}
	return res;
}

//realloc
char** join_buf(char** buf, uint32_t *buf_len){
	char** n_buf;
	int len= *buf_len;
	n_buf=chHeapAlloc (NULL,sizeof (char *) * (len+1));
	int i;
	printf("Start buffer join...\r\n");
	for(i=0; i<len;i++){
		printf("in join_buf for, Asking for %d bytes...\r\n",strlen(buf[i]+1));
		n_buf[i]=chHeapAlloc(NULL,strlen(buf[i])+1);
		printf("in join_buf for, Memory allocated...\r\n");
		strcpy(n_buf[i],buf[i]);
		printf("in join_buf for, Message copied...\r\n");
		chHeapFree(buf[i]);
		printf("in join_buf for, Memory cleared...\r\n");
	}
	printf("All data transferred\r\n");
	if(len!=0)
	{	chHeapFree(buf);	}
	printf("Old buffer cleared\r\n");
	len++;
	*buf_len=len;
	return n_buf;
}