I want to create a communication protocol between two microcontrollers, I use class logic that incorporates message types between systems. I want to develop a more simple process of creating new messages by doing something very simple like following
BEGIN_MSG(LinearDriveMsg)
ADD_2BIT(DriveSpeed, speed)
ADD_16BIT(GMath::Position, position.x)
END_MSG
Ideally it would expand to:
BEGIN_MSG(LinearDriveMsg)
BEGIN_SERIALIZER
ADD_SERIALIZER_2BIT(DriveSpeed, speed)
ADD_SERIALIZER_16BIT(GMath::Position, position.x)
END_SERIALIZER
BEGIN_DESERIALIZER
ADD_DESERIALIZER_2BIT(DriveSpeed, speed)
ADD_DESERIALIZER_16BIT(GMath::Position, position.x)
END_DESERIALIZER
END_MSG
And then expand to cpp code
...
bool LinearDriveMsg::deserialize(const uint8_t *incoming_buffer, const uint8_t *incoming_size) override{
if (*incoming_size != getMessageSize())
return false;
_speed = (DriveSpeed)((incoming_buffer[0] & SPEED_MASK) >> SPEED_OFFSET);
weldTwoBytesToInt(&incoming_buffer[1], _position.x);
return true;
}
int LinearDriveMsg::serialize(uint8_t *outgoing_buffer, uint8_t *outgoing_size) const override{
if (*outgoing_size < getMessageSize())
return -1;
outgoing_buffer[0] |= ((uint8_t)_speed << SPEED_OFFSET) & SPEED_MASK;
cutIntToTwoBytes(_position.x, outgoing_buffer + 1, 2);
return getMessageSize();
}
...
I know that doing some advanced preprocessor stuff is pretty tricky but maybe there some way to do this task? It is also possible to adjust the actual cpp code to make it possible (in that way that the efficiency is still ok)