supla-device
Loading...
Searching...
No Matches
PzemV2.h
1/*
2 Copyright (C) AC SOFTWARE SP. Z O.O.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17*/
18
19#ifndef SRC_SUPLA_SENSOR_PZEMV2_H_
20#define SRC_SUPLA_SENSOR_PZEMV2_H_
21
22#include <Arduino.h>
23// dependence: Arduino communication library for Peacefair PZEM-004T Energy
24// monitor https://github.com/olehs/PZEM004T
25#include <PZEM004T.h>
26#include <SoftwareSerial.h>
27#include <supla/time.h>
28
29#include "one_phase_electricity_meter.h"
30
31namespace Supla {
32namespace Sensor {
33
34class PZEMv2 : public OnePhaseElectricityMeter {
35 public:
36 PZEMv2(int8_t pinRX, int8_t pinTX) : pzem(pinRX, pinTX), ip(192, 168, 1, 1) {
37 }
38
39 explicit PZEMv2(HardwareSerial *serial) : pzem(serial), ip(192, 168, 1, 1) {
40 }
41
42 void onInit() {
43 lastReadTime = millis();
44 pzem.setAddress(ip);
45 readValuesFromDevice();
46 updateChannelValues();
47 }
48
49 virtual void readValuesFromDevice() {
50 float current = pzem.current(ip);
51 // If current reading is NAN, we assume that PZEM there is no valid
52 // communication with PZEM. Sensor shouldn't show any data
53 if (current == PZEM_ERROR_VALUE) {
54 resetReadParameters();
55 return;
56 }
57
58 float powerFactor = 0;
59 float reactive = 0;
60 float voltage = pzem.voltage(ip);
61 float active = pzem.power(ip);
62 float apparent = (voltage * current);
63 if (apparent > active) {
64 reactive = sqrt(apparent * apparent - active * active);
65 } else {
66 reactive = 0;
67 }
68 if (active > apparent) {
69 powerFactor = 1;
70 } else if (apparent == 0) {
71 powerFactor = 0;
72 } else {
73 powerFactor = (active / apparent);
74 }
75
76 setVoltage(0, voltage * 100);
77 setCurrent(0, current * 1000);
78 setPowerActive(0, active * 100000);
79 setFwdActEnergy(0, pzem.energy(ip) * 100);
80 setPowerApparent(0, apparent * 100000);
81 setPowerReactive(0, reactive * 10000);
82 setPowerFactor(0, powerFactor * 1000);
83 }
84
85 PZEM004T pzem;
86 IPAddress ip;
87};
88}; // namespace Sensor
89}; // namespace Supla
90
91#endif // SRC_SUPLA_SENSOR_PZEMV2_H_
void onInit()
Third method called on element in SuplaDevice.begin()
Definition PzemV2.h:42