Project

General

Profile

Driver - Byte to Int?

Added by MobileWill about 6 years ago

Hi,

How do you convert back to int when you receive a byte? I have struct with

struct {
byte light;
byte temp;
byte lobat :1;
int battery;

}payload;

For battery I get 199 so it should be 3271
I am not sure how to use readUInt16LE but I am sure that is it.

decode: (raw, cb) ->
#t = raw.readUInt16LE(3, true) & 0x3FF
cb
light: raw[1]
temp: raw[2]
lowbatt: raw[3]
#b = raw.readUINT16LE(5, true)
battery: raw[4]
#battery: b

Thanks for the help.


Replies (6)

RE: Driver - Byte to Int? - Added by gbloice about 6 years ago

In the decode function you need to decode the payload bytes with the correct offsets. For reasons unknown to me the offsets start at 1 instead of the more normal (for software) 0. The entries for light, temp and lobat are all ok, but to read the battery integer value you should use read the 16 bit unsigned integer from offset 4. This gives a decode function of:

decode: (raw, cb) ->
  cb
    light: raw[1]
    temp: raw[2]
    lowbatt: raw[3]
    battery: raw.readUInt16LE(4, true)

As an aside, the use of a whole byte in the payload for the lobatt flag is a bit wasteful. As it’s unlikely that the battery value uses the whole 16 bits, then your payload could encode it in the top bit of that integer and mask it off in the decode function.

RE: Driver - Byte to Int? - Added by MobileWill about 6 years ago

Thanks! Trying it now. I knew I was close, but it was 11pm when I was doing this. ;)

For the Light would it be better to invert it in house mon or the node? I ask because it is reverse. Higher percentage is more darkness.

RE: Driver - Byte to Int? - Added by MobileWill about 6 years ago

I tried it again and it stops housemon from starting, hmm. Looking at the error log now.

RE: Driver - Byte to Int? - Added by MobileWill about 6 years ago

Got it! Lol, I didn’t see that I had uppercase for INT instead of lowercase Int.

Thanks for the help. Time to dive in some more.

Now I need to figure out the sending the temp and convert with decimal place.

RE: Driver - Byte to Int? - Added by gbloice about 6 years ago

To scale the temp value you need to know your “conversion factors”. See the drivers.md item in docs, or have a look at my blog entry where I discuss this for my Airwick based room node.

RE: Driver - Byte to Int? - Added by MobileWill about 6 years ago

I will take a look.

I have it scaled, its just inverted. I think using the map function on the node would work.

light:
      title: 'Light intensity'
      min: 0
      max: 100
      factor: 100 / 255
      scale: 0
      unit: '%'
    (1-6/6)