SinricPro Library
SinricProPowerSensor.h
1 /*
2  * Copyright (c) 2019 Sinric. All rights reserved.
3  * Licensed under Creative Commons Attribution-Share Alike (CC BY-SA)
4  *
5  * This file is part of the Sinric Pro (https://github.com/sinricpro/)
6  */
7 
8 #ifndef _SINRICPOWERSENSOR_H_
9 #define _SINRICPOWERSENSOR_H_
10 
11 #include "SinricProDevice.h"
12 
18  public:
19  SinricProPowerSensor(const DeviceId &deviceId);
20  String getProductType() { return SinricProDevice::getProductType() + String("POWER_SENSOR"); }
21 
22  // event
23  bool sendPowerSensorEvent(float voltage, float current, float power=-1.0f, float apparentPower=-1.0f, float reactivePower=-1.0f, float factor=-1.0f, String cause = "PERIODIC_POLL");
24  private:
25  unsigned long startTime = 0;
26  unsigned long lastPower = 0;
27  protected:
28  float getWattHours(unsigned long currentTimestamp);
29 };
30 
31 SinricProPowerSensor::SinricProPowerSensor(const DeviceId &deviceId) : SinricProDevice(deviceId) {}
32 
46 bool SinricProPowerSensor::sendPowerSensorEvent(float voltage, float current, float power, float apparentPower, float reactivePower, float factor, String cause) {
47  DynamicJsonDocument eventMessage = prepareEvent(deviceId, "powerUsage", cause.c_str());
48  JsonObject event_value = eventMessage["payload"]["value"];
49  if (power == -1) power = voltage * current;
50  if (apparentPower != -1) factor = power / apparentPower;
51 
52  unsigned long currentTimestamp = getTimestamp();
53 
54  event_value["startTime"] = startTime;
55  event_value["voltage"] = voltage;
56  event_value["current"] = current;
57  event_value["power"] = power;
58  event_value["apparentPower"] = apparentPower;
59  event_value["reactivePower"] = reactivePower;
60  event_value["factor"] = factor;
61  event_value["wattHours"] = getWattHours(currentTimestamp);
62 
63  startTime = currentTimestamp;
64  lastPower = power;
65  return sendEvent(eventMessage);
66 }
67 
68 float SinricProPowerSensor::getWattHours(unsigned long currentTimestamp) {
69  if (startTime) return (currentTimestamp-startTime) * lastPower / 3600.0f;
70  return 0;
71 }
72 
73 #endif
SinricProPowerSensor
Device to report power usage.
Definition: SinricProPowerSensor.h:17
SinricProPowerSensor::sendPowerSensorEvent
bool sendPowerSensorEvent(float voltage, float current, float power=-1.0f, float apparentPower=-1.0f, float reactivePower=-1.0f, float factor=-1.0f, String cause="PERIODIC_POLL")
Send PowerSensor event to SinricPro Server.
Definition: SinricProPowerSensor.h:46
SinricProDevice
Base class for all device types.
Definition: SinricProDevice.h:24