/ TheThingsNetwork_Feather / ttn_lmic_dht22_decoder.js
ttn_lmic_dht22_decoder.js
 1  // TTN Decoder for TTN OTAA Feather US915 DHT22 Sketch
 2  // Link: https://github.com/mcci-catena/arduino-lmic/blob/master/examples/ttn-otaa-feather-us915-dht22/ttn-otaa-feather-us915-dht22.ino
 3  function Decoder(bytes, port) {
 4    // Decode an uplink message from a buffer
 5    // (array) of bytes to an object of fields.
 6    var decoded = {};
 7    
 8    // temperature 
 9  
10    rawTemp = bytes[0] + bytes[1] * 256;
11    
12    decoded.degreesC = sflt162f(rawTemp) * 100;
13    
14    // humidity 
15    rawHumid = bytes[2] + bytes[3] * 256;
16    decoded.humidity = sflt162f(rawHumid) * 100;
17    
18    return decoded;
19  }
20  
21  function sflt162f(rawSflt16)
22  	{
23  	// rawSflt16 is the 2-byte number decoded from wherever;
24  	// it's in range 0..0xFFFF
25  	// bit 15 is the sign bit
26  	// bits 14..11 are the exponent
27  	// bits 10..0 are the the mantissa. Unlike IEEE format, 
28  	// 	the msb is transmitted; this means that numbers
29  	//	might not be normalized, but makes coding for
30  	//	underflow easier.
31  	// As with IEEE format, negative zero is possible, so
32  	// we special-case that in hopes that JavaScript will
33  	// also cooperate.
34  	//
35  	// The result is a number in the open interval (-1.0, 1.0);
36  	// 
37  	
38  	// throw away high bits for repeatability.
39  	rawSflt16 &= 0xFFFF;
40  
41  	// special case minus zero:
42  	if (rawSflt16 == 0x8000)
43  		return -0.0;
44  
45  	// extract the sign.
46  	var sSign = ((rawSflt16 & 0x8000) != 0) ? -1 : 1;
47  	
48  	// extract the exponent
49  	var exp1 = (rawSflt16 >> 11) & 0xF;
50  
51  	// extract the "mantissa" (the fractional part)
52  	var mant1 = (rawSflt16 & 0x7FF) / 2048.0;
53  
54  	// convert back to a floating point number. We hope 
55  	// that Math.pow(2, k) is handled efficiently by
56  	// the JS interpreter! If this is time critical code,
57  	// you can replace by a suitable shift and divide.
58  	var f_unscaled = sSign * mant1 * Math.pow(2, exp1 - 15);
59  
60  	return f_unscaled;
61  	}