summaryrefslogtreecommitdiff
path: root/platformio/temphum
diff options
context:
space:
mode:
Diffstat (limited to 'platformio/temphum')
-rw-r--r--platformio/temphum/src/leds.cpp11
-rw-r--r--platformio/temphum/src/leds.h15
-rw-r--r--platformio/temphum/src/main.cpp217
-rw-r--r--platformio/temphum/src/mqtt.cpp316
-rw-r--r--platformio/temphum/src/mqtt.h114
-rw-r--r--platformio/temphum/src/temphum.cpp76
-rw-r--r--platformio/temphum/src/temphum.h37
7 files changed, 19 insertions, 767 deletions
diff --git a/platformio/temphum/src/leds.cpp b/platformio/temphum/src/leds.cpp
deleted file mode 100644
index f0c9d51..0000000
--- a/platformio/temphum/src/leds.cpp
+++ /dev/null
@@ -1,11 +0,0 @@
-#include "leds.h"
-
-namespace homekit {
-
-#ifdef CONFIG_TARGET_NODEMCU
-Led* board_led = new Led(CONFIG_BOARD_LED_GPIO);
-#endif
-Led* mcu_led = new Led(CONFIG_MCU_LED_GPIO);
-
-}
-
diff --git a/platformio/temphum/src/leds.h b/platformio/temphum/src/leds.h
deleted file mode 100644
index 04c1f79..0000000
--- a/platformio/temphum/src/leds.h
+++ /dev/null
@@ -1,15 +0,0 @@
-#ifndef HOMEKIT_TEMPHUM_LEDS_H
-#define HOMEKIT_TEMPHUM_LEDS_H
-
-#include <homekit/led.h>
-
-namespace homekit {
-
-#ifdef CONFIG_TARGET_NODEMCU
-extern Led* board_led;
-#endif
-extern Led* mcu_led;
-
-}
-
-#endif //HOMEKIT_TEMPHUM_LEDS_H \ No newline at end of file
diff --git a/platformio/temphum/src/main.cpp b/platformio/temphum/src/main.cpp
index 6e878a1..2df8638 100644
--- a/platformio/temphum/src/main.cpp
+++ b/platformio/temphum/src/main.cpp
@@ -1,109 +1,26 @@
#include <Arduino.h>
-#include <ESP8266WiFi.h>
-#include <DNSServer.h>
-#include <Ticker.h>
#include <Wire.h>
-
-#include <homekit/config.h>
-#include <homekit/logging.h>
-#ifndef CONFIG_TARGET_ESP01
-#include <homekit/http_server.h>
-#endif
-#include <homekit/wifi.h>
-
-#include "mqtt.h"
-#include "leds.h"
-#include "temphum.h"
+#include <homekit/main.h>
+#include <homekit/mqtt/mqtt.h>
+#include <homekit/mqtt/module/temphum.h>
+#include <homekit/temphum.h>
using namespace homekit;
+using main::LoopConfig;
+using mqtt::Mqtt;
+using mqtt::MqttTemphumModule;
-#ifndef CONFIG_TARGET_ESP01
-enum class WorkingMode {
- RECOVERY, // AP mode, http server with configuration
- NORMAL, // MQTT client
-};
-static enum WorkingMode working_mode = WorkingMode::NORMAL;
+temphum::Sensor* sensor = nullptr;
+MqttTemphumModule* mqttTemphumModule = nullptr;
-static const uint16_t recovery_boot_detection_ms = 2000;
-static const uint8_t recovery_boot_delay_ms = 100;
-#endif
+static void onMqttCreated(Mqtt& mqtt);
-enum class WiFiConnectionState {
- WAITING = 0,
- JUST_CONNECTED = 1,
- CONNECTED = 2
+LoopConfig loopConfig = {
+ .onMqttCreated = onMqttCreated
};
-static volatile enum WiFiConnectionState wifi_state = WiFiConnectionState::WAITING;
-static void* service = nullptr;
-static WiFiEventHandler wifiConnectHandler, wifiDisconnectHandler;
-static Ticker wifiTimer;
-temphum::BaseSensor* sensor = nullptr;
-
-#if MQTT_BLINK
-static StopWatch blinkStopWatch;
-#endif
-
-#ifndef CONFIG_TARGET_ESP01
-static DNSServer* dnsServer = nullptr;
-#endif
-
-static void onWifiConnected(const WiFiEventStationModeGotIP& event);
-static void onWifiDisconnected(const WiFiEventStationModeDisconnected& event);
-
-static void wifiConnect() {
- const char *ssid, *psk, *hostname;
- auto cfg = config::read();
- wifi::getConfig(cfg, &ssid, &psk, &hostname);
-
- PRINTF("Wi-Fi STA creds: ssid=%s, psk=%s, hostname=%s\n", ssid, psk, hostname);
-
- wifi_state = WiFiConnectionState::WAITING;
-
- WiFi.mode(WIFI_STA);
- WiFi.hostname(hostname);
- WiFi.begin(ssid, psk);
-
- PRINT("connecting to wifi..");
-}
-
-#ifndef CONFIG_TARGET_ESP01
-static void wifiHotspot() {
- mcu_led->on();
-
- auto scanResults = wifi::scan();
-
- WiFi.mode(WIFI_AP);
- WiFi.softAP(wifi::AP_SSID);
-
- dnsServer = new DNSServer();
- dnsServer->start(53, "*", WiFi.softAPIP());
-
- service = new HttpServer(scanResults);
- ((HttpServer*)service)->start();
-}
-
-static void waitForRecoveryPress() {
- pinMode(CONFIG_FLASH_GPIO, INPUT_PULLUP);
- for (uint16_t i = 0; i < recovery_boot_detection_ms; i += recovery_boot_delay_ms) {
- delay(recovery_boot_delay_ms);
- if (digitalRead(CONFIG_FLASH_GPIO) == LOW) {
- working_mode = WorkingMode::RECOVERY;
- break;
- }
- }
-}
-#endif
-
void setup() {
- WiFi.disconnect();
-#ifndef CONFIG_TARGET_ESP01
- waitForRecoveryPress();
-#endif
-
-#ifdef DEBUG
- Serial.begin(115200);
-#endif
+ main::setup();
#if CONFIG_MODULE == HOMEKIT_SI7021
sensor = new temphum::Si7021();
@@ -111,111 +28,15 @@ void setup() {
sensor = new temphum::DHT12();
#endif
sensor->setup();
-
- auto cfg = config::read();
- if (config::isDirty(cfg)) {
- PRINTLN("config is dirty, erasing...");
- config::erase(cfg);
-#ifdef CONFIG_TARGET_NODEMCU
- board_led->blink(10, 50);
-#else
- mcu_led->blink(10, 50);
-#endif
- }
-
-#ifndef CONFIG_TARGET_ESP01
- switch (working_mode) {
- case WorkingMode::RECOVERY:
- wifiHotspot();
- break;
-
- case WorkingMode::NORMAL:
-#endif
- wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnected);
- wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnected);
- wifiConnect();
-#ifndef CONFIG_TARGET_ESP01
- break;
- }
-#endif
}
void loop() {
-#ifndef CONFIG_TARGET_ESP01
- if (working_mode == WorkingMode::NORMAL) {
-#endif
- if (wifi_state == WiFiConnectionState::WAITING) {
- PRINT(".");
- mcu_led->blink(2, 50);
- delay(1000);
- return;
- }
-
- if (wifi_state == WiFiConnectionState::JUST_CONNECTED) {
-#ifdef CONFIG_TARGET_NODEMCU
- board_led->blink(3, 300);
-#endif
- wifi_state = WiFiConnectionState::CONNECTED;
-
- if (service == nullptr)
- service = new mqtt::MQTT();
-
- ((mqtt::MQTT*)service)->connect();
-#if MQTT_BLINK
- blinkStopWatch.save();
-#endif
- }
-
- auto mqtt = (mqtt::MQTT*)service;
- if (static_cast<int>(wifi_state) >= 1 && mqtt != nullptr) {
- mqtt->loop();
-
- if (mqtt->ota.readyToRestart) {
- mqtt->disconnect();
-
- } else if (mqtt->diagnosticsStopWatch.elapsed(10000)) {
- mqtt->sendDiagnostics();
-
- auto data = sensor->read();
- PRINT("temp:");
- PRINT(data.temp);
- PRINT(", rh: ");
- PRINTLN(data.rh);
-
- mqtt->sendTempHumData(data.temp, data.rh);
- }
-
-#if MQTT_BLINK
- // periodically blink board led
- if (blinkStopWatch.elapsed(5000)) {
-#ifdef CONFIG_TARGET_NODEMCU
- board_led->blink(1, 10);
-#endif
- blinkStopWatch.save();
- }
-#endif
- }
-#ifndef CONFIG_TARGET_ESP01
- } else {
- if (dnsServer != nullptr)
- dnsServer->processNextRequest();
-
- auto httpServer = (HttpServer*)service;
- if (httpServer != nullptr)
- httpServer->loop();
- }
-#endif
+ main::loop(&loopConfig);
}
-static void onWifiConnected(const WiFiEventStationModeGotIP& event) {
- PRINTF("connected (%s)\n", WiFi.localIP().toString().c_str());
- wifi_state = WiFiConnectionState::JUST_CONNECTED;
-}
-
-static void onWifiDisconnected(const WiFiEventStationModeDisconnected& event) {
- PRINTLN("disconnected from wi-fi");
- wifi_state = WiFiConnectionState::WAITING;
- if (service != nullptr)
- ((mqtt::MQTT*)service)->disconnect();
- wifiTimer.once(2, wifiConnect);
+static void onMqttCreated(Mqtt& mqtt) {
+ if (mqttTemphumModule == nullptr) {
+ mqttTemphumModule = new MqttTemphumModule(sensor);
+ mqtt.addModule(mqttTemphumModule);
+ }
} \ No newline at end of file
diff --git a/platformio/temphum/src/mqtt.cpp b/platformio/temphum/src/mqtt.cpp
deleted file mode 100644
index e912f35..0000000
--- a/platformio/temphum/src/mqtt.cpp
+++ /dev/null
@@ -1,316 +0,0 @@
-#include <ESP8266httpUpdate.h>
-#include <homekit/logging.h>
-#include <homekit/config.h>
-#include <homekit/util.h>
-#include <homekit/wifi.h>
-
-#include "mqtt.h"
-#include "leds.h"
-
-namespace homekit::mqtt {
-
-static const char TOPIC_DIAGNOSTICS[] = "stat";
-static const char TOPIC_INITIAL_DIAGNOSTICS[] = "stat1";
-static const char TOPIC_OTA_RESPONSE[] = "otares";
-static const char TOPIC_TEMPHUM_DATA[] = "data";
-static const char TOPIC_ADMIN_OTA[] = "admin/ota";
-static const uint16_t MQTT_KEEPALIVE = 30;
-
-enum class IncomingMessage {
- UNKNOWN,
- OTA
-};
-
-using namespace espMqttClientTypes;
-
-#define MD5_SIZE 16
-
-MQTT::MQTT() {
- auto cfg = config::read();
- homeId = String(cfg.flags.node_configured ? cfg.node_id : wifi::NODE_ID);
-
- randomSeed(micros());
-
- client.onConnect([&](bool sessionPresent) {
- PRINTLN("mqtt: connected");
-
- sendInitialDiagnostics();
- subscribe(TOPIC_ADMIN_OTA);
- });
-
- client.onDisconnect([&](DisconnectReason reason) {
- PRINTF("mqtt: disconnected, reason=%d\n", static_cast<int>(reason));
-#ifdef DEBUG
- if (reason == DisconnectReason::TLS_BAD_FINGERPRINT)
- PRINTLN("reason: bad fingerprint");
-#endif
-
- if (ota.started()) {
- PRINTLN("mqtt: update was in progress, canceling..");
- ota.clean();
- Update.end();
- Update.clearError();
- }
-
- if (ota.readyToRestart) {
- restartTimer.once(1, restart);
- } else {
- reconnectTimer.once(2, [&]() {
- reconnect();
- });
- }
- });
-
- client.onSubscribe([&](uint16_t packetId, const SubscribeReturncode* returncodes, size_t len) {
- PRINTF("mqtt: subscribe ack, packet_id=%d\n", packetId);
- for (size_t i = 0; i < len; i++) {
- PRINTF(" return code: %u\n", static_cast<unsigned int>(*(returncodes+i)));
- }
- });
-
- client.onUnsubscribe([&](uint16_t packetId) {
- PRINTF("mqtt: unsubscribe ack, packet_id=%d\n", packetId);
- });
-
- client.onMessage([&](const MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total) {
- PRINTF("mqtt: message received, topic=%s, qos=%d, dup=%d, retain=%d, len=%ul, index=%ul, total=%ul\n",
- topic, properties.qos, (int)properties.dup, (int)properties.retain, len, index, total);
-
- IncomingMessage msgType = IncomingMessage::UNKNOWN;
-
- const char *ptr = topic + homeId.length() + 10;
- String relevantTopic(ptr);
-
- if (relevantTopic == TOPIC_ADMIN_OTA)
- msgType = IncomingMessage::OTA;
-
- if (len != total && msgType != IncomingMessage::OTA) {
- PRINTLN("mqtt: received partial message, not supported");
- return;
- }
-
- switch (msgType) {
- case IncomingMessage::OTA:
- if (ota.finished)
- break;
- handleAdminOtaPayload(properties.packetId, payload, len, index, total);
- break;
-
- case IncomingMessage::UNKNOWN:
- PRINTF("error: invalid topic %s\n", topic);
- break;
- }
- });
-
- client.onPublish([&](uint16_t packetId) {
- PRINTF("mqtt: publish ack, packet_id=%d\n", packetId);
-
- if (ota.finished && packetId == ota.publishResultPacketId) {
- ota.readyToRestart = true;
- }
- });
-
- client.setServer(MQTT_SERVER, MQTT_PORT);
- client.setClientId(MQTT_CLIENT_ID);
- client.setCredentials(MQTT_USERNAME, MQTT_PASSWORD);
- client.setCleanSession(true);
- client.setFingerprint(MQTT_CA_FINGERPRINT);
- client.setKeepAlive(MQTT_KEEPALIVE);
-}
-
-void MQTT::connect() {
- reconnect();
-}
-
-void MQTT::reconnect() {
- if (client.connected()) {
- PRINTLN("warning: already connected");
- return;
- }
- client.connect();
-}
-
-void MQTT::disconnect() {
- // TODO test how this works???
- reconnectTimer.detach();
- client.disconnect();
-}
-
-uint16_t MQTT::publish(const String &topic, uint8_t *payload, size_t length) {
- String fullTopic = "hk/" + homeId + "/temphum/" + topic;
- return client.publish(fullTopic.c_str(), 1, false, payload, length);
-}
-
-void MQTT::loop() {
- client.loop();
-}
-
-uint16_t MQTT::subscribe(const String &topic, uint8_t qos) {
- String fullTopic = "hk/" + homeId + "/temphum/" + topic;
- PRINTF("mqtt: subscribing to %s...\n", fullTopic.c_str());
-
- uint16_t packetId = client.subscribe(fullTopic.c_str(), qos);
- if (!packetId)
- PRINTF("error: failed to subscribe to %s\n", fullTopic.c_str());
- return packetId;
-}
-
-void MQTT::sendInitialDiagnostics() {
- auto cfg = config::read();
- InitialDiagnosticsPayload stat{
- .ip = wifi::getIPAsInteger(),
- .fw_version = CONFIG_FW_VERSION,
- .rssi = wifi::getRSSI(),
- .free_heap = ESP.getFreeHeap(),
- .flags = DiagnosticsFlags{
- .state = 1,
- .config_changed_value_present = 1,
- .config_changed = static_cast<uint8_t>(cfg.flags.node_configured ||
- cfg.flags.wifi_configured ? 1 : 0)
- }
- };
- publish(TOPIC_INITIAL_DIAGNOSTICS, reinterpret_cast<uint8_t*>(&stat), sizeof(stat));
- diagnosticsStopWatch.save();
-}
-
-void MQTT::sendDiagnostics() {
- DiagnosticsPayload stat{
- .rssi = wifi::getRSSI(),
- .free_heap = ESP.getFreeHeap(),
- .flags = DiagnosticsFlags{
- .state = 1,
- .config_changed_value_present = 0,
- .config_changed = 0
- }
- };
- publish(TOPIC_DIAGNOSTICS, reinterpret_cast<uint8_t*>(&stat), sizeof(stat));
- diagnosticsStopWatch.save();
-}
-
-void MQTT::sendTempHumData(double temp, double rh) {
- TempHumDataPayload data {
- .temp = temp,
- .rh = rh
- };
- publish(TOPIC_TEMPHUM_DATA, reinterpret_cast<uint8_t*>(&data), sizeof(data));
-}
-
-uint16_t MQTT::sendOtaResponse(OTAResult status, uint8_t error_code) {
- OTAResponse resp{
- .status = status,
- .error_code = error_code
- };
- return publish(TOPIC_OTA_RESPONSE, reinterpret_cast<uint8_t*>(&resp), sizeof(resp));
-}
-
-void MQTT::handleAdminOtaPayload(uint16_t packetId, const uint8_t *payload, size_t length, size_t index, size_t total) {
- char md5[33];
- char* md5Ptr = md5;
-
- if (index != 0 && ota.dataPacketId != packetId) {
- PRINTLN("mqtt/ota: non-matching packet id");
- return;
- }
-
- Update.runAsync(true);
-
- if (index == 0) {
- if (length < CONFIG_NODE_SECRET_SIZE + MD5_SIZE) {
- PRINTLN("mqtt/ota: failed to check secret, first packet size is too small");
- return;
- }
-
- if (memcmp((const char*)payload, CONFIG_NODE_SECRET, CONFIG_NODE_SECRET_SIZE) != 0) {
- PRINTLN("mqtt/ota: invalid secret");
- return;
- }
-
- PRINTF("mqtt/ota: starting update, total=%ul\n", total-CONFIG_NODE_SECRET_SIZE);
- for (int i = 0; i < MD5_SIZE; i++) {
- md5Ptr += sprintf(md5Ptr, "%02x", *((unsigned char*)(payload+CONFIG_NODE_SECRET_SIZE+i)));
- }
- md5[32] = '\0';
- PRINTF("mqtt/ota: md5 is %s\n", md5);
- PRINTF("mqtt/ota: first packet is %ul bytes length\n", length);
-
- md5[32] = '\0';
-
- if (Update.isRunning()) {
- Update.end();
- Update.clearError();
- }
-
- if (!Update.setMD5(md5)) {
- PRINTLN("mqtt/ota: setMD5 failed");
- return;
- }
-
- ota.dataPacketId = packetId;
-
- if (!Update.begin(total - CONFIG_NODE_SECRET_SIZE - MD5_SIZE)) {
- ota.clean();
-#ifdef DEBUG
- Update.printError(Serial);
-#endif
- sendOtaResponse(OTAResult::UPDATE_ERROR, Update.getError());
- }
-
- ota.written = Update.write(const_cast<uint8_t*>(payload)+CONFIG_NODE_SECRET_SIZE + MD5_SIZE, length-CONFIG_NODE_SECRET_SIZE - MD5_SIZE);
- ota.written += CONFIG_NODE_SECRET_SIZE + MD5_SIZE;
-
- mcu_led->blink(1, 1);
- PRINTF("mqtt/ota: updating %u/%u\n", ota.written, Update.size());
-
- } else {
- if (!Update.isRunning()) {
- PRINTLN("mqtt/ota: update is not running");
- return;
- }
-
- if (index == ota.written) {
- size_t written;
- if ((written = Update.write(const_cast<uint8_t*>(payload), length)) != length) {
- PRINTF("mqtt/ota: error: tried to write %ul bytes, write() returned %ul\n",
- length, written);
- ota.clean();
- Update.end();
- Update.clearError();
- sendOtaResponse(OTAResult::WRITE_ERROR);
- return;
- }
- ota.written += length;
-
- mcu_led->blink(1, 1);
- PRINTF("mqtt/ota: updating %u/%u\n",
- ota.written - CONFIG_NODE_SECRET_SIZE - MD5_SIZE,
- Update.size());
- } else {
- PRINTF("mqtt/ota: position is invalid, expected %ul, got %ul\n", ota.written, index);
- ota.clean();
- Update.end();
- Update.clearError();
- }
- }
-
- if (Update.isFinished()) {
- ota.dataPacketId = 0;
-
- if (Update.end()) {
- ota.finished = true;
- ota.publishResultPacketId = sendOtaResponse(OTAResult::OK);
- PRINTF("mqtt/ota: ok, otares packet_id=%d\n", ota.publishResultPacketId);
- } else {
- ota.clean();
-
- PRINTF("mqtt/ota: error: %u\n", Update.getError());
-#ifdef DEBUG
- Update.printError(Serial);
-#endif
- Update.clearError();
-
- sendOtaResponse(OTAResult::UPDATE_ERROR, Update.getError());
- }
- }
-}
-
-} \ No newline at end of file
diff --git a/platformio/temphum/src/mqtt.h b/platformio/temphum/src/mqtt.h
deleted file mode 100644
index 84df5b1..0000000
--- a/platformio/temphum/src/mqtt.h
+++ /dev/null
@@ -1,114 +0,0 @@
-#ifndef HOMEKIT_TEMPHUM_MQTT_H
-#define HOMEKIT_TEMPHUM_MQTT_H
-
-#include <ESP8266WiFi.h>
-#include <espMqttClient.h>
-#include <Ticker.h>
-
-#include <homekit/stopwatch.h>
-#include <homekit/mqtt.h>
-
-namespace homekit { namespace mqtt {
-
-enum class OTAResult: uint8_t {
- OK = 0,
- UPDATE_ERROR = 1,
- WRITE_ERROR = 2,
-};
-
-struct OTAStatus {
- uint16_t dataPacketId;
- uint16_t publishResultPacketId;
- bool finished;
- bool readyToRestart;
- size_t written;
-
- OTAStatus()
- : dataPacketId(0)
- , publishResultPacketId(0)
- , finished(false)
- , readyToRestart(false)
- , written(0)
- {}
-
- inline void clean() {
- dataPacketId = 0;
- publishResultPacketId = 0;
- finished = false;
- readyToRestart = false;
- written = 0;
- }
-
- inline bool started() const {
- return dataPacketId != 0;
- }
-};
-
-class MQTT {
-private:
- String homeId;
- WiFiClientSecure httpsSecureClient;
- espMqttClientSecure client;
- Ticker reconnectTimer;
- Ticker restartTimer;
-
- void handleAdminOtaPayload(uint16_t packetId, const uint8_t* payload, size_t length, size_t index, size_t total);
-
- uint16_t publish(const String& topic, uint8_t* payload, size_t length);
- uint16_t subscribe(const String& topic, uint8_t qos = 0);
-
- void sendInitialDiagnostics();
- uint16_t sendOtaResponse(OTAResult status, uint8_t error_code = 0);
-
-public:
- StopWatch diagnosticsStopWatch;
- OTAStatus ota;
-
- MQTT();
- void connect();
- void disconnect();
- void reconnect();
- void loop();
- void sendDiagnostics();
- void sendTempHumData(double temp, double rh);
-};
-
-struct DiagnosticsFlags {
- uint8_t state: 1;
- uint8_t config_changed_value_present: 1;
- uint8_t config_changed: 1;
- uint8_t reserved: 5;
-} __attribute__((packed));
-
-struct InitialDiagnosticsPayload {
- uint32_t ip;
- uint8_t fw_version;
- int8_t rssi;
- uint32_t free_heap;
- DiagnosticsFlags flags;
-} __attribute__((packed));
-
-struct DiagnosticsPayload {
- int8_t rssi;
- uint32_t free_heap;
- DiagnosticsFlags flags;
-} __attribute__((packed));
-
-struct PowerPayload {
- char secret[12];
- uint8_t state;
-} __attribute__((packed));
-
-struct TempHumDataPayload {
- double temp;
- double rh;
-} __attribute__((packed));
-
-struct OTAResponse {
- OTAResult status;
- uint8_t error_code;
-} __attribute__((packed));
-
-} }
-
-#endif //HOMEKIT_TEMPHUM_MQTT_H \ No newline at end of file
diff --git a/platformio/temphum/src/temphum.cpp b/platformio/temphum/src/temphum.cpp
deleted file mode 100644
index 164f01e..0000000
--- a/platformio/temphum/src/temphum.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-#ifndef CONFIG_TARGET_ESP01
-#include <Arduino.h>
-#endif
-#include <homekit/logging.h>
-#include "temphum.h"
-
-namespace homekit::temphum {
-
-void BaseSensor::setup() const {
-#ifndef CONFIG_TARGET_ESP01
- pinMode(CONFIG_SDA_GPIO, OUTPUT);
- pinMode(CONFIG_SCL_GPIO, OUTPUT);
-
- Wire.begin(CONFIG_SDA_GPIO, CONFIG_SCL_GPIO);
-#else
- Wire.begin();
-#endif
-}
-
-void BaseSensor::writeCommand(int reg) const {
- Wire.beginTransmission(dev_addr);
- Wire.write(reg);
- Wire.endTransmission();
- delay(500); // wait for the measurement to be ready
-}
-
-SensorData Si7021::read() {
- writeCommand(0xf3); // command to measure temperature
- Wire.requestFrom(dev_addr, 2);
- uint16_t temp_raw = Wire.read() << 8 | Wire.read();
- double temperature = ((175.72 * temp_raw) / 65536.0) - 46.85;
-
- writeCommand(0xf5); // command to measure humidity
- Wire.requestFrom(dev_addr, 2);
- uint16_t hum_raw = Wire.read() << 8 | Wire.read();
- double humidity = ((125.0 * hum_raw) / 65536.0) - 6.0;
-
- return {
- .temp = temperature,
- .rh = humidity
- };
-}
-
-SensorData DHT12::read() {
- SensorData sd;
- byte raw[5];
-
- writeCommand(0);
- Wire.requestFrom(dev_addr, 5);
-
- if (Wire.available() < 5) {
- PRINTLN("DHT12: could not read 5 bytes");
- goto end;
- }
-
- // Parse the received data
- for (uint8_t i = 0; i < 5; i++)
- raw[i] = Wire.read();
-
- if (((raw[0] + raw[1] + raw[2] + raw[3]) & 0xff) != raw[4]) {
- PRINTLN("DHT12: checksum error");
- goto end;
- }
-
- // Calculate temperature and humidity values
- sd.temp = raw[2] + (raw[3] & 0x7f) * 0.1;
- if (raw[3] & 0x80)
- sd.temp *= -1;
-
- sd.rh = raw[0] + raw[1] * 0.1;
-
-end:
- return sd;
-}
-
-} \ No newline at end of file
diff --git a/platformio/temphum/src/temphum.h b/platformio/temphum/src/temphum.h
deleted file mode 100644
index 3d8f373..0000000
--- a/platformio/temphum/src/temphum.h
+++ /dev/null
@@ -1,37 +0,0 @@
-#pragma once
-
-#include <Wire.h>
-
-namespace homekit::temphum {
-
-struct SensorData {
- double temp = 0; // celsius
- double rh = 0; // relative humidity percentage
-};
-
-
-class BaseSensor {
-protected:
- int dev_addr;
-public:
- explicit BaseSensor(int dev) : dev_addr(dev) {}
- void setup() const;
- void writeCommand(int reg) const;
- virtual SensorData read() = 0;
-};
-
-
-class Si7021 : public BaseSensor {
-public:
- SensorData read() override;
- Si7021() : BaseSensor(0x40) {}
-};
-
-
-class DHT12 : public BaseSensor {
-public:
- SensorData read() override;
- DHT12() : BaseSensor(0x5c) {}
-};
-
-} \ No newline at end of file