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
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. // Check if we should read new data
  25. static unsigned long last_update = 0;
  26. if ((millis() - last_update > DS_UPDATE_INTERVAL) || (last_update == 0)) {
  27. last_update = millis();
  28. unsigned char tmpUnits = getSetting("tmpUnits", TMP_UNITS).toInt();
  29. // Read sensor data
  30. ds18b20.requestTemperatures();
  31. double t = (tmpUnits == TMP_CELSIUS) ? ds18b20.getTempCByIndex(0) : ds18b20.getTempFByIndex(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%s\n", temperature, (tmpUnits == TMP_CELSIUS) ? "ºC" : "ºF");
  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", 0, temperature);
  45. #endif
  46. // Update websocket clients
  47. char buffer[100];
  48. sprintf_P(buffer, PSTR("{\"dsVisible\": 1, \"dsTmp\": %s, \"tmpUnits\": %d}"), temperature, tmpUnits);
  49. wsSend(buffer);
  50. }
  51. }
  52. }
  53. #endif