inital commit
This commit is contained in:
parent
bc135ecd66
commit
a7976820b2
7 changed files with 1098 additions and 0 deletions
115
src/WMBusFrame.cpp
Normal file
115
src/WMBusFrame.cpp
Normal file
|
@ -0,0 +1,115 @@
|
|||
/*
|
||||
Copyright (C) 2020 chester4444@wolke7.net
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "WMbusFrame.h"
|
||||
|
||||
WMBusFrame::WMBusFrame()
|
||||
{
|
||||
aes128.setKey(key, sizeof(key));
|
||||
}
|
||||
|
||||
void WMBusFrame::check()
|
||||
{
|
||||
// check meterId
|
||||
for (uint8_t i = 0; i< 4; i++)
|
||||
{
|
||||
if (meterId[i] != payload[6-i])
|
||||
{
|
||||
isValid = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// TBD: check crc
|
||||
isValid = true;
|
||||
}
|
||||
|
||||
void WMBusFrame::printMeterInfo(uint8_t *data, size_t len)
|
||||
{
|
||||
// init positions for compact frame
|
||||
int pos_tt = 9; // total consumption
|
||||
int pos_tg = 13; // target consumption
|
||||
int pos_ic = 7; // info codes
|
||||
int pos_ft = 17; // flow temp
|
||||
int pos_at = 18; // ambient temp
|
||||
|
||||
if (data[2] == 0x78) // long frame
|
||||
{
|
||||
// overwrite it with long frame positions
|
||||
pos_tt = 10;
|
||||
pos_tg = 16;
|
||||
pos_ic = 6;
|
||||
pos_ft = 22;
|
||||
pos_at = 25;
|
||||
}
|
||||
|
||||
char total[10];
|
||||
uint32_t tt = data[pos_tt]
|
||||
+ (data[pos_tt+1] << 8)
|
||||
+ (data[pos_tt+2] << 16)
|
||||
+ (data[pos_tt+3] << 24);
|
||||
snprintf(total, sizeof(total), "%d.%03d", tt/1000, tt%1000 );
|
||||
Serial.printf("total: %s m%c - ", total, 179);
|
||||
|
||||
char target[10];
|
||||
uint32_t tg = data[pos_tg]
|
||||
+ (data[pos_tg+1] << 8)
|
||||
+ (data[pos_tg+2] << 16)
|
||||
+ (data[pos_tg+3] << 24);
|
||||
snprintf(target, sizeof(target), "%d.%03d", tg/1000, tg%1000 );
|
||||
Serial.printf("target: %s m%c - ", target, 179);
|
||||
|
||||
char flow_temp[3];
|
||||
snprintf(flow_temp, sizeof(flow_temp), "%2d", data[pos_ft]);
|
||||
Serial.printf("%s %cC - ", flow_temp, 176);
|
||||
|
||||
char ambient_temp[3];
|
||||
snprintf(ambient_temp, sizeof(ambient_temp), "%2d", data[pos_at]);
|
||||
Serial.printf("%s %cC\n\r", ambient_temp, 176);
|
||||
}
|
||||
|
||||
void WMBusFrame::decode()
|
||||
{
|
||||
// check meterId, CRC
|
||||
check();
|
||||
if (!isValid) return;
|
||||
|
||||
uint8_t cipherLength = length - 2 - 16; // cipher starts at index 16, remove 2 crc bytes
|
||||
memcpy(cipher, &payload[16], cipherLength);
|
||||
|
||||
memset(iv, 0, sizeof(iv)); // padding with 0
|
||||
memcpy(iv, &payload[1], 8);
|
||||
iv[8] = payload[10];
|
||||
memcpy(&iv[9], &payload[12], 4);
|
||||
|
||||
aes128.setIV(iv, sizeof(iv));
|
||||
aes128.decrypt(plaintext, (const uint8_t *) cipher, cipherLength);
|
||||
|
||||
/*
|
||||
Serial.printf("C: ");
|
||||
for (size_t i = 0; i < cipherLength; i++)
|
||||
{
|
||||
Serial.printf("%02X", cipher[i]);
|
||||
}
|
||||
Serial.println();
|
||||
Serial.printf("P(%d): ", cipherLength);
|
||||
for (size_t i = 0; i < cipherLength; i++)
|
||||
{
|
||||
Serial.printf("%02X", plaintext[i]);
|
||||
}
|
||||
Serial.println();
|
||||
*/
|
||||
|
||||
printMeterInfo(plaintext, cipherLength);
|
||||
}
|
265
src/WaterMeter.cpp
Normal file
265
src/WaterMeter.cpp
Normal file
|
@ -0,0 +1,265 @@
|
|||
/*
|
||||
Copyright (C) 2020 chester4444@wolke7.net
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "WaterMeter.h"
|
||||
|
||||
WaterMeter::WaterMeter()
|
||||
{
|
||||
}
|
||||
|
||||
// ChipSelect assert
|
||||
inline void WaterMeter::selectCC1101(void)
|
||||
{
|
||||
digitalWrite(SS, LOW);
|
||||
}
|
||||
|
||||
// ChipSelect deassert
|
||||
inline void WaterMeter::deselectCC1101(void)
|
||||
{
|
||||
digitalWrite(SS, HIGH);
|
||||
}
|
||||
|
||||
// wait for MISO pulling down
|
||||
inline void WaterMeter::waitMiso(void)
|
||||
{
|
||||
while(digitalRead(MISO) == HIGH);
|
||||
}
|
||||
|
||||
// write a single register of CC1101
|
||||
void WaterMeter::writeReg(uint8 regAddr, uint8 value)
|
||||
{
|
||||
selectCC1101(); // Select CC1101
|
||||
waitMiso(); // Wait until MISO goes low
|
||||
SPI.transfer(regAddr); // Send register address
|
||||
SPI.transfer(value); // Send value
|
||||
deselectCC1101(); // Deselect CC1101
|
||||
}
|
||||
|
||||
// send a strobe command to CC1101
|
||||
void WaterMeter::cmdStrobe(uint8 cmd)
|
||||
{
|
||||
selectCC1101(); // Select CC1101
|
||||
delayMicroseconds(5);
|
||||
waitMiso(); // Wait until MISO goes low
|
||||
SPI.transfer(cmd); // Send strobe command
|
||||
delayMicroseconds(5);
|
||||
deselectCC1101(); // Deselect CC1101
|
||||
}
|
||||
|
||||
// read CC1101 register (status or configuration)
|
||||
uint8 WaterMeter::readReg(uint8 regAddr, uint8 regType)
|
||||
{
|
||||
uint8 addr, val;
|
||||
|
||||
addr = regAddr | regType;
|
||||
selectCC1101(); // Select CC1101
|
||||
waitMiso(); // Wait until MISO goes low
|
||||
SPI.transfer(addr); // Send register address
|
||||
val = SPI.transfer(0x00); // Read result
|
||||
deselectCC1101(); // Deselect CC1101
|
||||
|
||||
return val;
|
||||
}
|
||||
|
||||
//
|
||||
void WaterMeter::readBurstReg(uint8 * buffer, uint8 regAddr, uint8 len)
|
||||
{
|
||||
uint8 addr, i;
|
||||
|
||||
addr = regAddr | READ_BURST;
|
||||
selectCC1101(); // Select CC1101
|
||||
delayMicroseconds(5);
|
||||
waitMiso(); // Wait until MISO goes low
|
||||
SPI.transfer(addr); // Send register address
|
||||
for(i=0 ; i<len ; i++)
|
||||
buffer[i] = SPI.transfer(0x00); // Read result byte by byte
|
||||
delayMicroseconds(2);
|
||||
deselectCC1101(); // Deselect CC1101
|
||||
}
|
||||
|
||||
// power on reset
|
||||
void WaterMeter::reset(void)
|
||||
{
|
||||
deselectCC1101(); // Deselect CC1101
|
||||
delayMicroseconds(3);
|
||||
|
||||
digitalWrite(MOSI, LOW);
|
||||
digitalWrite(SCK, HIGH); // see CC1101 datasheet 11.3
|
||||
|
||||
selectCC1101(); // Select CC1101
|
||||
delayMicroseconds(3);
|
||||
deselectCC1101(); // Deselect CC1101
|
||||
delayMicroseconds(45); // at least 40 us
|
||||
|
||||
selectCC1101(); // Select CC1101
|
||||
|
||||
waitMiso(); // Wait until MISO goes low
|
||||
SPI.transfer(CC1101_SRES); // Send reset command strobe
|
||||
waitMiso(); // Wait until MISO goes low
|
||||
|
||||
deselectCC1101(); // Deselect CC1101
|
||||
}
|
||||
|
||||
// set IDLE state, flush FIFO and (re)start receiver
|
||||
void WaterMeter::startReceiver(void)
|
||||
{
|
||||
cmdStrobe(CC1101_SIDLE); // Enter IDLE state
|
||||
while (readReg(CC1101_MARCSTATE, CC1101_STATUS_REGISTER) != MARCSTATE_IDLE);
|
||||
{
|
||||
delay(1);
|
||||
}
|
||||
|
||||
cmdStrobe(CC1101_SFRX); // flush receive queue
|
||||
|
||||
cmdStrobe(CC1101_SRX); // Enter RX state
|
||||
while (readReg(CC1101_MARCSTATE, CC1101_STATUS_REGISTER) != MARCSTATE_RX);
|
||||
{
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
|
||||
// initialize all the CC1101 registers
|
||||
void WaterMeter::initializeRegisters(void)
|
||||
{
|
||||
writeReg(CC1101_IOCFG2, CC1101_DEFVAL_IOCFG2);
|
||||
writeReg(CC1101_IOCFG0, CC1101_DEFVAL_IOCFG0);
|
||||
writeReg(CC1101_FIFOTHR, CC1101_DEFVAL_FIFOTHR);
|
||||
writeReg(CC1101_PKTLEN, CC1101_DEFVAL_PKTLEN);
|
||||
writeReg(CC1101_PKTCTRL1, CC1101_DEFVAL_PKTCTRL1);
|
||||
writeReg(CC1101_PKTCTRL0, CC1101_DEFVAL_PKTCTRL0);
|
||||
writeReg(CC1101_SYNC1, CC1101_DEFVAL_SYNC1);
|
||||
writeReg(CC1101_SYNC0, CC1101_DEFVAL_SYNC0);
|
||||
writeReg(CC1101_ADDR, CC1101_DEFVAL_ADDR);
|
||||
writeReg(CC1101_CHANNR, CC1101_DEFVAL_CHANNR);
|
||||
writeReg(CC1101_FSCTRL1, CC1101_DEFVAL_FSCTRL1);
|
||||
writeReg(CC1101_FSCTRL0, CC1101_DEFVAL_FSCTRL0);
|
||||
writeReg(CC1101_FREQ2, CC1101_DEFVAL_FREQ2);
|
||||
writeReg(CC1101_FREQ1, CC1101_DEFVAL_FREQ1);
|
||||
writeReg(CC1101_FREQ0, CC1101_DEFVAL_FREQ0);
|
||||
writeReg(CC1101_MDMCFG4, CC1101_DEFVAL_MDMCFG4);
|
||||
writeReg(CC1101_MDMCFG3, CC1101_DEFVAL_MDMCFG3);
|
||||
writeReg(CC1101_MDMCFG2, CC1101_DEFVAL_MDMCFG2);
|
||||
writeReg(CC1101_MDMCFG1, CC1101_DEFVAL_MDMCFG1);
|
||||
writeReg(CC1101_MDMCFG0, CC1101_DEFVAL_MDMCFG0);
|
||||
writeReg(CC1101_DEVIATN, CC1101_DEFVAL_DEVIATN);
|
||||
writeReg(CC1101_MCSM1, CC1101_DEFVAL_MCSM1);
|
||||
writeReg(CC1101_MCSM0, CC1101_DEFVAL_MCSM0);
|
||||
writeReg(CC1101_FOCCFG, CC1101_DEFVAL_FOCCFG);
|
||||
writeReg(CC1101_BSCFG, CC1101_DEFVAL_BSCFG);
|
||||
writeReg(CC1101_AGCCTRL2, CC1101_DEFVAL_AGCCTRL2);
|
||||
writeReg(CC1101_AGCCTRL1, CC1101_DEFVAL_AGCCTRL1);
|
||||
writeReg(CC1101_AGCCTRL0, CC1101_DEFVAL_AGCCTRL0);
|
||||
writeReg(CC1101_FREND1, CC1101_DEFVAL_FREND1);
|
||||
writeReg(CC1101_FREND0, CC1101_DEFVAL_FREND0);
|
||||
writeReg(CC1101_FSCAL3, CC1101_DEFVAL_FSCAL3);
|
||||
writeReg(CC1101_FSCAL2, CC1101_DEFVAL_FSCAL2);
|
||||
writeReg(CC1101_FSCAL1, CC1101_DEFVAL_FSCAL1);
|
||||
writeReg(CC1101_FSCAL0, CC1101_DEFVAL_FSCAL0);
|
||||
writeReg(CC1101_FSTEST, CC1101_DEFVAL_FSTEST);
|
||||
writeReg(CC1101_TEST2, CC1101_DEFVAL_TEST2);
|
||||
writeReg(CC1101_TEST1, CC1101_DEFVAL_TEST1);
|
||||
writeReg(CC1101_TEST0, CC1101_DEFVAL_TEST0);
|
||||
}
|
||||
|
||||
volatile boolean packetAvailable = false;
|
||||
void ICACHE_RAM_ATTR GD0_ISR(void);
|
||||
|
||||
// handle interrupt from CC1101 via GDO0
|
||||
void GD0_ISR(void) {
|
||||
// set the flag that a package is available
|
||||
packetAvailable = true;
|
||||
}
|
||||
|
||||
// should be called frequently, handles the ISR flag
|
||||
// does the frame checkin and decryption
|
||||
bool WaterMeter::isFrameAvailable(void)
|
||||
{
|
||||
if (packetAvailable)
|
||||
{
|
||||
//Serial.println("packet received");
|
||||
// Disable wireless reception interrupt
|
||||
detachInterrupt(digitalPinToInterrupt(CC1101_GDO0));
|
||||
|
||||
// clear the flag
|
||||
packetAvailable = false;
|
||||
|
||||
WMBusFrame frame;
|
||||
|
||||
receive(&frame);
|
||||
|
||||
// Enable wireless reception interrupt
|
||||
attachInterrupt(digitalPinToInterrupt(CC1101_GDO0), GD0_ISR, FALLING);
|
||||
return frame.isValid;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Initialize CC1101 to receive WMBus MODE C1
|
||||
void WaterMeter::begin()
|
||||
{
|
||||
pinMode(SS, OUTPUT); // SS Pin -> Output
|
||||
SPI.begin(); // Initialize SPI interface
|
||||
pinMode(CC1101_GDO0, INPUT); // Config GDO0 as input
|
||||
|
||||
reset(); // power on CC1101
|
||||
|
||||
//Serial.println("Setting CC1101 registers");
|
||||
initializeRegisters(); // init CC1101 registers
|
||||
|
||||
cmdStrobe(CC1101_SCAL);
|
||||
delay(1);
|
||||
|
||||
attachInterrupt(digitalPinToInterrupt(CC1101_GDO0), GD0_ISR, FALLING);
|
||||
startReceiver();
|
||||
}
|
||||
|
||||
// reads a single byte from the RX fifo
|
||||
uint8_t WaterMeter::readByteFromFifo(void)
|
||||
{
|
||||
return readReg(CC1101_RXFIFO, CC1101_CONFIG_REGISTER);
|
||||
}
|
||||
|
||||
// handles a received frame and restart the CC1101 receiver
|
||||
void WaterMeter::receive(WMBusFrame * frame)
|
||||
{
|
||||
// read preamble, should be 0x543D
|
||||
uint8_t p1 = readByteFromFifo();
|
||||
uint8_t p2 = readByteFromFifo();
|
||||
//Serial.printf("%02x%02x", p1, p2);
|
||||
|
||||
uint8_t payloadLength = readByteFromFifo();
|
||||
|
||||
// is it Mode C1, frame B and does it fit in the buffer
|
||||
if ( (payloadLength < WMBusFrame::MAX_LENGTH )
|
||||
&& (p1 == 0x54) && (p2 == 0x3D) )
|
||||
{
|
||||
// 3rd byte is payload length
|
||||
frame->length = payloadLength;
|
||||
|
||||
//Serial.printf("%02X", lfield);
|
||||
|
||||
// starting with 1! index 0 is lfield
|
||||
for (int i = 0; i < payloadLength; i++)
|
||||
{
|
||||
frame->payload[i] = readByteFromFifo();
|
||||
}
|
||||
|
||||
// do some checks: my meterId, crc ok
|
||||
frame->decode();
|
||||
}
|
||||
|
||||
// flush RX fifo and restart receiver
|
||||
startReceiver();
|
||||
//Serial.printf("rxStatus: 0x%02x\n\r", readStatusReg(CC1101_RXBYTES));
|
||||
}
|
419
src/main.cpp
Normal file
419
src/main.cpp
Normal file
|
@ -0,0 +1,419 @@
|
|||
/*
|
||||
Copyright (C) 2020 chester4444@wolke7.net
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266mDNS.h>
|
||||
#include <SoftwareSerial.h>
|
||||
#include <WiFiUdp.h>
|
||||
#include <PubSubClient.h>
|
||||
#include <ArduinoOTA.h>
|
||||
#include "WaterMeter.h"
|
||||
#include "credentials.h"
|
||||
|
||||
#define ESP_NAME "ESP-Meter"
|
||||
|
||||
// Attach CC1101 pins to ESP8266 SPI pins
|
||||
// VCC => 3V3
|
||||
// GND => GND
|
||||
// CSN => D8
|
||||
// MOSI => D7
|
||||
// MISO => D6
|
||||
// SCK => D5
|
||||
// GD0 => D2 A valid interrupt pin for your platform (defined below this)
|
||||
// GD2 => not connected
|
||||
|
||||
#define DEBUG 0
|
||||
|
||||
//Wifi settings: SSID, PW, MQTT broker
|
||||
#define NUM_SSID_CREDENTIALS 3
|
||||
const char *credentials[NUM_SSID_CREDENTIALS][4] =
|
||||
// SSID, PW, MQTT
|
||||
{ {SSID1, PW1, MQTT1 }
|
||||
, {SSID2, PW2, MQTT2 }
|
||||
, {SSID3, PW3, MQTT3 }
|
||||
};
|
||||
|
||||
WaterMeter waterMeter;
|
||||
|
||||
WiFiClient espMqttClient;
|
||||
PubSubClient mqttClient(espMqttClient);
|
||||
|
||||
char MyIp[16];
|
||||
int cred = -1;
|
||||
|
||||
int getWifiToConnect(int numSsid)
|
||||
{
|
||||
for (int i = 0; i < NUM_SSID_CREDENTIALS; i++)
|
||||
{
|
||||
//Serial.println(WiFi.SSID(i));
|
||||
|
||||
for (int j = 0; j < numSsid; ++j)
|
||||
{
|
||||
/*Serial.print(j);
|
||||
Serial.print(": ");
|
||||
Serial.print(WiFi.SSID(i).c_str());
|
||||
Serial.print(" = ");
|
||||
Serial.println(credentials[j][0]);*/
|
||||
if (strcmp(WiFi.SSID(j).c_str(), credentials[i][0]) == 0)
|
||||
{
|
||||
Serial.println("Credentials found for: ");
|
||||
Serial.println(credentials[i][0]);
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// connect to wifi – returns true if successful or false if not
|
||||
bool ConnectWifi(void)
|
||||
{
|
||||
int i = 0;
|
||||
|
||||
Serial.println("starting scan");
|
||||
// scan for nearby networks:
|
||||
int numSsid = WiFi.scanNetworks();
|
||||
|
||||
Serial.print("scanning WIFI, found ");
|
||||
Serial.print(numSsid);
|
||||
Serial.println(" available access points:");
|
||||
|
||||
if (numSsid == -1)
|
||||
{
|
||||
Serial.println("Couldn't get a wifi connection");
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < numSsid; i++)
|
||||
{
|
||||
Serial.print(i+1);
|
||||
Serial.print(") ");
|
||||
Serial.println(WiFi.SSID(i));
|
||||
}
|
||||
|
||||
// search for given credentials
|
||||
cred = getWifiToConnect(numSsid);
|
||||
if (cred == -1)
|
||||
{
|
||||
Serial.println("No Wifi!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// try to connect
|
||||
WiFi.begin(credentials[cred][0], credentials[cred][1]);
|
||||
Serial.println("");
|
||||
Serial.print("Connecting to WiFi ");
|
||||
Serial.println(credentials[cred][0]);
|
||||
|
||||
i = 0;
|
||||
while (WiFi.status() != WL_CONNECTED)
|
||||
{
|
||||
digitalWrite(LED_BUILTIN, LOW);
|
||||
delay(300);
|
||||
Serial.print(".");
|
||||
digitalWrite(LED_BUILTIN, HIGH);
|
||||
delay(300);
|
||||
if (i++ > 30)
|
||||
{
|
||||
// giving up
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void mqttDebug(const char* debug_str)
|
||||
{
|
||||
String s="/watermeter/debug";
|
||||
mqttClient.publish(s.c_str(), debug_str);
|
||||
}
|
||||
|
||||
void mqttCallback(char* topic, byte* payload, unsigned int len)
|
||||
{
|
||||
// create a local copies of topic and payload
|
||||
// PubSubClient overwrites it internally
|
||||
String t(topic);
|
||||
byte *p = new byte[len];
|
||||
memcpy(p, payload, len);
|
||||
|
||||
/* Serial.print("MQTT-RECV: ");
|
||||
Serial.print(topic);
|
||||
Serial.print(" ");
|
||||
Serial.println((char)payload[0]); // FIXME LEN
|
||||
*/
|
||||
if (strstr(topic, "/smarthomeNG/start"))
|
||||
{
|
||||
if (len == 4) // True
|
||||
{
|
||||
// maybe to something
|
||||
}
|
||||
}
|
||||
else if (strstr(topic, "/espmeter/reset"))
|
||||
{
|
||||
if (len == 4) // True
|
||||
{
|
||||
// maybe to something
|
||||
const char *topic = "/espmeter/reset/status";
|
||||
const char *msg = "False";
|
||||
mqttClient.publish(topic, msg);
|
||||
mqttClient.loop();
|
||||
delay(200);
|
||||
|
||||
// reboot
|
||||
ESP.restart();
|
||||
}
|
||||
}
|
||||
// and of course, free it
|
||||
delete[] p;
|
||||
}
|
||||
|
||||
bool mqttConnect()
|
||||
{
|
||||
mqttClient.setServer(credentials[cred][2], 1883);
|
||||
mqttClient.setCallback(mqttCallback);
|
||||
|
||||
// connect client to retainable last will message
|
||||
return mqttClient.connect(ESP_NAME, "/watermeter/online", 0, true, "False");
|
||||
}
|
||||
|
||||
void mqttSubscribe()
|
||||
{
|
||||
String s;
|
||||
// publish online status
|
||||
s = "/watermeter/online";
|
||||
mqttClient.publish(s.c_str(), "True", true);
|
||||
// Serial.print("MQTT-SEND: ");
|
||||
// Serial.print(s);
|
||||
// Serial.println(" True");
|
||||
|
||||
// publish ip address
|
||||
s="/watermeter/ipaddr";
|
||||
IPAddress MyIP = WiFi.localIP();
|
||||
snprintf(MyIp, 16, "%d.%d.%d.%d", MyIP[0], MyIP[1], MyIP[2], MyIP[3]);
|
||||
mqttClient.publish(s.c_str(), MyIp, true);
|
||||
// Serial.print("MQTT-SEND: ");
|
||||
// Serial.print(s);
|
||||
// Serial.print(" ");
|
||||
// Serial.println(MyIp);
|
||||
|
||||
// if smarthome.py restarts -> publish init values
|
||||
s = "/smarthomeNG/start";
|
||||
mqttClient.subscribe(s.c_str());
|
||||
|
||||
// if True; meter data are published every 5 seconds
|
||||
// if False: meter data are published once a minute
|
||||
s = "/watermeter/liveData";
|
||||
mqttClient.subscribe(s.c_str());
|
||||
|
||||
// if True -> perform an reset
|
||||
s = "/espmeter/reset";
|
||||
mqttClient.subscribe(s.c_str());
|
||||
}
|
||||
|
||||
void setupOTA()
|
||||
{
|
||||
// Port defaults to 8266
|
||||
// ArduinoOTA.setPort(8266);
|
||||
|
||||
// Hostname defaults to esp8266-[ChipID]
|
||||
ArduinoOTA.setHostname(ESP_NAME);
|
||||
|
||||
// No authentication by default
|
||||
// ArduinoOTA.setPassword((const char *)"123");
|
||||
|
||||
ArduinoOTA.onStart([]() {
|
||||
String type;
|
||||
if (ArduinoOTA.getCommand() == U_FLASH) {
|
||||
type = "sketch";
|
||||
} else { // U_FS
|
||||
type = "filesystem";
|
||||
}
|
||||
|
||||
// NOTE: if updating FS this would be the place to unmount FS using FS.end()
|
||||
Serial.println("Start updating " + type);
|
||||
});
|
||||
ArduinoOTA.onEnd([]() {
|
||||
Serial.println("\nEnd");
|
||||
});
|
||||
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
|
||||
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
|
||||
});
|
||||
ArduinoOTA.onError([](ota_error_t error) {
|
||||
Serial.printf("Error[%u]: ", error);
|
||||
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
|
||||
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
|
||||
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
|
||||
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
|
||||
else if (error == OTA_END_ERROR) Serial.println("End Failed");
|
||||
});
|
||||
ArduinoOTA.begin();
|
||||
}
|
||||
|
||||
// receive encrypted packets -> send it via MQTT to decrypter
|
||||
void waterMeterLoop()
|
||||
{
|
||||
if (waterMeter.isFrameAvailable())
|
||||
{
|
||||
// publish meter info via MQTT
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
void setup()
|
||||
{
|
||||
pinMode(LED_BUILTIN, OUTPUT);
|
||||
|
||||
Serial.begin(115200);
|
||||
|
||||
waterMeter.begin();
|
||||
Serial.println("Setup done...");
|
||||
}
|
||||
|
||||
enum ControlStateType
|
||||
{ StateInit
|
||||
, StateNotConnected
|
||||
, StateWifiConnect
|
||||
, StateMqttConnect
|
||||
, StateConnected
|
||||
, StateOperating
|
||||
};
|
||||
ControlStateType ControlState = StateInit;
|
||||
|
||||
void loop()
|
||||
{
|
||||
switch (ControlState)
|
||||
{
|
||||
case StateInit:
|
||||
//Serial.println("StateInit:");
|
||||
WiFi.mode(WIFI_STA);
|
||||
|
||||
ControlState = StateNotConnected;
|
||||
break;
|
||||
|
||||
case StateNotConnected:
|
||||
//Serial.println("StateNotConnected:");
|
||||
|
||||
ControlState = StateWifiConnect;
|
||||
break;
|
||||
|
||||
case StateWifiConnect:
|
||||
//Serial.println("StateWifiConnect:");
|
||||
// station mode
|
||||
ConnectWifi();
|
||||
|
||||
delay(500);
|
||||
|
||||
if (WiFi.status() == WL_CONNECTED)
|
||||
{
|
||||
Serial.println("");
|
||||
Serial.print("Connected to ");
|
||||
Serial.println(credentials[cred][0]); // FIXME
|
||||
Serial.print("IP address: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
|
||||
setupOTA();
|
||||
|
||||
ControlState = StateMqttConnect;
|
||||
}
|
||||
else
|
||||
{
|
||||
Serial.println("");
|
||||
Serial.println("Connection failed.");
|
||||
|
||||
// try again
|
||||
ControlState = StateNotConnected;
|
||||
|
||||
// reboot
|
||||
ESP.restart();
|
||||
}
|
||||
break;
|
||||
|
||||
case StateMqttConnect:
|
||||
Serial.println("StateMqttConnect:");
|
||||
digitalWrite(LED_BUILTIN, HIGH); // off
|
||||
|
||||
if (WiFi.status() != WL_CONNECTED)
|
||||
{
|
||||
ControlState = StateNotConnected;
|
||||
break; // exit (hopefully) switch statement
|
||||
}
|
||||
|
||||
Serial.print("try to connect to MQTT server ");
|
||||
Serial.println(credentials[cred][2]); // FIXME
|
||||
|
||||
if (mqttConnect())
|
||||
{
|
||||
ControlState = StateConnected;
|
||||
}
|
||||
else
|
||||
{
|
||||
Serial.println("MQTT connect failed");
|
||||
|
||||
delay(1000);
|
||||
// try again
|
||||
}
|
||||
ArduinoOTA.handle();
|
||||
|
||||
break;
|
||||
|
||||
case StateConnected:
|
||||
Serial.println("StateConnected:");
|
||||
|
||||
if (!mqttClient.connected())
|
||||
{
|
||||
ControlState = StateMqttConnect;
|
||||
delay(1000);
|
||||
}
|
||||
else
|
||||
{
|
||||
// subscribe to given topics
|
||||
mqttSubscribe();
|
||||
|
||||
ControlState = StateOperating;
|
||||
digitalWrite(LED_BUILTIN, LOW); // on
|
||||
Serial.println("StateOperating:");
|
||||
//mqttDebug("up and running");
|
||||
}
|
||||
ArduinoOTA.handle();
|
||||
|
||||
break;
|
||||
|
||||
case StateOperating:
|
||||
//Serial.println("StateOperating:");
|
||||
|
||||
if (WiFi.status() != WL_CONNECTED)
|
||||
{
|
||||
ControlState = StateWifiConnect;
|
||||
break; // exit (hopefully switch statement)
|
||||
}
|
||||
|
||||
if (!mqttClient.connected())
|
||||
{
|
||||
Serial.println("not connected to MQTT server");
|
||||
ControlState = StateMqttConnect;
|
||||
}
|
||||
|
||||
// here we go
|
||||
waterMeterLoop();
|
||||
|
||||
mqttClient.loop();
|
||||
|
||||
ArduinoOTA.handle();
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
Serial.println("Error: invalid ControlState");
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue