summaryrefslogtreecommitdiffstats
path: root/ULPSoilMonitor.ino
blob: 76a14d30e1bd706c73a8bbef1700450197f00aec (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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/*
 * Must allocate more memory for the ulp in 
 * esp32/tools/sdk/include/sdkconfig.h 
 * -> #define CONFIG_ULP_COPROC_RESERVE_MEM
 * for this sketch to compile. 2048b seems 
 * good.
 */
#include "esp_sleep.h"
#include "driver/rtc_io.h"
#include "driver/adc.h"
#include "esp32/ulp.h"
#include "ulp_soil.h"
#include "ulptool.h"
#include <math.h>

#include <MQTT.h>
#include <IotWebConf.h>

#define ADC_FACTOR (3.5f)
#define ADC_VCC_PIN (ADC2_CHANNEL_9)

#define ULP_PERIOD_MS (30000)

extern const uint8_t ulp_main_bin_start[] asm("_binary_ulp_main_bin_start");
extern const uint8_t ulp_main_bin_end[]   asm("_binary_ulp_main_bin_end");

struct {
  float soil0;
  float soil1;
  float soil2;
  float soil3;
  float soil4;
  float soil5;
} sensor_offset, sensor_gradient;

struct soil_data {
  float vcc;
  float soil0;
  float soil1;
  float soil2;
  float soil3;
  float soil4;
  float soil5;
  bool valid = false;
} soil;

const char default_name[] = "ULPSoilMonitor";
const char inital_ap_password[] = "SuperSavePassword";

#define STRING_LEN 128
#define CONFIG_VERSION "ulpsm02"

/* This function is called once after power-on reset, to load ULP program into
   RTC memory and configure the ADC.
*/
static void init_ulp_program();

/* This function is called every time before going into deep sleep.
   It starts the ULP program and resets measurement counter.
*/
static void start_ulp_program();

/* measures voltage on GPIO26 */
static void measure_vcc();

static void init_sensor_coefficients();

static float soil_moisture(uint16_t adc_value, float vcc, float offset, float gradient);

/* fills soil_data struct */
static void calculate_soil_data();

/* logs current soil_data */
static void print_soil_data();

static void setup_webconf();

void wifi_connected();
void config_saved();

void goto_sleep();

DNSServer dns;
WebServer server(80);
HTTPUpdateServer http_updater;
WiFiClient net;
MQTTClient mqtt_client;

char mqtt_server[STRING_LEN];
char mqtt_user_name[STRING_LEN];

IotWebConf webconf(default_name, &dns, &server, inital_ap_password, CONFIG_VERSION);
IotWebConfParameter param_mqtt_server = IotWebConfParameter("MQTT server", "mqtt_server", mqtt_server, STRING_LEN);

boolean do_connect_mqtt = false;
boolean do_reset = false;

unsigned long last_mqtt_connection_attempt = 0;

void setup() {
  Serial.begin(115200);

  measure_vcc();

  setup_webconf();

  esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
  if (cause == ESP_SLEEP_WAKEUP_ULP) {

    Serial.printf("Deep sleep wakeup\n");
    /* Count temperature form -5 ℃ , so ulp_temperature minus 5 */
    Serial.printf("max_diff:%d\n", (uint16_t)ulp_max_diff);

    calculate_soil_data();
    print_soil_data();

  } else {

    esp_err_t err = ulptool_load_binary(0, ulp_main_bin_start, (ulp_main_bin_end - ulp_main_bin_start) / sizeof(uint32_t));
    ESP_ERROR_CHECK(err);

  }

}

void loop() {
  webconf.doLoop();
  mqtt_client.loop();

  if (do_connect_mqtt) {
    if (connect_mqtt()) {
      do_connect_mqtt = false;
    }
  } else if (webconf.getState() == IOTWEBCONF_STATE_ONLINE && !mqtt_client.connected()) {
    connect_mqtt();
  }

  if (do_reset) {
    webconf.delay(1000);
    ESP.restart();
  }

  if (mqtt_client.connected()) {
    Serial.println("Sending data via MQTT.");
    String topic_prefix = String("/ULPSoilMonitor/") + webconf.getThingName() + String("/");
    if (soil.valid) {
      mqtt_client.publish(topic_prefix + "vcc", String(soil.vcc));
      mqtt_client.publish(topic_prefix + "soil0", String(soil.soil0));
      mqtt_client.publish(topic_prefix + "soil1", String(soil.soil1));
      mqtt_client.publish(topic_prefix + "soil2", String(soil.soil2));
      mqtt_client.publish(topic_prefix + "soil3", String(soil.soil3));
      mqtt_client.publish(topic_prefix + "soil4", String(soil.soil4));
      mqtt_client.publish(topic_prefix + "soil5", String(soil.soil5));
    } else {
      mqtt_client.publish(topic_prefix + "vcc", String(NAN));
      mqtt_client.publish(topic_prefix + "soil0", String(NAN));
      mqtt_client.publish(topic_prefix + "soil1", String(NAN));
      mqtt_client.publish(topic_prefix + "soil2", String(NAN));
      mqtt_client.publish(topic_prefix + "soil3", String(NAN));
      mqtt_client.publish(topic_prefix + "soil4", String(NAN));
      mqtt_client.publish(topic_prefix + "soil5", String(NAN));
    }
    goto_sleep();
  }
}

static void init_ulp_program()
{
  /* Configure ADC channel */
  adc1_ulp_enable();
  adc1_config_channel_atten(ADC1_CHANNEL_7, ADC_ATTEN_DB_0);
  adc1_config_channel_atten(ADC1_CHANNEL_4, ADC_ATTEN_DB_0);
  adc1_config_channel_atten(ADC1_CHANNEL_5, ADC_ATTEN_DB_0);
  adc1_config_channel_atten(ADC1_CHANNEL_6, ADC_ATTEN_DB_0);
  adc1_config_channel_atten(ADC1_CHANNEL_3, ADC_ATTEN_DB_0);
  adc1_config_channel_atten(ADC1_CHANNEL_0, ADC_ATTEN_DB_0);
  adc1_config_width(ADC_WIDTH_BIT_12);

  gpio_deep_sleep_hold_en();

  /* Configure SENSOR_ENABLE */
  rtc_gpio_init(GPIO_NUM_25);
  rtc_gpio_set_direction(GPIO_NUM_25, RTC_GPIO_MODE_OUTPUT_ONLY);
  rtc_gpio_pullup_en(GPIO_NUM_25);
  rtc_gpio_set_level(GPIO_NUM_25, 1);
  rtc_gpio_hold_en(GPIO_NUM_25);

  /* Set ULP wake up period */
  ulp_set_wakeup_period(0, ULP_PERIOD_MS * 1000);

  /* Disable pullup on GPIO15, in case it is connected to ground to suppress
     boot messages.
  */
  rtc_gpio_pullup_dis(GPIO_NUM_15);
  rtc_gpio_hold_en(GPIO_NUM_15);
}

static void start_ulp_program()
{
  init_ulp_program();

  /* Start the program */
  esp_err_t err = ulp_run((&ulp_entry - RTC_SLOW_MEM) / sizeof(uint32_t));
  ESP_ERROR_CHECK(err);
}

static void measure_vcc()
{
  int raw;

  gpio_reset_pin(GPIO_NUM_25);
  gpio_pad_select_gpio(GPIO_NUM_25);
  gpio_hold_dis(GPIO_NUM_25);
  gpio_set_direction(GPIO_NUM_25, GPIO_MODE_OUTPUT_OD);
  gpio_set_level(GPIO_NUM_25, 0);

  vTaskDelay(10);

  adc2_config_channel_atten(ADC_VCC_PIN, ADC_ATTEN_DB_0);
  esp_err_t r = adc2_get_raw(ADC_VCC_PIN, ADC_WIDTH_12Bit, &raw);

  gpio_set_level(GPIO_NUM_25, 1);
  gpio_hold_en(GPIO_NUM_25);

  if (r != ESP_OK) {
    soil.vcc = NAN;
    soil.valid = false;
  } else {
    float vcc = ((float)raw * ADC_FACTOR) / 4095;
    soil.vcc = vcc;
  }
}

static void  init_sensor_coefficients()
{
  sensor_offset.soil0 = 1.746;
  sensor_offset.soil1 = 1.746;
  sensor_offset.soil2 = 1.746;
  sensor_offset.soil3 = 1.746;
  sensor_offset.soil4 = 1.746;
  sensor_offset.soil5 = 1.746;

  sensor_gradient.soil0 = -2.849;
  sensor_gradient.soil1 = -2.849;
  sensor_gradient.soil2 = -2.849;
  sensor_gradient.soil3 = -2.849;
  sensor_gradient.soil4 = -2.849;
  sensor_gradient.soil5 = -2.849;
}

static float soil_moisture(uint16_t adc_value, float vcc, float offset, float gradient)
{
  if (adc_value == 0.0) {
    return NAN;
  }
  float moisture = 100.0 * (gradient * ((adc_value * ADC_FACTOR / 4095) / vcc) + offset);

  if (moisture > 100.0)
    moisture = 100.0;
  else if (moisture < 0.0)
    moisture = 0.0;

  return moisture;
}

static void calculate_soil_data()
{
  if (isnan(soil.valid))
    return;

  init_sensor_coefficients();

  soil.soil0 = soil_moisture(ulp_soil0, soil.vcc, sensor_offset.soil0, sensor_gradient.soil0);
  soil.soil1 = soil_moisture(ulp_soil1, soil.vcc, sensor_offset.soil1, sensor_gradient.soil1);
  soil.soil2 = soil_moisture(ulp_soil2, soil.vcc, sensor_offset.soil2, sensor_gradient.soil2);
  soil.soil3 = soil_moisture(ulp_soil3, soil.vcc, sensor_offset.soil3, sensor_gradient.soil3);
  soil.soil4 = soil_moisture(ulp_soil4, soil.vcc, sensor_offset.soil4, sensor_gradient.soil4);
  soil.soil5 = soil_moisture(ulp_soil5, soil.vcc, sensor_offset.soil5, sensor_gradient.soil5);

  soil.valid = true;
}

static void print_soil_data()
{
    Serial.printf("valid: %d\n", soil.valid);
    Serial.printf("VCC: %f\n", soil.vcc);
    Serial.printf("Soil0:%d -> %f\n", (uint16_t)ulp_soil0, soil.soil0);
    Serial.printf("Soil1:%d -> %f\n", (uint16_t)ulp_soil1, soil.soil1);
    Serial.printf("Soil2:%d -> %f\n", (uint16_t)ulp_soil2, soil.soil2);
    Serial.printf("Soil3:%d -> %f\n", (uint16_t)ulp_soil3, soil.soil3);
    Serial.printf("Soil4:%d -> %f\n", (uint16_t)ulp_soil4, soil.soil4);
    Serial.printf("Soil5:%d -> %f\n", (uint16_t)ulp_soil5, soil.soil5);
}

static void setup_webconf()
{
  webconf.addParameter(&param_mqtt_server);
  webconf.setConfigSavedCallback(&config_saved);
  webconf.setWifiConnectionCallback(&wifi_connected);
  webconf.setupUpdateServer(&http_updater);
  webconf.setWifiConnectionTimeoutMs(250);
  webconf.setApTimeoutMs(1);

  boolean config_valid = webconf.init();
  if (!config_valid) {
    mqtt_server[0] = '\0';

    Serial.println("Config invalid");
  }

  webconf.setApTimeoutMs(500);

  server.on("/", handle_root);
  server.on("/config", []{ webconf.handleConfig(); });
  server.onNotFound([](){ webconf.handleNotFound(); });

  mqtt_client.begin(mqtt_server, net);

  net.setNoDelay(true);
}

void handle_root()
{
  if (webconf.handleCaptivePortal()) {
    // -- Captive portal request were already served.
    return;
  }

  String s = "<!DOCTYPE html><html lang=\"en\"><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/>";
  s += "<title>ULPSoilMonitor</title></head><body>MQTT App demo";
  s += "<ul>";
  s += "<li>MQTT server: ";
  s += mqtt_server;
  s += "</ul>";
  s += "Go to <a href='config'>configure page</a> to change values.";
  s += "</body></html>\n";

  server.send(200, "text/html", s);
}

void wifi_connected()
{
  do_connect_mqtt = true;
}

void config_saved()
{
  do_reset = true;
}

boolean connect_mqtt()
{
  unsigned long now = millis();

  if (1000 > now - last_mqtt_connection_attempt) {
    return false;
  }

  Serial.println("Connecting to MQTT server...");
  if (!mqtt_client.connect(webconf.getThingName())) {
    last_mqtt_connection_attempt = now;
    return false;
  }

  Serial.println("Connected to MQTT server!");
  return true;
}


void goto_sleep()
{
  if (mqtt_client.connected()) {
    mqtt_client.loop();
    net.flush();
    mqtt_client.disconnect();
    mqtt_client.loop();
  }

  net.flush();
  net.stop();
  delay(20);

  Serial.printf("Entering deep sleep\n\n");
  start_ulp_program();
  ESP_ERROR_CHECK(esp_sleep_enable_ulp_wakeup());
  esp_deep_sleep_start();
}