LowPowerLab Forum

Hardware support => Moteino => Topic started by: bird_e on October 23, 2014, 12:47:22 PM

Title: struct - looking for best practice
Post by: bird_e on October 23, 2014, 12:47:22 PM
OK,
So I have one Moteino as a gateway talking with a fleet of remotes that have various sensors, that return different quanitity of data readings and data types.   Should I setup a specific struct for each remote, or a single generic struct that can handle all different remotes and data types?   
I hope this makes sense!
thanks!
Bob
Title: Re: struct - looking for best practice
Post by: Felix on October 23, 2014, 02:56:43 PM
Whatever is easiest for you. You could use the first byte to indicate the struct type then read accordingly ... maybe a generic one makes it easier, but if you have a lot of variables that end up unused then you're wasting a lot of space and taking longer transmissions.
Title: Re: struct - looking for best practice
Post by: Kitsibas on October 24, 2014, 03:55:49 AM
QuoteYou could use the first byte to indicate the struct type then read accordingly
Could you write simple example ?
Title: Re: struct - looking for best practice
Post by: Felix on October 24, 2014, 08:14:34 AM
I have 2 struct examples for send and receive here: https://github.com/LowPowerLab/RFM69/tree/master/Examples
You could simply add another 1 byte "signature" field in each struct (first byte). Then when you get a package you read that first byte and cross check it against an enumeration of possible "signatures". Then you do something like:

if (signatureByte == foo)
{
    process radio data as foo structure;
}
else if (signatureByte == bar)
{
    process radio data as bar structure;
}
Title: Re: struct - looking for best practice
Post by: kiwisincebirth on October 26, 2014, 06:42:12 AM
For simplicity of coding I would keep the number of structures to a minimum, having common reusable messages where possible. Below is the structure I have used in my small sensor network. You should use different structures where the message being sent has data which is very different in type.

struct Message {
  byte operation  :  3 ;   // P for Publish / S-set G-get value
  byte locationID :  5 ;   // Defines a Location In House
  byte measure    :  4 ;   // What are we measuring
  long value      : 20 ;   // The value we observed
} message;


Another way to differentiate messages is by length (assuming each message is a different size).

if (radio.DATALEN == sizeof(Message)) {
    Message received = *(Message*)radio.DATA;
    ....
} else if (radio.DATALEN == sizeof( ... )) {
    ....
}