vortigont / pzem-edl

An event-driven library for ESP32 implementing PZEM-004T v3.0 / PZEM-003 / PZEM-017 Modbus-RTU proto
GNU General Public License v3.0
21 stars 4 forks source link

Resetting energy counter #5

Closed ndastur closed 2 years ago

ndastur commented 2 years ago

I can't find a way to reset the power meters back to zero. I.e. a Energy counter reset

From https://github.com/mandulaj/PZEM-004T-v30/blob/master/src/PZEM004Tv30.cpp

/*!
 * PZEM004Tv30::resetEnergy
 *
 * Reset the Energy counter on the device
 *
 * @return success
*/
bool PZEM004Tv30::resetEnergy(){
    uint8_t buffer[] = {0x00, CMD_REST, 0x00, 0x00};
    uint8_t reply[5];
    buffer[0] = _addr;

    setCRC(buffer, 4);
    _serial->write(buffer, 4);

    uint16_t length = receive(reply, 5);

    if(length == 0 || length == 5){
        return false;
    }

    return true;
}
vortigont commented 2 years ago

Hi! You can find an example in pzem_cli code https://github.com/vortigont/pzem-edl/blob/c964cababb6034fd219036760783da17011fed4b/examples/pzem_cli/src/main.cpp#L143-L147

message could be sent directly to the port queue.

I will add additional method to PZEM Class a bit later to implement the same.

ndastur commented 2 years ago

Thank you. I'll try that. Would be good if it worked for individual PZEMs.

vortigont commented 2 years ago

@ndastur, you can check nrgrst branch with new methods PZEM::resetEnergyCounter(), PZPool::resetEnergyCounter()

ndastur commented 2 years ago

Thank you @vortigont. That's brilliant and super fast response. I'll try out the code.

From the manual it seems an status is returned.

2.5 Reset energy
The command format of the master to reset the slave's energy is (total 4 bytes):
Slave address + 0x42 + CRC check high byte + CRC check low byte.
Correct reply: slave address + 0x42 + CRC check high byte + CRC check low byte.
Error Reply: Slave address + 0xC2 + Abnormal code + CRC check high byte + CRC check
low byte

My understanding of abnormal code is the same as all other commands. Just returning a bool would be good.

vortigont commented 2 years ago

Hi @ndastur, pls let me know if it works OK? I do not have access to PZEM devices for now, so can't test it myself.

Just returning a bool would be good.

Sorry, it might be confusing, but PZEM::resetEnergyCounter() can't return result code due to asynchronous nature of the lib. It just enqueues a message and returns immediately. Result code will arrive later and can be accessed via PZEM::getState()->err (i.e. == pzemcmd_t::reset_err). Just need to be careful with order messaging. In my code comment I meant that if result code needs to be handled, for ex. retry "reset command", or do some other action the proper way should be to inject your own code into callback handler. You can check pz003::rx_msg_prettyp() for an inspiration. Asynchronous model implies some complications :)