Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.8 KiB

  1. /*
  2. DS18B20 MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if ENABLE_DS18B20
  6. #include <OneWire.h>
  7. #include <DallasTemperature.h>
  8. OneWire oneWire(DS_PIN);
  9. DallasTemperature ds18b20(&oneWire);
  10. double _dsTemperature = 0;
  11. // -----------------------------------------------------------------------------
  12. // DS18B20
  13. // -----------------------------------------------------------------------------
  14. double getDSTemperature() {
  15. return _dsTemperature;
  16. }
  17. void dsSetup() {
  18. ds18b20.begin();
  19. apiRegister("/api/temperature", "temperature", [](char * buffer, size_t len) {
  20. dtostrf(_dsTemperature, len-1, 1, buffer);
  21. });
  22. }
  23. void dsLoop() {
  24. if (!mqttConnected()) return;
  25. // Check if we should read new data
  26. static unsigned long last_update = 0;
  27. if ((millis() - last_update > DS_UPDATE_INTERVAL) || (last_update == 0)) {
  28. last_update = millis();
  29. // Read sensor data
  30. ds18b20.requestTemperatures();
  31. double t = ds18b20.getTempCByIndex(0);
  32. // Check if readings are valid
  33. if (isnan(t)) {
  34. DEBUG_MSG("[DS18B20] Error reading sensor\n");
  35. } else {
  36. _dsTemperature = t;
  37. char temperature[6];
  38. dtostrf(t, 5, 1, temperature);
  39. DEBUG_MSG("[DS18B20] Temperature: %s\n", temperature);
  40. // Send MQTT messages
  41. mqttSend(getSetting("dsTmpTopic", DS_TEMPERATURE_TOPIC).c_str(), temperature);
  42. // Send to Domoticz
  43. #if ENABLE_DOMOTICZ
  44. domoticzSend("dczTmpIdx", temperature);
  45. #endif
  46. // Update websocket clients
  47. char buffer[100];
  48. sprintf_P(buffer, PSTR("{\"dsVisible\": 1, \"dsTmp\": %s}"), temperature);
  49. wsSend(buffer);
  50. }
  51. }
  52. }
  53. #endif