34class TMP102 :
public Thermometer {
40 bool alertPolarity =
false;
42 bool alertMode =
false;
43 double thresholdPercentage = 30.0;
46 explicit TMP102(uint8_t address,
56 explicit TMP102(uint8_t address = 0x48,
58 TwoWire *wire = &Wire)
63 initSensor(address_, wire_);
64 channel.setNewValue(getTemp());
67 double getTemp()
override {
68 double t = TEMPERATURE_NOT_AVAILABLE;
69 if (mutex_) mutex_->lock();
71 t = tmp102_.readTempC();
73 if (mutex_) mutex_->unlock();
74 if (t == TEMPERATURE_NOT_AVAILABLE) {
77 if (t < -40.0 || t > 125.0) {
78 SUPLA_LOG_WARNING(
"[TMP102] invalid reading: %.2f", t);
79 return TEMPERATURE_NOT_AVAILABLE;
81 if (lastValidTemperature_ != TEMPERATURE_NOT_AVAILABLE) {
82 double diff = percentageDifference(t, lastValidTemperature_);
83 if (diff > cfg_.thresholdPercentage) {
84 SUPLA_LOG_DEBUG(
"[TMP102] rejected value: %.2f (diff: %d%%)", t,
85 static_cast<int>(diff));
86 return lastValidTemperature_;
89 lastValidTemperature_ = std::round(t * 100) / 100.0;
90 return lastValidTemperature_;
93 bool getAlertState() {
94 if (mutex_) mutex_->lock();
95 bool raw = tmp102_.alert();
96 if (mutex_) mutex_->unlock();
97 return cfg_.alertMode ? raw : !raw;
103 TwoWire *wire_ =
nullptr;
104 Supla::Mutex *mutex_ =
nullptr;
105 uint8_t address_ = 0x48;
106 bool isConnected_ =
false;
107 double lastValidTemperature_ = TEMPERATURE_NOT_AVAILABLE;
109 void initSensor(uint8_t address, TwoWire *wire) {
110 if (mutex_) mutex_->lock();
111 if (tmp102_.begin(address, *wire)) {
112 SUPLA_LOG_DEBUG(
"TMP102 connected at 0x%x", address);
114 tmp102_.setHighTempC(cfg_.hTemp);
115 tmp102_.setLowTempC(cfg_.lTemp);
116 tmp102_.setExtendedMode(cfg_.extMode);
117 tmp102_.setAlertPolarity(cfg_.alertPolarity);
118 tmp102_.setFault(cfg_.fault);
119 tmp102_.setAlertMode(cfg_.alertMode);
122 SUPLA_LOG_ERROR(
"Unable to find TMP102 at 0x%x", address);
124 if (mutex_) mutex_->unlock();
127 static double percentageDifference(
double a,
double b) {
128 return std::abs(a - b) / b * 100.0;