Simvik

Solar inverter: decode a status frame

Check a frame from the inverter and decode its power, voltage and temperature. A medium embedded C problem (Protocols, framing and checksums), run and graded…

medium · Protocols, framing and checksums · framing · checksum · big-endian · product

Product: Solar inverter (Energy)

Requirement. The monitoring box reads a status frame from the solar inverter every second and must never show a value from a damaged frame.

A frame is 9 bytes: 0xAA, the length 6, power in watts (2 bytes, high byte first), grid voltage in tenths of a volt (2 bytes, high byte first), temperature in °C (one signed byte), a status byte, and a checksum: the XOR of every byte from the length to the status byte.

Decode f (of n bytes) into *out and return true, or return false, leaving *out alone, if the frame is not exactly that.

Starter code

bool inverter_decode(const uint8_t *f, size_t n, inverter_t *out) {
  out->power_w = (uint16_t)(f[3] << 8 | f[2]);
  out->volts_x10 = (uint16_t)(f[5] << 8 | f[4]);
  out->temp_c = (int8_t)f[6];
  out->status = f[7];
  return true;
}

Example tests

A sunny afternoon

uint8_t f[9] = { 0xAA, 6, 0x0B, 0xB8, 0x09, 0x60, 45, 0x01, 0 };
for (int i = 1; i < 8; i++) f[8] ^= f[i];
inverter_t v = { 0 };
bool ok = inverter_decode(f, 9, &v);
printf("%d %u %u %d %u\n", ok, v.power_w, v.volts_x10, v.temp_c, v.status);

Expected output:

1 3000 2400 45 1

A byte damaged by noise

uint8_t f[9] = { 0xAA, 6, 0x0B, 0xB8, 0x09, 0x60, 45, 0x01, 0 };
for (int i = 1; i < 8; i++) f[8] ^= f[i];
f[3] ^= 0x10;
inverter_t v = { 0 };
printf("%d\n", inverter_decode(f, 9, &v));

Expected output:

0

Learn it first

More Protocols, framing and checksums problems