LoRa sending a Struct instead of just var's

I have a struct with a few values in it.

struct myData_t{
    uint8_t myNum;          //Just a number
    char DevID[15];         //Human redable device name
    byte myChomp;           //one byte should do it.
}someData = {120,"MyDevice01",200};

I would ideally like to send the Struct over LoRa without having to send each variable, Is there a way to do this?

I did make an attempt to setup a template similar tot he onbe I used for storing my config in eeprom but that did not seem to work.

template int LoRa_writeAnything(char* data, const T& value){
const byte* p = (const byte*)(const void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
data[i]=*p++;
return i;
}
#define BUFFER_SIZE 124 // Define the payload size here
char txpacket[BUFFER_SIZE];
LoRa_writeAnything(txpacket, someData); //this should take the struct and put it in the buffer
Radio.Send( (uint8_t *)txpacket, strlen(txpacket) ); //send the package out

Any thoughts on how this could be done easier?

A general statement:
It is not recommendable to send a struct over a network. The reason is that the compilers on sender and receiver system could arrange the data differently, e.g. one on byte boundary, the other on 16-bit word boundary or even on 32-bit boundary.

You could have a look for a union instead of a struct.

Regards Achim

An other point could be the big endian / little endian problem. In other words it is important to define the network data interface clearly.

Achim

Thanks, The system I am building is a unitasker and the code is designed only to ever work on the cubecell AB01 but i do hear you and see where there may be a future issues should I rebuild something and use a later compiler version.

I will look in to union Thanks :slight_smile:

I use a CBOR serializer to encode structs and decode them using CBOR.

This has the extra advantage in making your communication resistant to version issues if you add or remove a field. If a field is ‘missing’ the default is used on read. If an unexpected field is found it is just ignored.

To use the reference library above, all that is needed is to add MicroCbor.hpp to your project.

uint8_t buf[80];  // tx temp buffer
entazza::MicroCbor cbor_tx(buf, sizeof(buf));
cbor_tx.startMap();
cbor_tx.add("n", someData.myNum);
cbor_tx.add("id", someData.DevID);
cbor_tx.add("mc", someData.myChomp);
cbor_tx.endMap();

std::cout << "Serialized bytes = " << cbor_tx.bytesSerialized() << std::endl;

struct myData_t readData;
entazza::MicroCbor cbor_rx(buf, sizeof(buf));  // use rx bytes from LoRa
readData.myNum = cbor_rx.get("n", uint8_t(0));
strncpy(readData.DevID, cbor_rx.get("id", "Default"), sizeof(someData.DevID));
readData.myChomp = cbor_rx.get("mc", 0);

std::cout << int(readData.myNum) << ", " << readData.DevID << ", "
          << int(readData.myChomp) << std::endl;