supla-device
Loading...
Searching...
No Matches
PzemV2.h
1// SPDX-FileCopyrightText: AC SOFTWARE SP. Z O.O.
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#ifndef SRC_SUPLA_SENSOR_PZEMV2_H_
5#define SRC_SUPLA_SENSOR_PZEMV2_H_
6
7#include <Arduino.h>
8// dependence: Arduino communication library for Peacefair PZEM-004T Energy
9// monitor https://github.com/olehs/PZEM004T
10#include <PZEM004T.h>
11#include <SoftwareSerial.h>
12#include <supla/time.h>
13
14#include "one_phase_electricity_meter.h"
15
16namespace Supla {
17namespace Sensor {
18
20 public:
21 PZEMv2(int8_t pinRX, int8_t pinTX) : pzem(pinRX, pinTX), ip(192, 168, 1, 1) {
22 }
23
24 explicit PZEMv2(HardwareSerial *serial) : pzem(serial), ip(192, 168, 1, 1) {
25 }
26
27 void onInit() {
28 lastReadTime = millis();
29 pzem.setAddress(ip);
30 readValuesFromDevice();
31 updateChannelValues();
32 }
33
34 virtual void readValuesFromDevice() {
35 float current = pzem.current(ip);
36 // If current reading is NAN, we assume that PZEM there is no valid
37 // communication with PZEM. Sensor shouldn't show any data
38 if (current == PZEM_ERROR_VALUE) {
39 resetReadParameters();
40 return;
41 }
42
43 float powerFactor = 0;
44 float reactive = 0;
45 float voltage = pzem.voltage(ip);
46 float active = pzem.power(ip);
47 float apparent = (voltage * current);
48 if (apparent > active) {
49 reactive = sqrt(apparent * apparent - active * active);
50 } else {
51 reactive = 0;
52 }
53 if (active > apparent) {
54 powerFactor = 1;
55 } else if (apparent == 0) {
56 powerFactor = 0;
57 } else {
58 powerFactor = (active / apparent);
59 }
60
61 setVoltage(0, voltage * 100);
62 setCurrent(0, current * 1000);
63 setPowerActive(0, active * 100000);
64 setFwdActEnergy(0, pzem.energy(ip) * 100);
65 setPowerApparent(0, apparent * 100000);
66 setPowerReactive(0, reactive * 10000);
67 setPowerFactor(0, powerFactor * 1000);
68 }
69
70 PZEM004T pzem;
71 IPAddress ip;
72};
73}; // namespace Sensor
74}; // namespace Supla
75
76#endif // SRC_SUPLA_SENSOR_PZEMV2_H_
Definition ip_address.h:15
Definition one_phase_electricity_meter.h:11
Definition PzemV2.h:19
void onInit()
Third method called on element in SuplaDevice.begin()
Definition PzemV2.h:27