12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- #include <EmonLib.h>
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- #define TOPIC "/home/sensors/power"
- #define MQTT_SERVER "192.168.1.3"
- #define SSID "GCHQ Surveillance Van"
- #define PASSWORD "cocklol."
- #define MAINS_VOLTAGE 230.0
- #define CALIBRATION 90.9090909091
- void callback(char *topic, byte *payload, unsigned int length);
- EnergyMonitor emon1;
- WiFiClient wifiClient;
- PubSubClient mqtt(MQTT_SERVER, 1883, callback, wifiClient);
- void callback(char *topic, byte *payload, unsigned int length) {}
- void waitForWiFi() {
- if (WiFi.status() == WL_CONNECTED)
- return;
- Serial.println("Reconnecting WiFi...");
- int waitCount=0;
- while (WiFi.status() != WL_CONNECTED) {
- delay(100);
- waitCount++;
- if (waitCount>600)
- ESP.restart();
- }
- Serial.println("Connected WiFi!");
- }
- void waitForMQTT() {
- if (mqtt.connected())
- return;
- Serial.println("Reconnecting MQTT...");
- while (!mqtt.connected())
- if (!mqtt.connect(TOPIC))
- delay(50);
- Serial.println("Connected MQTT!");
- }
- void reconnect() {
- waitForWiFi();
- waitForMQTT();
- }
- void setup() {
- Serial.begin(115200);
- WiFi.begin(SSID, PASSWORD);
- reconnect();
- emon1.current(A0, CALIBRATION);
- }
- void loop() {
- long startTick = millis();
- double Irms = emon1.calcIrms(1480);
- double kwh = Irms * MAINS_VOLTAGE;
- Serial.println(kwh);
- mqtt.publish(TOPIC, String(kwh).c_str());
- mqtt.loop();
- delay(10000 - (millis() - startTick));
- }
|