power_meter.ino 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include <EmonLib.h>
  2. #include <ESP8266WiFi.h>
  3. #include <PubSubClient.h>
  4. #define TOPIC "/home/sensors/power"
  5. #define MQTT_SERVER "192.168.1.3"
  6. #define SSID "GCHQ Surveillance Van"
  7. #define PASSWORD "cocklol."
  8. #define MAINS_VOLTAGE 230.0
  9. #define CALIBRATION 90.9090909091
  10. void callback(char *topic, byte *payload, unsigned int length);
  11. EnergyMonitor emon1;
  12. WiFiClient wifiClient;
  13. PubSubClient mqtt(MQTT_SERVER, 1883, callback, wifiClient);
  14. void callback(char *topic, byte *payload, unsigned int length) {}
  15. void waitForWiFi() {
  16. if (WiFi.status() == WL_CONNECTED)
  17. return;
  18. Serial.println("Reconnecting WiFi...");
  19. int waitCount=0;
  20. while (WiFi.status() != WL_CONNECTED) {
  21. delay(100);
  22. waitCount++;
  23. if (waitCount>600)
  24. ESP.restart();
  25. }
  26. Serial.println("Connected WiFi!");
  27. }
  28. void waitForMQTT() {
  29. if (mqtt.connected())
  30. return;
  31. Serial.println("Reconnecting MQTT...");
  32. while (!mqtt.connected())
  33. if (!mqtt.connect(TOPIC))
  34. delay(50);
  35. Serial.println("Connected MQTT!");
  36. }
  37. void reconnect() {
  38. waitForWiFi();
  39. waitForMQTT();
  40. }
  41. void setup() {
  42. Serial.begin(115200);
  43. WiFi.begin(SSID, PASSWORD);
  44. reconnect();
  45. emon1.current(A0, CALIBRATION);
  46. }
  47. void loop() {
  48. long startTick = millis();
  49. double Irms = emon1.calcIrms(1480);
  50. double kwh = Irms * MAINS_VOLTAGE;
  51. Serial.println(kwh);
  52. mqtt.publish(TOPIC, String(kwh).c_str());
  53. mqtt.loop();
  54. delay(10000 - (millis() - startTick));
  55. }