/**
*	Anatole SCHRAMM-HENRY
*	Tim THUREL
*	GROUPE 3
*	
*	UPDATE 10/05/2020 : Ajout du décodage de la température externe
**/

function DecodeByteFirstHalf(data) //Data de type byte
{
	return data & 0x0F;
}

function DecodeByteSecondHalf(data) //Data de type byte
{
	return data >> 4;
}

function DecodeDatePart(data, index)
{
	return {
		year   : data[index]+2000,
		month  : data[index+1],
		day    : data[index+2],
		hour   : data[index+3],
		minute : data[index+4], 
	};
	
}

//10 bits (1 de signe et 9 de valeur) pour
//la partie entière et 6 bits pour la partie fractionnaire
function DecodeQ10_6(data, index)
{
  var temp = (data[index] << 8) | data[index + 1];
	
	//Regarde si la valeur et positive ou négative
	if((temp & 0x8000) !== 0)
	{
		//Valeur négative on fait le complément à deux
		temp = ~temp;
		temp &= 0x7FFF ;
		temp++;
		temp *= -1*Math.pow(2,-6);
	}
	else
	  temp *= Math.pow(2,-6);
	
	
	return temp;
}

function Decoder(bytes, port) {
   // Decode an uplink message from a buffer
   // (array) of bytes to an object of fields.
   var listToReturn = {}, decoded = {}, sensorNbr = 0;
   
   decoded.packetNbr = DecodeByteFirstHalf(bytes[0]);
   decoded.packetId  = DecodeByteSecondHalf(bytes[0]);
   decoded.sensorRow = DecodeByteFirstHalf(bytes[1]);
   decoded.sensorCol = DecodeByteSecondHalf(bytes[1]);
   sensorNbr = decoded.sensorRow * decoded.sensorCol;
   
   var date = DecodeDatePart(bytes, 2);
   
   for (var attrname in date) { decoded[attrname] = date[attrname]; }
   
   decoded.externTemp = DecodeQ10_6(bytes, 7);
   
   for(i = 0; i < sensorNbr*2; i+=2)
   {
	   decoded["t_"+Number(i/2+1)] = DecodeQ10_6(bytes, 9+i);
   }
   
   listToReturn[0] = decoded;

   return listToReturn;
}