Sensor3/lib/patrix/sensors/Dallas.h

91 lines
1.8 KiB
C++

#ifndef SENSOR2_DALLAS_H
#define SENSOR2_DALLAS_H
#include "wifi.h"
#include "log.h"
#include "OneWire.h"
#include "DallasTemperature.h"
#define DALLAS_TIMEOUT_MILLISECONDS 3000
class Dallas {
private:
OneWire oneWire;
DallasTemperature sensors;
time_t timestamp = 0;
unsigned long lastMillis = 0;
bool converting = false;
bool converted = false;
bool first = true;
public:
explicit Dallas(int pin) : oneWire(pin), sensors(&oneWire) {
sensors.begin();
sensors.setWaitForConversion(false);
}
void loop() {
if (converting) {
if (sensors.isConversionComplete()) {
if (first) {
first = false;
uint8_t count = sensors.getDeviceCount();
if (count == 0) {
error("DALLAS", "No devices found!");
} else {
debug("DALLAS", "Found %d devices:", count);
uint64_t address;
for (int index = 0; index < count; ++index) {
sensors.getAddress((uint8_t *) &address, index);
debug("DALLAS", " - 0x%016llX = %5.1f C", address, sensors.getTempC((uint8_t *) &address));
}
}
}
converting = false;
converted = true;
} else if (millis() - lastMillis > DALLAS_TIMEOUT_MILLISECONDS) {
error("DALLAS", "Timeout!");
converting = false;
converted = false;
}
} else {
sensors.requestTemperatures();
timestamp = getTime();
lastMillis = millis();
converting = true;
converted = false;
}
}
double read(uint64_t address) {
float value = sensors.getTempC((uint8_t *) &address);
if (value <= DEVICE_DISCONNECTED_C) {
return NAN;
}
return value;
}
time_t getTimestamp() const {
return timestamp;
}
bool isConverted() const {
return converted;
}
};
#endif