psvanstrom / esphome-p1reader

ESPHome custom component for reading P1 data from electricity meters.
MIT License
251 stars 106 forks source link

Unsigned negative current #90

Closed alfs closed 1 month ago

alfs commented 1 month ago

I noticed current measurement at 6552 amps appearing after installing solar:

image

After troubleshooting, it turns out that the utility meter display is showing negative current (i.e. exporting to grid) when this occurs, but p1reader sends the unsigned value. (2^16)/10 - current explains the numbers around 6552.

This is for the HDLC code, in combination with solar production. All other metrics work as expected (voltage, import/export power) so I assume it's somewhere around https://github.com/psvanstrom/esphome-p1reader/blob/main/p1reader.h#L378

@Megamannen @forsberg if you are exporting power measured by HDLC meter, is the current correctly reported for you?

alfs commented 1 month ago

I added some debugging prints for tag 0x10:

      } else if (tag == 0x10) {
        Serial.readBytes(buffer, 2);
        //value = buffer[0] | buffer[1] << 8; //
        is_signed = true;
        value = buffer[1] | buffer[0] << 8;
        if (strncmp(obis, "31.7.0", 6) == 0)
          ESP_LOGD("hdlc", "tag 0x10 - Value of value is %d", value);

Getting the print

[12:09:30][D][hdlc:400]: tag 0x10 - Value of value is 65506

Value is a 32 bit signed int:

https://github.com/psvanstrom/esphome-p1reader/blob/4de0e9728b3ae6cd255654fbe7f3a3c01a4591f6/p1reader.h#L371

... and packing a 16 bit signed integer into 32 bits then drops the sign.

alfs commented 1 month ago

I implemented a bugfix, see PR https://github.com/psvanstrom/esphome-p1reader/pull/91

Tested and the p1reader now delivers expected negative/export values for current sensors.