// MPP Solar / Voltronic PIP RS232 protocol (2400 8N1). No Arduino dependencies. #pragma once #include #include #include #include namespace mpp { // CRC-16/XMODEM. Bytes that would look like '(', CR or LF are increased by one. inline uint16_t crc(const std::string &data) { uint16_t value = 0; for (unsigned char byte : data) { value ^= byte << 8; for (int bit = 0; bit < 8; bit++) value = value & 0x8000 ? (value << 1) ^ 0x1021 : value << 1; } uint8_t high = value >> 8, low = value & 0xFF; if (high == '(' || high == '\r' || high == '\n') high++; if (low == '(' || low == '\r' || low == '\n') low++; return (high << 8) | low; } // inline std::string frame(const std::string &command) { uint16_t sum = crc(command); return command + char(sum >> 8) + char(sum & 0xFF) + '\r'; } // Takes a reply without the final CR. Returns false on a bad CRC or a NAK. inline bool payload(const std::string &reply, std::string &out) { if (reply.size() < 3 || reply[0] != '(') return false; std::string body = reply.substr(0, reply.size() - 2); uint16_t received = (uint8_t(reply[reply.size() - 2]) << 8) | uint8_t(reply.back()); if (crc(body) != received) return false; out = body.substr(1); return out != "NAK"; } // Names of the numeric QPIGS fields, in the order of the protocol document const char *const QPIGS_FIELDS[] = { "grid_v", "grid_hz", "out_v", "out_hz", "out_va", "out_w", "load_pct", "bus_v", "batt_v", "batt_charge_a", "batt_pct", "heatsink_c", "pv_a", "pv_v", "batt_scc_v", "batt_discharge_a"}; const int QPIGS_COUNT = sizeof(QPIGS_FIELDS) / sizeof(QPIGS_FIELDS[0]); // QPIGS payload to JSON. Returns an empty string if fields are missing. inline std::string qpigsToJson(const std::string &data) { std::string json = "{"; size_t start = 0; for (int i = 0; i < QPIGS_COUNT; i++) { if (start >= data.size()) return ""; size_t end = data.find(' ', start); if (end == std::string::npos) end = data.size(); char number[24]; snprintf(number, sizeof(number), "%g", atof(data.substr(start, end - start).c_str())); json += std::string(i ? "," : "") + "\"" + QPIGS_FIELDS[i] + "\":" + number; start = end + 1; } return json + "}"; } } // namespace mpp