Android Code Snippet Send structure from C++ to B4X in prefix mode

I needed to send a structure from an STM32 running an Arduino core to an Android device using Async Streams in prefix mode over Bluetooth. This snippet should work with the 8 bitters too.
Seems to work for me. Better programmers than me are sure to find holes in it so I am waiting to learn.

B4X:
typedef struct __PACKED {
    ...
    ...
} Pkt_Struct;
Pkt_Struct pkt;

void SendPacket() {
    static uint32_t cPktPrefix = sizeof(Pkt_Struct);

    #ifdef __ORDER_LITTLE_ENDIAN__
    Serial2.write((uint8_t)(cPktPrefix & 0xff));
    Serial2.write((uint8_t)((cPktPrefix >> 8) & 0xff));
    Serial2.write((uint8_t)((cPktPrefix >> 16) & 0xff));
    Serial2.write((uint8_t)((cPktPrefix >> 24) & 0xff));
    #else
    Serial2.write(reinterpret_cast<uint8_t*>(&cPktPrefix), sizeof(cPktPrefix));
    #endif

    Serial2.write(reinterpret_cast<uint8_t*>(&pkt), sizeof(Pkt_Struct));
}
 
Top