75 lines
1.8 KiB
C++
75 lines
1.8 KiB
C++
#include <stdint.h>
|
|
|
|
#include <SmingCore/SmingCore.h>
|
|
#include <SmingCore/HardwareTimer.h>
|
|
|
|
#include <SpejsNode.h>
|
|
#include <Endpoint.h>
|
|
#include <endpoints/OutputEndpoint.h>
|
|
#include <TcpPublish.h>
|
|
|
|
extern "C" {
|
|
#include "sonoff_pow.h"
|
|
};
|
|
|
|
SpejsNode node("sonoff pow");
|
|
OutputEndpoint *relay;
|
|
TcpPublish tcpPublish;
|
|
|
|
Hardware_Timer cseMeasureTimer;
|
|
Timer cseUpdateTimer;
|
|
Timer printTimer;
|
|
bool started;
|
|
|
|
void startServers() {
|
|
tcpPublish.listen(123);
|
|
// TODO change to false when disconnected
|
|
started = true;
|
|
}
|
|
|
|
void print() {
|
|
char buf[30];
|
|
memset(buf, 0, 30);
|
|
|
|
int len = 0;
|
|
float power_factor = 21517.217583641264;
|
|
float power =
|
|
(float)cse.power.changes * power_factor / (float)cse.power.samples;
|
|
double energy_factor = 0.001494251221086199;
|
|
double energy = (double)cse.energy * energy_factor;
|
|
len = m_snprintf(buf, 30, "%.2f W\n", power);
|
|
tcpPublish.write("power: ", 7);
|
|
tcpPublish.write(buf, len);
|
|
if ( started == true ) {
|
|
relay->notify("power", String(buf, len));
|
|
}
|
|
|
|
len = m_snprintf(buf, 30, "%.4f Wh\n", energy);
|
|
tcpPublish.write("energy: ", 8);
|
|
tcpPublish.write(buf, len);
|
|
if ( started == true ) {
|
|
// TODO ignore notify if not connected to mqtt broker
|
|
relay->notify("energy", String(buf, len));
|
|
}
|
|
}
|
|
|
|
|
|
void init() {
|
|
Serial.begin(SERIAL_BAUD_RATE); // 115200 by default
|
|
Serial.systemDebugOutput(true);
|
|
|
|
relay = new OutputEndpoint(RELAY_PIN);
|
|
node.registerEndpoint("relay", relay);
|
|
node.onConnectedCallback = startServers;
|
|
node.init();
|
|
|
|
cse_init( 4000 );
|
|
cseMeasureTimer.initializeUs(250, cse_measure_isr);
|
|
cseMeasureTimer.start();
|
|
cseUpdateTimer.initializeMs(100, cse_update);
|
|
cseUpdateTimer.start();
|
|
|
|
printTimer.initializeMs(1000, print).start();
|
|
printTimer.start();
|
|
}
|