Page 1 of 7

Support for PZEM 004T Energy monitor

Posted: 25 Jan 2017, 21:25
by mvn77
Is it possible to implement support for the popular PZEM 004T Energy monitor?
https://ru.aliexpress.com/item/PEACEFAI ... e7c8&tpp=1

Re: Support for PZEM 004T Energy monitor

Posted: 26 Jan 2017, 13:15
by papperone
I've oredered one fo those, will give it a try to write a plugin once I will receive...

Re: Support for PZEM 004T Energy monitor

Posted: 08 Mar 2017, 08:08
by mvn77

Re: Support for PZEM 004T Energy monitor

Posted: 26 Jun 2017, 12:30
by Aliki
Hi!

There are what news about support PZEM-004T Energy monitor in EspEasy?

I have a problem: how to transfer the data ( V, I, W, W*h) from PZEM-004T to Domoticz by EspEasy.
There are ways???

I ask the help.)))

Re: Support for PZEM 004T Energy monitor

Posted: 26 Jun 2017, 12:35
by papperone
still waiting mine to arrive and then I'll code a plugin, no worries, just be patient :)

Re: Support for PZEM 004T Energy monitor

Posted: 26 Jun 2017, 12:47
by Aliki
papperone, You already very long wait... Since January 2017. :) June already comes to an end... ;)

Somebody can already has made support ?
Can developers will add support PZEM-004T in the next release ESPEasy?

Re: Support for PZEM 004T Energy monitor

Posted: 26 Jun 2017, 12:57
by papperone
Aliki wrote: 26 Jun 2017, 12:47 papperone, You already very long wait... Since January 2017. :) June already comes to an end... ;)

Somebody can already has made support ?
Can developers will add support PZEM-004T in the next release ESPEasy?
I know, oredered from China, usually 2/3 months but this was was probably lost and reordered in May.... Sorry but in Italy we have a not so good postal service :o

Re: Support for PZEM 004T Energy monitor

Posted: 26 Jun 2017, 13:38
by Aliki
papperone, Yes. It happens to the Chinese mail.)))
There are no problems will wait.
By the way, in firmware WiFi-IoT (paid firmware builder) support this Power Monitor. ... but there is no support Domoticz (very bad and inconvenient support Domoticz).

Re: Support for PZEM 004T Energy monitor

Posted: 08 Aug 2017, 22:31
by Aliki
papperone, any news ? ;)

Re: Support for PZEM 004T Energy monitor

Posted: 24 Aug 2017, 19:52
by papperone
Aliki wrote: 08 Aug 2017, 22:31 papperone, any news ? ;)
Believe it or not got my sensor today in my mailbox!!
Will start to test it to understand how it works then will translate it into a plugin, stay tuned ;)

Re: Support for PZEM 004T Energy monitor

Posted: 08 Sep 2017, 00:13
by Aliki
papperone wrote: 24 Aug 2017, 19:52
Aliki wrote: 08 Aug 2017, 22:31 papperone, any news ? ;)
Will start to test it to understand how it works then will translate it into a plugin, stay tuned ;)
Hi ! Have any news ? :)

Re: Support for PZEM 004T Energy monitor

Posted: 08 Sep 2017, 01:11
by papperone
Aliki wrote: 08 Sep 2017, 00:13
papperone wrote: 24 Aug 2017, 19:52
Aliki wrote: 08 Aug 2017, 22:31 papperone, any news ? ;)
Will start to test it to understand how it works then will translate it into a plugin, stay tuned ;)
Hi ! Have any news ? :)
still testing it, the serial interface with PZEM 004T is a little weird and for sure non-standard; basic library sems to work but not stable, so I'm actually rewriting basic code in order to have a more reliable plugin :)
as soon as it's kind of "working state" I'll publish it in the Playground, dont' worry!

Re: Support for PZEM 004T Energy monitor

Posted: 13 Sep 2017, 10:59
by papperone
Plugin is in a kinda of working status, this sensor has some "features" which I try to adapt:

1) sensor library is quite messy and requests a manual update of the SoftwareSerial library for ESP8266 to v3.2.3
2) the module I do have fails all the readings if it's not connected to the main AC line
3) while it's ok to have V A and W to zero when no readings, the Energy reading (which is accumulated and saved on the flash memory of the module) shoudl be reported
4) to avoid point 3) issue I decided to check if the reading was OK and (only for the Energy) to retain old device value in order to always show the accumulated Wh
5) in case of no AC line to the module, the module reading are quite slower and thus serial-comm is used the ESP8266 become slugghish (so don't blame plugin but module!)
6) If you select wrong GPIOs you can experience an almost unusable ESP8266 (somehow SoftwareSerial setup to the wrong pins generate this unresponsivness)

below a current screenshot; I'm waiting the GitHub to be cleaned up after vacation (I see too many PU request pending) to avoid flooding with more requests.
Capture.JPG
Capture.JPG (31.01 KiB) Viewed 1607525 times

Re: Support for PZEM 004T Energy monitor

Posted: 15 Sep 2017, 20:57
by reliable_bob
Hello!
I, too, are waiting for the plug-in to the PZEM. Any news?

Re: Support for PZEM 004T Energy monitor

Posted: 15 Sep 2017, 23:23
by papperone
guys I woud like to upload the pluing to GitHub playground but I've this error which I can't understand how to fix:
Capture.JPG
Capture.JPG (12.13 KiB) Viewed 1607465 times
and if I try to commit the new plugin "_P171..." is added to the pull request of the previous "_P170..." updated which are waiting to be merged more than 1 month...

can someone help??

Re: Support for PZEM 004T Energy monitor

Posted: 17 Sep 2017, 11:29
by papperone
_P171 PZEM-004T submitted in the Playground...

please provide feedback/bugs in order to eventually fix them before to move to the main branch!

Re: Support for PZEM 004T Energy monitor

Posted: 17 Sep 2017, 18:31
by reliable_bob
papperone wrote: 17 Sep 2017, 11:29 _P171 PZEM-004T submitted in the Playground...

please provide feedback/bugs in order to eventually fix them before to move to the main branch!
Hello and thank you for what you are doing!
I can try to test, but I do not understand where and how to download the firmware. And more, if it is possible, please give the scheme of connecting the ESP to PZEM004

Re: Support for PZEM 004T Energy monitor

Posted: 17 Sep 2017, 18:39
by papperone
reliable_bob wrote: 17 Sep 2017, 18:31
papperone wrote: 17 Sep 2017, 11:29 _P171 PZEM-004T submitted in the Playground...

please provide feedback/bugs in order to eventually fix them before to move to the main branch!
Hello and thank you for what you are doing!
I can try to test, but I do not understand where and how to download the firmware. And more, if it is possible, please give the scheme of connecting the ESP to PZEM004
You nee to download from GITHUB repository "playground" the pluing, as it's not part (yet) of the standard package.
Then you need to compile by yourself the firmware using Arduino IDE or Platformio (plenty of instruction on the Wiki).
Connection is pretty straightforward:
- VCC to 5V
- GND to GND
- TX to a free GPIO
- RX to a free GPIO
the last 2 GPIO then needs to be configured in the device page as SoftwareSerial is used.

Re: Support for PZEM 004T Energy monitor

Posted: 18 Sep 2017, 19:08
by reliable_bob
Hey. I tried, but the result is zero. Maybe I did something wrong. I did this:
1. I took the file ESPEasy.ino from the package ESPEasy_v2.0.0-dev11 and opened it in Arduino IDE.
2. Created a new tab, named it _P171_PZEM-004T and inserted the contents into it by the link https://github.com/papperone/ESPEasyPlu ... M-004T.ino
3. Compiled the firmware file.
4. Filled the firmware in the ESP12-е.
5. In the settings of the web interface, configure the device, chose the GPIO for the SoftwareSerial.
However, all indications are zero ...

Re: Support for PZEM 004T Energy monitor

Posted: 19 Sep 2017, 00:06
by papperone
reliable_bob wrote: 18 Sep 2017, 19:08 Hey. I tried, but the result is zero. Maybe I did something wrong. I did this:
1. I took the file ESPEasy.ino from the package ESPEasy_v2.0.0-dev11 and opened it in Arduino IDE.
2. Created a new tab, named it _P171_PZEM-004T and inserted the contents into it by the link https://github.com/papperone/ESPEasyPlu ... M-004T.ino
3. Compiled the firmware file.
4. Filled the firmware in the ESP12-е.
5. In the settings of the web interface, configure the device, chose the GPIO for the SoftwareSerial.
However, all indications are zero ...
try to swap TX and RX

Re: Support for PZEM 004T Energy monitor

Posted: 19 Sep 2017, 18:20
by reliable_bob
Well, in general, the situation is as follows.
There is NodeMCU and PZEM-004T.
The system works, but only if you apply power to the PZEM after the NodeMCU boots up. Otherwise, NodeMCU simply does not load.
And further. Your code may have been created from an older version of the library. When using the new version of the library, an error occurs when compiling in Arduino IDE.

Re: Support for PZEM 004T Energy monitor

Posted: 19 Sep 2017, 21:02
by papperone
reliable_bob wrote: 19 Sep 2017, 18:20 Well, in general, the situation is as follows.
There is NodeMCU and PZEM-004T.
The system works, but only if you apply power to the PZEM after the NodeMCU boots up. Otherwise, NodeMCU simply does not load.
And further. Your code may have been created from an older version of the library. When using the new version of the library, an error occurs when compiling in Arduino IDE.
I'm using latest version as I forket the GIT of the library...
which errors did you get so I can try to help you figure it out?
if it's related to SoftwareSerial, indeed the Arduino IDE push you to install a "newer" version which is buggy, so you need to downgrate this specific library to previous (which is again the officially GITHUB supported) in order to compile correctly...
(sorry I forgot to mention this!!)

PS; in my configuration the node boots up perfectly despite I applyed 230VAC or not to PZEM, just the sensor is unresponsive and sluggish as I already explained!

Re: Support for PZEM 004T Energy monitor

Posted: 08 Oct 2017, 16:42
by coldman
papperone wrote: 13 Sep 2017, 10:59 Plugin is in a kinda of working status, this sensor has some "features" which I try to adapt:

1) sensor library is quite messy and requests a manual update of the SoftwareSerial library for ESP8266 to v3.2.3
2) the module I do have fails all the readings if it's not connected to the main AC line
3) while it's ok to have V A and W to zero when no readings, the Energy reading (which is accumulated and saved on the flash memory of the module) shoudl be reported
4) to avoid point 3) issue I decided to check if the reading was OK and (only for the Energy) to retain old device value in order to always show the accumulated Wh
5) in case of no AC line to the module, the module reading are quite slower and thus serial-comm is used the ESP8266 become slugghish (so don't blame plugin but module!)
6) If you select wrong GPIOs you can experience an almost unusable ESP8266 (somehow SoftwareSerial setup to the wrong pins generate this unresponsivness)

below a current screenshot; I'm waiting the GitHub to be cleaned up after vacation (I see too many PU request pending) to avoid flooding with more requests.
Capture.JPG
Great job! Thanks.
but how to add those values to Domoticz?
if selected Dummy - Electric - only voltage

upd: also, not all values are often displayed
2017-10-08_20-10-37.png
2017-10-08_20-10-37.png (15.07 KiB) Viewed 1612432 times
2017-10-08_20-01-36.png
2017-10-08_20-01-36.png (15.04 KiB) Viewed 1612432 times
2017-10-08_20-00-31.png
2017-10-08_20-00-31.png (14.99 KiB) Viewed 1612432 times

Code: Select all

2017-10-08 19:30:16	216.00;1.99;0.00;985.00
2017-10-08 19:29:15	212.50;1.99;0.00;985.00
2017-10-08 19:28:16	215.20;0.00;0.00;985.00
2017-10-08 19:27:14	209.80;1.99;0.00;985.00
2017-10-08 19:26:13	210.50;1.94;0.00;978.00
2017-10-08 19:25:13	205.10;1.94;0.00;972.00
2017-10-08 19:24:13	211.40;1.99;0.00;965.00
2017-10-08 19:23:16	214.10;0.00;0.00;0.00
2017-10-08 18:56:02	205.80;1.95;0.00;726.00
2017-10-08 18:55:02	207.50;1.95;0.00;726.00
2017-10-08 18:54:01	203.70;1.94;0.00;726.00
2017-10-08 18:53:01	204.00;1.91;0.00;726.00
2017-10-08 18:52:02	208.90;0.00;0.00;726.00
2017-10-08 18:51:00	208.00;1.94;0.00;726.00
2017-10-08 18:49:58	207.10;1.97;370.00;726.00
2017-10-08 18:48:59	208.30;1.96;0.00;719.00
2017-10-08 18:48:00	216.00;0.00;0.00;712.00
2017-10-08 18:46:59	203.20;1.92;0.00;705.00
2017-10-08 18:46:00	203.30;1.95;0.00;638.00
2017-10-08 18:44:58	195.70;1.89;369.00;638.00
2017-10-08 18:43:59	201.60;1.89;0.00;638.00
2017-10-08 18:42:57	195.60;1.86;365.00;638.00
2017-10-08 18:41:56	193.10;1.90;359.00;638.00
2017-10-08 18:40:56	196.90;1.91;373.00;638.00
2017-10-08 18:39:57	209.30;1.99;0.00;638.00

Re: Support for PZEM 004T Energy monitor

Posted: 08 Nov 2017, 10:03
by aleph0
Hi, and thanks for making this nice plugin !

As I had to do some searching to finally compile and install it, here is a all-in-one summary of what needs to be done :
1/ Install and configure platform.io according to the instructions here :
https://www.letscontrolit.com/wiki/inde ... Platformio
then
https://www.letscontrolit.com/wiki/inde ... platformio

2/ Download the source tree from here :
https://github.com/letscontrolit/ESPEas ... .0.0-dev12 (or later version as there are being developed

3/ Download the plugin source from here and copy it in the main source
https://github.com/papperone/ESPEasyPlu ... M-004T.ino

4/ Download PZEM004T library from here and copy it in the lib subdirectory of the main source
https://github.com/olehs/PZEM004T

5/ Download SofwareSerial library in version 3.2.3 from here and copy it in the lib subdirectory of the main source
https://github.com/plerup/espsoftwarese ... /tag/3.2.3

6/ Update the library.json file that came from the softwareserial library with the following content :

Code: Select all

{
    "name": "EspSoftwareSerial",
    "version": "3.2.3",
    "keywords": [
      "serial", "io", "softwareserial"
    ],
    "description": "Implementation of the Arduino software serial for ESP8266.",
    "repository":
    {
        "type": "git",
        "url": "https://github.com/plerup/espsoftwareserial"
    },
    "frameworks": "arduino",
    "platforms": "espressif8266"
}
(version was missing and platforms mispelled :( )

After that, I was able to compile espeasy with the plugin and send it to the esp via OTA :)

Re: Support for PZEM 004T Energy monitor

Posted: 08 Nov 2017, 10:13
by aleph0
Some remarks/comments about the plugin itself :

- RX and TX indications on the device page are somewhat confusing as there are referring to the pins on the esp side, so they have to be reversed compared to the pzem side. I changed the text in the version below to make it clearer
- I added some more debugging lines to make it easier to follow-up what's going on
- I noticed pzem answers in 2s when 220V is applied to the module and in 12s when no power is applied. So don't use polling time faster than 15s ; I dunno if there is a way to block that on the web page or at least to display it somewhere.

Now some problems I dunno how to fix by myself (yet ;) ) as I'm a noob is espeasy programming !
- pzem initialisation is done at boot of the esp only, so any further changes in the GPIO pins are not taken in consideration. IMHO It should be done after any config change
- I made some experiments with two modules on the same esp, as I'm trying to build a 3 phase power analyser and the plugin does not handle this correctly : Only the first one is initialised correctly and both readings are made from the 1st one. Help would be very appreciated to remove this limitation

Thanks again from this great plugin :)

Code: Select all

//#######################################################################################################
//################### Plugin 171 PZEM-004T AC Current and Voltage measurement sensor ####################
//#######################################################################################################
//
// This plugin is interfacing with PZEM-004T Sesor with softserial communication as the sensor
// has an UART pinout (TX/RX/VCC/GND)
//

#ifdef PLUGIN_BUILD_TESTING

#include <SoftwareSerial.h>
#include <PZEM004T.h>
PZEM004T *Plugin_171_pzem;
IPAddress pzemIP(192,168,1,1);    // required by the library but not used (dummy value)

#define PLUGIN_171
#define PLUGIN_ID_171        171
#define PLUGIN_171_DEBUG     true   //activate extra log info in the debug
#define PLUGIN_NAME_171       "Voltage & Current (AC) - PZEM-004T [TESTING]"
#define PLUGIN_VALUENAME1_171 "Voltage (V)"
#define PLUGIN_VALUENAME2_171 "Current (A)"
#define PLUGIN_VALUENAME3_171 "Power (W)"
#define PLUGIN_VALUENAME4_171 "Energy (Wh)"

// local parameter for this plugin
#define PZEM_MAX_ATTEMPT      3

boolean Plugin_171(byte function, struct EventStruct *event, String& string)
{
  boolean success = false;

  switch (function)
  {
    case PLUGIN_DEVICE_ADD:
      {
        Device[++deviceCount].Number = PLUGIN_ID_171;
        Device[deviceCount].Type = DEVICE_TYPE_DUAL;
        Device[deviceCount].VType = SENSOR_TYPE_QUAD;
        Device[deviceCount].Ports = 0;
        Device[deviceCount].PullUpOption = false;
        Device[deviceCount].InverseLogicOption = false;
        Device[deviceCount].FormulaOption = true;
        Device[deviceCount].ValueCount = 4;
        Device[deviceCount].SendDataOption = true;
        Device[deviceCount].TimerOption = true;
        Device[deviceCount].GlobalSyncOption = false;
        break;
      }

    case PLUGIN_GET_DEVICENAME:
      {
        string = F(PLUGIN_NAME_171);
        break;
      }

    case PLUGIN_GET_DEVICEVALUENAMES:
      {
        strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[0], PSTR(PLUGIN_VALUENAME1_171));
        strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[1], PSTR(PLUGIN_VALUENAME2_171));
        strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[2], PSTR(PLUGIN_VALUENAME3_171));
        strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[3], PSTR(PLUGIN_VALUENAME4_171));
        break;
      }

    case PLUGIN_WEBFORM_LOAD:
      {
        addFormNote(string, F("SoftSerial: 1st=to TX-Pin, 2nd=to RX-Pin"));
        success = true;
        break;
      }

    case PLUGIN_WEBFORM_SAVE:
      {
        success = true;
        break;
      }

    case PLUGIN_READ:
      {
        if (PLUGIN_171_DEBUG) {
          String log = F("PZEM004T: Reading started.");
          addLog(LOG_LEVEL_INFO, log);
        }
    		float pzVoltage = Plugin171_ReadVoltage();
    		float pzCurrent = Plugin171_ReadCurrent();
    		float pzPower   = Plugin171_ReadPower();
    		float pzEnergy  = Plugin171_ReadEnergy();
        //-------------------------------------------------------------------
        // readings can be ZERO if there's no AC input on the module.
        // in this case V A and W are reported correctly as ZERO but
        // the accumulated Energy paramenter will not be saved so to
        // preserve previous value
        //-------------------------------------------------------------------
        UserVar[event->BaseVarIndex]     = pzVoltage;
        UserVar[event->BaseVarIndex + 1] = pzCurrent;
        UserVar[event->BaseVarIndex + 2] = pzPower;
        if (pzEnergy>=0)  UserVar[event->BaseVarIndex + 3] = pzEnergy;
        if (PLUGIN_171_DEBUG) {
          String log = F("PZEM004T: Voltage="); log += pzVoltage; log += F(" V");
          addLog(LOG_LEVEL_INFO, log);
          log = F("PZEM004T: Current="); log += pzCurrent; log += F(" A");
          addLog(LOG_LEVEL_INFO, log);
          log = F("PZEM004T: Power="); log += pzPower; log += F(" W");
          addLog(LOG_LEVEL_INFO, log);
          log = F("PZEM004T: Energy="); log += pzEnergy; log += F(" Wh");
          addLog(LOG_LEVEL_INFO, log);
        }
        success = true;
        break;
      }

    case PLUGIN_INIT:
      {
        if (!Plugin_171_pzem)
        {
          int pzemRXpin = Settings.TaskDevicePin1[event->TaskIndex];
          int pzemTXpin = Settings.TaskDevicePin2[event->TaskIndex];
          Plugin_171_pzem = new PZEM004T(pzemRXpin, pzemTXpin);
          if (PLUGIN_171_DEBUG) {
            String log = F("PZEM004T: Object Initialized");
            log += F(" - RX-Pin="); log += pzemRXpin;
            log += F(" - TX-Pin="); log += pzemTXpin;
            addLog(LOG_LEVEL_INFO, log);
          }
		      Plugin_171_pzem->setAddress(pzemIP);  // This initializes the PZEM004T library using a (useless) fake IP address
          if (PLUGIN_171_DEBUG) {
            String log = F("PZEM004T: setup address (dummy)");
            log += F(" - "); log += pzemIP;
            addLog(LOG_LEVEL_INFO, log);
          }
        }
        success = true;
        break;
      }

  }
  return success;
}

//************************************//
//***** reading values functions *****//
//************************************//

// NOTE: readings are attempted only PZEM_AMX_ATTEMPT times

float Plugin171_ReadVoltage() {
  int counter = 0;
	float reading = -1.0;
	do {
		reading = Plugin_171_pzem->voltage(pzemIP);
		wdt_reset();
		counter++;
	} while (counter < PZEM_MAX_ATTEMPT && reading < 0.0);
  if (reading == -1) reading = 0;
	return reading;
}

float Plugin171_ReadCurrent() {
	int counter = 0;
	float reading = -1.0;
	do {
		reading = Plugin_171_pzem->current(pzemIP);
		wdt_reset();
		counter++;
	} while (counter < PZEM_MAX_ATTEMPT && reading < 0.0);
  if (reading == -1) reading = 0;
  return reading;
}

float Plugin171_ReadPower() {
  int counter = 0;
	float reading = -1.0;
	do {
		reading = Plugin_171_pzem->power(pzemIP);
		wdt_reset();
		counter++;
	} while (counter < PZEM_MAX_ATTEMPT && reading < 0.0);
  if (reading == -1) reading = 0;
  return reading;
}

float Plugin171_ReadEnergy() {
	int counter = 0;
	float reading = -1.0;
	do {
		reading = Plugin_171_pzem->energy(pzemIP);
		wdt_reset();
		counter++;
	} while (counter < PZEM_MAX_ATTEMPT && reading < 0.0);
	return reading;
}
#endif

Re: Support for PZEM 004T Energy monitor

Posted: 08 Nov 2017, 10:27
by aleph0
coldman wrote: 08 Oct 2017, 16:42 but how to add those values to Domoticz?
if selected Dummy - Electric - only voltage
I didn't find a clean way to get the values, but a workaroud : In domoticz I defined a dummy of type "3 phase Ampers" and I gave the idx of it to pzem plugin in espeasy. Then I used the following code in domoticz to read from the 3ph amp dummy and dispatch the infos in "real" devices :

Code: Select all

local dev_HC= "Heures creuses EDF"
local dev_pzem="pzem L1" 
local dev_V="Tension L1"
local dev_A="Amp L1"
local dev_W="Power L1"

--------------------------------------------------------------------------------
--                     Function library                              --
--------------------------------------------------------------------------------
function UpdateDev(device,nvalue,svalues)
    --Met à jour un device numérique Domoticz
    commandArray[#commandArray+1] = {['UpdateDevice'] = otherdevices_idx[device]..'|'..tostring(nvalue)..'|'..tostring(svalues)}
end

function UpdateP1(device,HC,conso,prod,freq)
    -- Met à jour le P1 smart counter
    -- device : nom du compteur
    -- HC     : "On" si heures creuses, "Off" si heures pleines
    -- conso  : consommation instantannée
    -- prod   : production instantannée
    -- freq   : frequence d'exécution du script (en minutes) 
    
    local u1, u2, p1, p2
    local dbg=0
    
    u1, u2, p1, p2 = string.match(otherdevices_svalues[device],"(.-);(.-);(.-);(.-);.*")
    
    -- Utile pour les compteurs nouvellement crées
    u1=u1 or 0
    u2=u2 or 0
    p1=p1 or 0
    p2=p2 or 0

    if dbg == 1 then
        print("Mise à jour de "..tostring(device))
        print("u1 "..tostring(u1))
        print("u2 "..tostring(u2))
        print("p1 "..tostring(p1))
        print("p2 "..tostring(p2))
        print("conso "..tostring(conso))
        print("prod "..tostring(prod))
    end

    if otherdevices[HC] == 'Off' then
        -- svalue=USAGE1;USAGE2;RETURN1;RETURN2;CONS;PROD
        commandArray[#commandArray+1] = {['UpdateDevice'] = otherdevices_idx[device]..'|0|'..tostring(u1+conso*freq/60)..';'..tostring(u2)..';'..tostring(p1+prod*freq/60)..';'..tostring(p2)..';'..tostring(conso)..';'..tostring(prod)}
    else
        commandArray[#commandArray+1] = {['UpdateDevice'] = otherdevices_idx[device]..'|0|'..tostring(u1)..';'..tostring(u2+conso*freq/60)..';'..tostring(p1)..';'..tostring(p2+prod*freq/60)..';'..tostring(conso)..';'..tostring(prod)}
    end
end

function pzem_read(pzem,HC,dev_V,dev_A,dev_W,freq)
    --[[read information from a pzem in a 3ph amp device
    and dispatch voltage, current and power measures in corresponding devices
    Input :
    pzem : type 3PH Amp
    HC : switch "On"=Happy hours
    
    Output :
    dev_V : type Tension
    dev_A : type Ampers
    dev_W : P1 smart counter
    freq : measure frequency of the pzem, in minutes. Must match the delay parameter of the esp
    ]]--

    local val_V,val_A,val_W,val_Wh

    val_V,val_A,val_W,val_Wh=string.match(otherdevices_svalues[pzem],"(.-);(.-);(.-);(.-)")
    UpdateDev(dev_V,0,val_V)
    UpdateDev(dev_A,0,val_A)
    UpdateP1(dev_W,HC,val_W,0,1)
end

commandArray = {}

if devicechanged[dev_pzem] then pzem_read(dev_pzem,dev_HC,dev_V,dev_A,dev_W,1) end

return commandArray

Hope it helps !

Re: Support for PZEM 004T Energy monitor

Posted: 08 Nov 2017, 12:30
by papperone
thanks for your feedback...
at the moment the plugin is not build to allow multiple sensors connected to single ESP8266; no having more than one I can't test it :(

about PIN naming it's just a matter of convention, as for me I believe it's more relevant to map the pin function of ESP8266 (same when you connect an FTDI interface to program ESP8266 module, you need to link RX to TX and viceversa)...
I'm open to suggestion here, if the majority thinks it's better to reverse the naming so RX means on PZEM and not on ESP8266 we can submit such pull-request on github! :mrgreen:

Re: Support for PZEM 004T Energy monitor

Posted: 10 Nov 2017, 20:23
by ut1545
Hello all,

Just a few words about PZEM 004T:

I have implement one PZEM connected to a ESP-12F and running a very simple custom sketch. It is installed at very beginning of the incoming electrical line so, it should measure the same as the meter of electrical provider. After 11 months comparing the two meters, I can say that it is very precise: around 0,45% difference!!!

So, in my opinion, it is a very good device in order to measure electrical consumption. I will be next two months on travel but I will try to migrate my sketch to ESP Easy + PZEM plugin. I will post any relevant information if it can help....

Also, let me thank all of you for your efforts in create this ESP Plugin. Great job !!!!

Regards,

Re: Support for PZEM 004T Energy monitor

Posted: 14 Nov 2017, 21:56
by aleph0
papperone wrote: 08 Nov 2017, 12:30 at the moment the plugin is not build to allow multiple sensors connected to single ESP8266; no having more than one I can't test it :(
Could you give me some hints of what should be done to allow that ? I'd try to implement it and contribute back as I can test it ;)

Re: Support for PZEM 004T Energy monitor

Posted: 15 Nov 2017, 06:55
by papperone
Well if you are not familiar with the structure of ESPEasy won't be that simple :(
I ned as well to make other pluging (for my personal needs) able to use multiple devices and still no time to devote to programming this...

Re: Support for PZEM 004T Energy monitor

Posted: 15 Nov 2017, 21:38
by Germil
Hello, im New in forum and If that can help, Ill be glad.
https://github.com/apreb/eNode

Re: Support for PZEM 004T Energy monitor

Posted: 17 Nov 2017, 15:11
by TD-er
Germil wrote: 15 Nov 2017, 21:38 Hello, im New in forum and If that can help, Ill be glad.
https://github.com/apreb/eNode
Hmm, that looks like a nice project to read about :)

Re: Support for PZEM 004T Energy monitor

Posted: 19 Nov 2017, 18:13
by aleph0
Hi all,

here is a fix for the problem of parameters being taken into account only at boot. Now things can be changed on the fly by re-doing initialisation at every "submit" of the form :

Code: Select all

//#######################################################################################################
//################### Plugin 171 PZEM-004T AC Current and Voltage measurement sensor ####################
//#######################################################################################################
//
// This plugin is interfacing with PZEM-004T Sesor with softserial communication as the sensor
// has an UART pinout (TX/RX/VCC/GND)
//

#ifdef PLUGIN_BUILD_TESTING

#include <SoftwareSerial.h>
#include <PZEM004T.h>
PZEM004T *Plugin_171_pzem;
IPAddress pzemIP(192,168,1,1);    // required by the library but not used (dummy value)

boolean Plugin_171_init = false;

#define PLUGIN_171
#define PLUGIN_ID_171        171
#define PLUGIN_171_DEBUG     true   //activate extra log info in the debug
#define PLUGIN_NAME_171       "Voltage & Current (AC) - PZEM-004T [TESTING]"
#define PLUGIN_VALUENAME1_171 "Voltage (V)"
#define PLUGIN_VALUENAME2_171 "Current (A)"
#define PLUGIN_VALUENAME3_171 "Power (W)"
#define PLUGIN_VALUENAME4_171 "Energy (Wh)"

// local parameter for this plugin
#define PZEM_MAX_ATTEMPT      3

boolean Plugin_171(byte function, struct EventStruct *event, String& string)
{
  boolean success = false;

  switch (function)
  {
    case PLUGIN_DEVICE_ADD:
      {
        Device[++deviceCount].Number = PLUGIN_ID_171;
        Device[deviceCount].Type = DEVICE_TYPE_DUAL;
        Device[deviceCount].VType = SENSOR_TYPE_QUAD;
        Device[deviceCount].Ports = 0;
        Device[deviceCount].PullUpOption = false;
        Device[deviceCount].InverseLogicOption = false;
        Device[deviceCount].FormulaOption = true;
        Device[deviceCount].ValueCount = 4;
        Device[deviceCount].SendDataOption = true;
        Device[deviceCount].TimerOption = true;
        Device[deviceCount].GlobalSyncOption = false;
        break;
      }

    case PLUGIN_GET_DEVICENAME:
      {
        string = F(PLUGIN_NAME_171);
        break;
      }

    case PLUGIN_GET_DEVICEVALUENAMES:
      {
        strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[0], PSTR(PLUGIN_VALUENAME1_171));
        strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[1], PSTR(PLUGIN_VALUENAME2_171));
        strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[2], PSTR(PLUGIN_VALUENAME3_171));
        strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[3], PSTR(PLUGIN_VALUENAME4_171));
        break;
      }

    case PLUGIN_WEBFORM_LOAD:
      {
        addFormNote(string, F("SoftSerial: 1st=to TX-Pin, 2nd=to RX-Pin"));
        success = true;
        break;
      }

    case PLUGIN_WEBFORM_SAVE:
      {
        Plugin_171_init = false;
        success = true;
        break;
      }

    case PLUGIN_READ:
      {
        if (PLUGIN_171_DEBUG) {
          String log = F("PZEM004T: Reading started.");
          addLog(LOG_LEVEL_INFO, log);
        }
    		float pzVoltage = Plugin171_ReadVoltage();
    		float pzCurrent = Plugin171_ReadCurrent();
    		float pzPower   = Plugin171_ReadPower();
    		float pzEnergy  = Plugin171_ReadEnergy();
        //-------------------------------------------------------------------
        // readings can be ZERO if there's no AC input on the module.
        // in this case V A and W are reported correctly as ZERO but
        // the accumulated Energy paramenter will not be saved so to
        // preserve previous value
        //-------------------------------------------------------------------
        UserVar[event->BaseVarIndex]     = pzVoltage;
        UserVar[event->BaseVarIndex + 1] = pzCurrent;
        UserVar[event->BaseVarIndex + 2] = pzPower;
        if (pzEnergy>=0)  UserVar[event->BaseVarIndex + 3] = pzEnergy;
        if (PLUGIN_171_DEBUG) {
          String log = F("PZEM004T: Voltage="); log += pzVoltage; log += F(" V");
          addLog(LOG_LEVEL_INFO, log);
          log = F("PZEM004T: Current="); log += pzCurrent; log += F(" A");
          addLog(LOG_LEVEL_INFO, log);
          log = F("PZEM004T: Power="); log += pzPower; log += F(" W");
          addLog(LOG_LEVEL_INFO, log);
          log = F("PZEM004T: Energy="); log += pzEnergy; log += F(" Wh");
          addLog(LOG_LEVEL_INFO, log);
        }
        success = true;
        break;
      }

    case PLUGIN_INIT:
      {
        if (!Plugin_171_init)
        {
          int pzemRXpin = Settings.TaskDevicePin1[event->TaskIndex];
          int pzemTXpin = Settings.TaskDevicePin2[event->TaskIndex];
          Plugin_171_pzem = new PZEM004T(pzemRXpin, pzemTXpin);
          if (PLUGIN_171_DEBUG) {
            String log = F("PZEM004T: Object Initialized");
            log += F(" - RX-Pin="); log += pzemRXpin;
            log += F(" - TX-Pin="); log += pzemTXpin;
            addLog(LOG_LEVEL_INFO, log);
          }
		      Plugin_171_pzem->setAddress(pzemIP);  // This initializes the PZEM004T library using a (useless) fake IP address
          if (PLUGIN_171_DEBUG) {
            String log = F("PZEM004T: setup address (dummy)");
            log += F(" - "); log += pzemIP;
            addLog(LOG_LEVEL_INFO, log);
          }
        }
        Plugin_171_init = true;
        success = true;
        break;
      }

  }
  return success;
}

//************************************//
//***** reading values functions *****//
//************************************//

// NOTE: readings are attempted only PZEM_AMX_ATTEMPT times

float Plugin171_ReadVoltage() {
  int counter = 0;
	float reading = -1.0;
	do {
		reading = Plugin_171_pzem->voltage(pzemIP);
		wdt_reset();
		counter++;
	} while (counter < PZEM_MAX_ATTEMPT && reading < 0.0);
  if (reading == -1) reading = 0;
  if (PLUGIN_171_DEBUG) {
    String log = F("Voltage try :"); log += counter;
    addLog(LOG_LEVEL_DEBUG, log);
  }
	return reading;
}

float Plugin171_ReadCurrent() {
	int counter = 0;
	float reading = -1.0;
	do {
		reading = Plugin_171_pzem->current(pzemIP);
		wdt_reset();
		counter++;
	} while (counter < PZEM_MAX_ATTEMPT && reading < 0.0);
  if (reading == -1) reading = 0;
  if (PLUGIN_171_DEBUG) {
    String log = F("Current try :"); log += counter;
    addLog(LOG_LEVEL_DEBUG, log);
  }
  return reading;
}

float Plugin171_ReadPower() {
  int counter = 0;
	float reading = -1.0;
	do {
		reading = Plugin_171_pzem->power(pzemIP);
		wdt_reset();
		counter++;
	} while (counter < PZEM_MAX_ATTEMPT && reading < 0.0);
  if (reading == -1) reading = 0;
  if (PLUGIN_171_DEBUG) {
    String log = F("Power try :"); log += counter;
    addLog(LOG_LEVEL_DEBUG, log);
  }
  return reading;
}

float Plugin171_ReadEnergy() {
	int counter = 0;
	float reading = -1.0;
	do {
		reading = Plugin_171_pzem->energy(pzemIP);
		wdt_reset();
		counter++;
	} while (counter < PZEM_MAX_ATTEMPT && reading < 0.0);
  if (PLUGIN_171_DEBUG) {
    String log = F("Energy try :"); log += counter;
    addLog(LOG_LEVEL_DEBUG, log);
  }
	return reading;
}
#endif
Sorry, I don't know how to use git to make pull requests :( this will come also, please bear with my learning curve ;)

I also found a workaround to have several modules using the "port" feature of espeasy but it's a bit ugly ; if anybody have urgent need of many module I can publish, if not I'll wait to find a better solution !

Re: Support for PZEM 004T Energy monitor

Posted: 05 Dec 2017, 22:16
by F-rank
Hi,

Great plugin!
All values show correctly in the web interface that runs on the esp.
At first, some values weren't Always displayed.
I solved that by using another power supply for the 5v supply for the pzem004t.
Maybe some other users can solve their problems reading the values knowing that.

Now, I can add the pzem to Domoticz without problems, only one value is displayed.. The voltage. Other then that, nothing shows.
I was wondering if it would be possible to choose an IDX for each value of the sensor?
I don't know if that is possible at all in esp-easy?

It would help me out a lot.
Since I'm not a die hard coder, I can't do it myself...

Hope someone can help!

Keep up the good work!
\
Best regards,
Frank.

Re: Support for PZEM 004T Energy monitor

Posted: 06 Dec 2017, 01:02
by papperone
aleph0 wrote: 19 Nov 2017, 18:13 Hi all,

here is a fix for the problem of parameters being taken into account only at boot. Now things can be changed on the fly by re-doing initialisation at every "submit" of the form :

[ CODE ]

Sorry, I don't know how to use git to make pull requests :( this will come also, please bear with my learning curve ;)

I also found a workaround to have several modules using the "port" feature of espeasy but it's a bit ugly ; if anybody have urgent need of many module I can publish, if not I'll wait to find a better solution !
Sorry for late reply but I missed your post; you are right about the bug on save changin parameter, it's enough to destroy the object so it will be recreated on the init (no need of the boolean flag), I will submit this bug-fix asap.
Can you please explain better what you mean with "port feature of espeasy" so I can implement the multiple sensor support? (you can share your code even via PM and I can incorporate with my plugin and publish it on GitHub to be tested)

Re: Support for PZEM 004T Energy monitor

Posted: 06 Dec 2017, 04:08
by sega2177
Hello aleph0, could you put the compiled firmware with the plugin PZET-004?

Re: Support for PZEM 004T Energy monitor

Posted: 06 Dec 2017, 13:15
by aleph0
sega2177 wrote: 06 Dec 2017, 04:08 Hello aleph0, could you put the compiled firmware with the plugin PZET-004?
Please find attached the version for 4Gb flash with all the "Testing" plugins enabled, including the PZEM-004T with my last modifications to handle two modules. Use "port" to select the module : port 0 for first module and port 1 for second module. Remember each module will take up to 12s to answer in case there is no voltage on the main terminal, so don't poll faster then 15s*the number of modules

Feedback is welcome !

Re: Support for PZEM 004T Energy monitor

Posted: 06 Dec 2017, 13:18
by aleph0
F-rank wrote: 05 Dec 2017, 22:16 Now, I can add the pzem to Domoticz without problems, only one value is displayed.. The voltage. Other then that, nothing shows.
Have a look here for a workaround viewtopic.php?p=20595#p20595

Re: Support for PZEM 004T Energy monitor

Posted: 06 Dec 2017, 13:41
by F-rank
Ok thanks,

I must have overlooked that...
I never used code in domoticz before. How do I use it?
I googled and looked in the wiki pages. But can't find an answer to it?

Maybe I'm not looking at the right places?

Re: Support for PZEM 004T Energy monitor

Posted: 06 Dec 2017, 15:40
by sega2177
Thank you very much, everything turned out, but as with many, only the voltage in domoticz is output, you gave an example above how to prescribe, so that this does not happen-I did not understand which folder I should throw it in?

Re: Support for PZEM 004T Energy monitor

Posted: 06 Dec 2017, 19:36
by sega2177
I figured out the numeric values, but when I open the log, it's empty (((

Re: Support for PZEM 004T Energy monitor

Posted: 07 Dec 2017, 00:36
by F-rank
I have put the code in the file device.Lua?
Don't know for sure if this is the correct file? Or how to do this correctly.
I do get four separate values now, as shown in the picture below.
But indeed the log stays empty.

Hope you can help me out here.
At least I want to log Voltage and Current.
So I hope this will be possible with my setup

Many thanks for all the help.

Image

Re: Support for PZEM 004T Energy monitor

Posted: 07 Dec 2017, 07:20
by aleph0
Hi!

Regarding domoticz code, you have two choices :
- either you copy it in the domoticz/script/lua folder with a name ending by _device.lua eg pzem_device.lua
- either you go to the tools menu->more-> events, create a new "lua" "device" script named as you want and replace the default content by the code I posted

You also need to edit the first lines of the script starting by local dev,_... to match the name of your own devices

Btw, it's normal for the dummy pzem log to be empty as we overload the object. You'll get the log from the devices managed by the script

Hope it helps !

Re: Support for PZEM 004T Energy monitor

Posted: 07 Dec 2017, 07:48
by F-rank
Thanks a lot!

I will look into that after work.
I have been looking for some setting regarding lua scripts as I thought I had to look in thst way. But didn't find any...
Now... I may have overlooked it, but can it be a specific version when it was introduced?
If i click update, It says it's the latest.

Thanks again!

Re: Support for PZEM 004T Energy monitor

Posted: 07 Dec 2017, 10:17
by sega2177
it is not entirely clear what to prescribe after dev, could you describe in more detail, since I'm new to this and I'm hard at programming, thank you in advance

Re: Support for PZEM 004T Energy monitor

Posted: 07 Dec 2017, 10:32
by aleph0
I can understand :). This issue is now purely related to domoticz and not espeasy. So far, espeasy is doing the job correctly :) If it's ok for you all, I'll open a thread on the domoticz forum and upload a detailed tutorial over there. It'll be this week-end as I have no time for this during the week ; I'll post the link here when I'm done with it

Re: Support for PZEM 004T Energy monitor

Posted: 07 Dec 2017, 10:47
by F-rank
That would be great!

Thanks!

Re: Support for PZEM 004T Energy monitor

Posted: 07 Dec 2017, 11:36
by sega2177
we will wait, thank you

Re: Support for PZEM 004T Energy monitor

Posted: 09 Dec 2017, 22:32
by aleph0
Hi All !

Here is the link to topic on the domoticz forum on how to retreive the pzem values :
https://www.domoticz.com/forum/viewtopi ... 14&t=20820

Please note that in that post, I updated the domoticz script compared to the one I posted here previously to fix a few bugs, and for more accurate measurements

Feedback is welcome !

Re: Support for PZEM 004T Energy monitor

Posted: 10 Dec 2017, 11:50
by sega2177
Hi, I did everything as you do, but in the device tab, the values ​​are shown, and when you switch to auxiliary values ​​by zero, what else could it be? It is not entirely clear what values ​​to write when assigning a variable? Same as you on the screen or others?