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.

81 lines
2.0 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. unsigned char tmpUnits = getSetting("tmpUnits", TMP_UNITS).toInt();
  30. // Read sensor data
  31. ds18b20.requestTemperatures();
  32. double t = (tmpUnits == TMP_CELSIUS) ? ds18b20.getTempCByIndex(0) : ds18b20.getTempFByIndex(0);
  33. // Check if readings are valid
  34. if (isnan(t)) {
  35. DEBUG_MSG("[DS18B20] Error reading sensor\n");
  36. } else {
  37. _dsTemperature = t;
  38. char temperature[6];
  39. dtostrf(t, 5, 1, temperature);
  40. DEBUG_MSG("[DS18B20] Temperature: %s%s\n", temperature, (tmpUnits == TMP_CELSIUS) ? "ºC" : "ºF");
  41. // Send MQTT messages
  42. mqttSend(getSetting("dsTmpTopic", DS_TEMPERATURE_TOPIC).c_str(), temperature);
  43. // Send to Domoticz
  44. #if ENABLE_DOMOTICZ
  45. domoticzSend("dczTmpIdx", 0, temperature);
  46. #endif
  47. // Update websocket clients
  48. char buffer[100];
  49. sprintf_P(buffer, PSTR("{\"dsVisible\": 1, \"dsTmp\": %s, \"tmpUnits\": %d}"), temperature, tmpUnits);
  50. wsSend(buffer);
  51. }
  52. }
  53. }
  54. #endif