I am working on an IoT project and using ESP32 as a microcontroller for my devices.
This simple struct in c++ stores the basic state of a device:
struct DeviceState {
char UID[12];
DeviceMode mode;
DeviceErrorType errorCode;
char errorReason[256];
char name[64];
}; // <--- this is line #28
UPDATE:missing types
enum DeviceMode {
DEVICE_MODE_DEFAULT = 0,
DEVICE_MODE_SETUP = 1,
DEVICE_MODE_WORK = 2,
DEVICE_MODE_FAILURE = 4
};
enum DeviceErrorType {
DEVICE_OK = 0b00000000,
DEVICE_FATAL_ERROR = 0b10000001,
DEVICE_INVALID_STATE = 0b00000010,
DEVICE_SENSOR_ERROR = 0b00000011
};
I use char arrays and not char*/std::string/String, because this state data will be saved in ESP32 flash, and i find char arrays a good choice. What I really want and have problems with is that if I want to define a default deviceState (which never changes, and will be copied to the current state when device resets)
DeviceState defaultDeviceState = {
.UID = "undefined",
.mode = DeviceMode::DEVICE_MODE_SETUP, // just an enum
.errorCode = DeviceErrorType::DEVICE_OK, // also enum
.errorReason = "",
.name = "noname"
};
I get the following error message:
WebSetupConsts.h: 28:5: error: C99 designator 'UID' outside aggregate initializer
WebSetupConsts.h: 28:5: error: C99 designator 'errorReason' outside aggregate initializer
WebSetupConsts.h: 28:5: error: C99 designator 'name' outside aggregate initializer
WebSetupConsts.h:28: sorry, unimplemented non-trivial designated initializers not supported
WebSetupConsts.h:28: sorry, unimplemented non-trivial designated initializers not supported
WebSetupConsts.h:28: sorry, unimplemented non-trivial designated initializers not supported
I understand the error message, but for another initialization of a different struct having char* as members, this would work:
ConnectionData connData = {
{ .mqttServer = "4x.1xx.2xx.2xx" },
{ .mqttUsername = "xxxxxxxx" },
{ .mqttPassword = "password" },
.mqttPort = 1883,
{ .wifiSSID = "UPCxxxxxxx" },
{ .wifiPassword = "xxxxxxxxxx" }
};
Wrapping char* members in {} brackets works, but it won't work with char[].
Can someone explain me, why it won't work for char arrays? Is there any way to define a struct having char arrays, and initialize it using designated initializer(member names)?
Using a different initialization won't work either:
DeviceState defaultDeviceState = {
"undefined",
DeviceMode::DEVICE_MODE_SETUP,
DeviceErrorType::DEVICE_OK,
"",
"noname"
};
The error message is:
WebSetupConsts.h: 28:5: error: invalid conversion from 'const char*' to 'char' [-fpermissive]
WebSetupConsts.h: 28:5: error: invalid conversion from 'const char*' to 'char' [-fpermissive]
Then how can I initialize it?
And the last question is: if this is not the best way to store device state, what is?
I know i have too many questions, but I really want to understand c++, thanks for the answers. The compiler is: xtensa-esp32-elf-gcc 1.22.0-80-g6c4433a-5.2.0