summaryrefslogtreecommitdiff
path: root/platformio/temphum/src/main.cpp
blob: 6e878a13d237fe1d6540d2408feaea76d013182d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#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"

using namespace homekit;

#ifndef CONFIG_TARGET_ESP01
enum class WorkingMode {
    RECOVERY, // AP mode, http server with configuration
    NORMAL,   // MQTT client
};
static enum WorkingMode working_mode = WorkingMode::NORMAL;

static const uint16_t recovery_boot_detection_ms = 2000;
static const uint8_t recovery_boot_delay_ms = 100;
#endif

enum class WiFiConnectionState {
    WAITING = 0,
    JUST_CONNECTED = 1,
    CONNECTED = 2
};

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

#if CONFIG_MODULE == HOMEKIT_SI7021
    sensor = new temphum::Si7021();
#elif CONFIG_MODULE == HOMEKIT_DHT12
    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
}

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);
}