Skip to content

Instantly share code, notes, and snippets.

@natm
Last active November 20, 2016 21:59
Show Gist options
  • Save natm/d47d8d86f900030295d55ac90aeee320 to your computer and use it in GitHub Desktop.
Save natm/d47d8d86f900030295d55ac90aeee320 to your computer and use it in GitHub Desktop.
CurrentCost power usage to MQTT using Homie
#include <Homie.h>
#include <SoftwareSerial.h>
#define FW_NAME "currentcost"
#define FW_VERSION "0.0.2"
const char *__FLAGGED_FW_NAME = "\xbf\x84\xe4\x13\x54" FW_NAME "\x93\x44\x6b\xa7\x75";
const char *__FLAGGED_FW_VERSION = "\x6a\x3f\x3e\x0e\xe1" FW_VERSION "\xb0\x30\x48\xd4\x1a";
#define PUB_INTERVAL 15
HomieNode ch1Node("ch1", "watts");
SoftwareSerial mySerial = SoftwareSerial(4, 14);
byte readByte = 0xFF;
byte pinState = 0;
char startPattern[] = "<ch1><watts>";
char endPattern[] = "<";
int state = 0;
int pos = 0;
int power = 0;
int powerLast = 0;
unsigned long lastPublish = 0;
void setupHandler() {
Homie.setNodeProperty(ch1Node, "unit", "watts", true);
}
void loopHandler() {
readByte = mySerial.read();
if (readByte == 0xFF) {
}
else {
gotByte();
}
if (millis() - lastPublish >= PUB_INTERVAL * 1000UL) {
if (powerLast > 0) {
if (Homie.setNodeProperty(ch1Node, "watts", String(powerLast), true)) {
lastPublish = millis();
}
}
}
}
void setup() {
Homie.setFirmware(FW_NAME, FW_VERSION);
Homie.registerNode(ch1Node);
Homie.setSetupFunction(setupHandler);
Homie.setLoopFunction(loopHandler);
Homie.enableBuiltInLedIndicator(false);
Homie.setup();
}
void loop() {
Homie.loop();
}
void gotByte() {
if (state == 0) {
if (readByte == startPattern[pos]) {
++pos;
if (startPattern[pos] == 0) {
// finished matching start pattern
++state;
power = 0;
}
}
else {
pos = 0;
}
}
else if (state == 1) {
if (readByte == endPattern[0]) {
// finished reading power
powerLast = power;
state = 0;
} else {
// read another digit
power = power * 10 + readByte - '0';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment