2025-02-24 17:42:37 +01:00

56 lines
1.4 KiB
C++

#include "NameMsg.h"
#include <string.h>
namespace RoboidControl {
NameMsg::NameMsg(unsigned char networkId, Thing* thing) {
this->networkId = networkId;
this->thingId = thing->id;
if (thing->name == nullptr)
this->nameLength = 0;
else
this->nameLength = (unsigned char)strlen(thing->name);
// the name string in the buffer is not \0 terminated!
char* name = new char[this->nameLength + 1];
for (int i = 0; i < this->nameLength; i++)
name[i] = thing->name[i];
name[this->nameLength] = '\0';
this->name = name;
}
NameMsg::NameMsg(const char* buffer) {
unsigned char ix = 1; // first byte is msg id
this->networkId = buffer[ix++];
this->thingId = buffer[ix++];
this->nameLength = buffer[ix++];
// the name string in the buffer is not \0 terminated!
char* name = new char[this->nameLength + 1];
for (int i = 0; i < this->nameLength; i++)
name[i] = buffer[ix++];
name[this->nameLength] = '\0';
this->name = name;
}
NameMsg::~NameMsg() {
delete[] this->name;
}
unsigned char NameMsg::Serialize(char* buffer) {
if (this->nameLength == 0 || this->name == nullptr)
return 0;
unsigned char ix = 0;
buffer[ix++] = this->id;
buffer[ix++] = this->networkId;
buffer[ix++] = this->thingId;
buffer[ix++] = this->nameLength;
for (int nameIx = 0; nameIx < this->nameLength; nameIx++)
buffer[ix++] = this->name[nameIx];
return ix;
}
} // namespace RoboidControl