IotWebConfParameter.cpp 15.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
/**
 * IotWebConfParameter.cpp -- IotWebConf is an ESP8266/ESP32
 *   non blocking WiFi/AP web configuration library for Arduino.
 *   https://github.com/prampec/IotWebConf
 *
 * Copyright (C) 2020 Balazs Kelemen <prampec+arduino@gmail.com>
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

Eric Duminil's avatar
Eric Duminil committed
12
#include "IotWebConfParameter.h"
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402

namespace iotwebconf
{

ParameterGroup::ParameterGroup(
  const char* id, const char* label) :
  ConfigItem(id)
{
  this->label = label;
}

void ParameterGroup::addItem(ConfigItem* configItem)
{
  if (configItem->_parentItem != nullptr)
  {
    return; // Item must not be added two times.
  }
  if (this->_firstItem == nullptr)
  {
    this->_firstItem = configItem;
    return;
  }
  ConfigItem* current = this->_firstItem;
  while (current->_nextItem != nullptr)
  {
    current = current->_nextItem;
  }
  current->_nextItem = configItem;
  configItem->_parentItem = this;
}

int ParameterGroup::getStorageSize()
{
  int size = 0;
  ConfigItem* current = this->_firstItem;
  while (current != nullptr)
  {
    size += current->getStorageSize();
    current = current->_nextItem;
  }
  return size;
}
void ParameterGroup::applyDefaultValue()
{
  ConfigItem* current = this->_firstItem;
  while (current != nullptr)
  {
    current->applyDefaultValue();
    current = current->_nextItem;
  }
}

void ParameterGroup::storeValue(
  std::function<void(SerializationData* serializationData)> doStore)
{
  ConfigItem* current = this->_firstItem;
  while (current != nullptr)
  {
    current->storeValue(doStore);
    current = current->_nextItem;
  }
}
void ParameterGroup::loadValue(
  std::function<void(SerializationData* serializationData)> doLoad)
{
  ConfigItem* current = this->_firstItem;
  while (current != nullptr)
  {
    current->loadValue(doLoad);
    current = current->_nextItem;
  }
}

void ParameterGroup::renderHtml(
  bool dataArrived, WebRequestWrapper* webRequestWrapper)
{
    if (this->label != nullptr)
    {
      String content = getStartTemplate();
      content.replace("{b}", this->label);
      content.replace("{i}", this->getId());
      webRequestWrapper->sendContent(content);
    }
    ConfigItem* current = this->_firstItem;
    while (current != nullptr)
    {
      if (current->visible)
      {
        current->renderHtml(dataArrived, webRequestWrapper);
      }
      current = current->_nextItem;
    }
    if (this->label != nullptr)
    {
      String content = getEndTemplate();
      content.replace("{b}", this->label);
      content.replace("{i}", this->getId());
      webRequestWrapper->sendContent(content);
    }
}
void ParameterGroup::update(WebRequestWrapper* webRequestWrapper)
{
  ConfigItem* current = this->_firstItem;
  while (current != nullptr)
  {
    current->update(webRequestWrapper);
    current = current->_nextItem;
  }
}
void ParameterGroup::clearErrorMessage()
{
  ConfigItem* current = this->_firstItem;
  while (current != nullptr)
  {
    current->clearErrorMessage();
    current = current->_nextItem;
  }
}
void ParameterGroup::debugTo(Stream* out)
{
  out->print('[');
  out->print(this->getId());
  out->println(']');

  // -- Here is some overcomplicated logic to have nice debug output.
  bool ownItem = false;
  bool lastItem = false;
  PrefixStreamWrapper stream =
    PrefixStreamWrapper(
      out,
      [&](Stream* out1)
    {
      if (ownItem)
      {
        ownItem = false;
        return (size_t)0;
      }
      if (lastItem)
      {
        return out1->print("    ");
      }
      else
      {
        return out1->print("|   ");
      }
    });

  ConfigItem* current = this->_firstItem;
  while (current != nullptr)
  {
    if (current->_nextItem == nullptr)
    {
      out->print("\\-- ");
    }
    else
    {
      out->print("|-- ");
    }
    ownItem = true;
    lastItem = (current->_nextItem == nullptr);
    current->debugTo(&stream);
    current = current->_nextItem;
  }
}

#ifdef IOTWEBCONF_ENABLE_JSON
void ParameterGroup::loadFromJson(JsonObject jsonObject)
{
  if (jsonObject.containsKey(this->getId()))
  {
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
  Serial.print(F("Applying values from JSON for groupId: "));
  Serial.println(this->getId());
#endif
    JsonObject myObject = jsonObject[this->getId()];
    ConfigItem* current = this->_firstItem;
    while (current != nullptr)
    {
      current->loadFromJson(myObject);
      current = current->_nextItem;
    }
  }
  else
  {
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
    Serial.print(F("Group data not found in JSON. Skipping groupId: "));
    Serial.println(this->getId());
#endif
  }
}
#endif

///////////////////////////////////////////////////////////////////////////////

Parameter::Parameter(
  const char* label, const char* id, char* valueBuffer, int length,
  const char* defaultValue) :
  ConfigItem(id)
{
  this->label = label;
  this->valueBuffer = valueBuffer;
  this->_length = length;
  this->defaultValue = defaultValue;

  this->errorMessage = nullptr;
}
int Parameter::getStorageSize()
{
  return this->_length;
}
void Parameter::applyDefaultValue()
{
  if (defaultValue != nullptr)
  {
    strncpy(this->valueBuffer, this->defaultValue, this->getLength());
  }
  else
  {
    this->valueBuffer[0] = '\0';
  }
}
void Parameter::storeValue(
  std::function<void(SerializationData* serializationData)> doStore)
{
  SerializationData serializationData;
  serializationData.length = this->_length;
  serializationData.data = (byte*)this->valueBuffer;
  doStore(&serializationData);
}
void Parameter::loadValue(
  std::function<void(SerializationData* serializationData)> doLoad)
{
  SerializationData serializationData;
  serializationData.length = this->_length;
  serializationData.data = (byte*)this->valueBuffer;
  doLoad(&serializationData);
}
void Parameter::update(WebRequestWrapper* webRequestWrapper)
{
  if (webRequestWrapper->hasArg(this->getId()))
  {
    String newValue = webRequestWrapper->arg(this->getId());
    this->update(newValue);
  }
}
void Parameter::clearErrorMessage()
{
    this->errorMessage = nullptr;
}
#ifdef IOTWEBCONF_ENABLE_JSON
void Parameter::loadFromJson(JsonObject jsonObject)
{
  if (jsonObject.containsKey(this->getId()))
  {
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
  Serial.print(F("Applying value from JSON for parameterId: "));
  Serial.println(this->getId());
#endif
    const char* value = jsonObject[this->getId()];
    this->update(String(value));
  }
  else
  {
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
  Serial.print(F("No value found in JSON for parameterId: "));
  Serial.println(this->getId());
#endif
  }
}
#endif


///////////////////////////////////////////////////////////////////////////////

TextParameter::TextParameter(
  const char* label, const char* id, char* valueBuffer, int length,
  const char* defaultValue,
  const char* placeholder,
  const char* customHtml)
  : Parameter(label, id, valueBuffer, length, defaultValue)
{
  this->placeholder = placeholder;
  this->customHtml = customHtml;
}

void TextParameter::renderHtml(
  bool dataArrived, WebRequestWrapper* webRequestWrapper)
{
  String content = this->renderHtml(
    dataArrived,
    webRequestWrapper->hasArg(this->getId()),
    webRequestWrapper->arg(this->getId()));
  webRequestWrapper->sendContent(content);
}
String TextParameter::renderHtml(
  bool dataArrived, bool hasValueFromPost, String valueFromPost)
{
  return this->renderHtml("text", hasValueFromPost, valueFromPost);
}
String TextParameter::renderHtml(
  const char* type, bool hasValueFromPost, String valueFromPost)
{
  TextParameter* current = this;
  char parLength[12];

  String pitem = getHtmlTemplate();

  pitem.replace("{b}", current->label);
  pitem.replace("{t}", type);
  pitem.replace("{i}", current->getId());
  pitem.replace("{p}", current->placeholder == nullptr ? "" : current->placeholder);
  snprintf(parLength, 12, "%d", current->getLength()-1);
  pitem.replace("{l}", parLength);
  if (hasValueFromPost)
  {
    // -- Value from previous submit
    pitem.replace("{v}", valueFromPost);
  }
  else
  {
    // -- Value from config
    pitem.replace("{v}", current->valueBuffer);
  }
  pitem.replace(
      "{c}", current->customHtml == nullptr ? "" : current->customHtml);
  pitem.replace(
      "{s}",
      current->errorMessage == nullptr ? "" : "de"); // Div style class.
  pitem.replace(
      "{e}",
      current->errorMessage == nullptr ? "" : current->errorMessage);

  return pitem;
}

void TextParameter::update(String newValue)
{
  newValue.toCharArray(this->valueBuffer, this->getLength());
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
  Serial.print(this->getId());
  Serial.print(": ");
  Serial.println(this->valueBuffer);
#endif
}

void TextParameter::debugTo(Stream* out)
{
  Parameter* current = this;
  out->print("'");
  out->print(current->getId());
  out->print("' with value: '");
  out->print(current->valueBuffer);
  out->println("'");
}

///////////////////////////////////////////////////////////////////////////////

NumberParameter::NumberParameter(
  const char* label, const char* id, char* valueBuffer, int length,
  const char* defaultValue,
  const char* placeholder,
  const char* customHtml)
  : TextParameter(label, id, valueBuffer, length, defaultValue,
  placeholder, customHtml)
{
}

String NumberParameter::renderHtml(
  bool dataArrived,
  bool hasValueFromPost, String valueFromPost)
{
  return TextParameter::renderHtml("number", hasValueFromPost, valueFromPost);
}

///////////////////////////////////////////////////////////////////////////////

PasswordParameter::PasswordParameter(
  const char* label, const char* id, char* valueBuffer, int length,
  const char* defaultValue,
  const char* placeholder,
  const char* customHtml)
  : TextParameter(label, id, valueBuffer, length, defaultValue,
  placeholder, customHtml)
{
}

String PasswordParameter::renderHtml(
  bool dataArrived,
  bool hasValueFromPost, String valueFromPost)
{
403
  return TextParameter::renderHtml("password", true, String(this->valueBuffer));
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
}

void PasswordParameter::debugTo(Stream* out)
{
  Parameter* current = this;
  out->print("'");
  out->print(current->getId());
  out->print("' with value: ");
#ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL
  out->print("'");
  out->print(current->valueBuffer);
  out->println("'");
#else
  out->println(F("<hidden>"));
#endif
}

void PasswordParameter::update(String newValue)
{
  Parameter* current = this;
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
  Serial.print(this->getId());
  Serial.print(": ");
#endif
428
  if (newValue != current->valueBuffer)
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
  {
    // -- Value was set.
    newValue.toCharArray(current->valueBuffer, current->getLength());
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
# ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL
    Serial.println(current->valueBuffer);
# else
    Serial.println("<updated>");
# endif
#endif
  }
  else
  {
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
    Serial.println("<was not changed>");
#endif
  }
}

///////////////////////////////////////////////////////////////////////////////

CheckboxParameter::CheckboxParameter(
    const char* label, const char* id, char* valueBuffer, int length,
    bool defaultValue)
  : TextParameter(label, id, valueBuffer, length, defaultValue ? "selected" : nullptr,
  nullptr, nullptr)
{
}

String CheckboxParameter::renderHtml(
  bool dataArrived,
  bool hasValueFromPost, String valueFromPost)
{
  bool checkSelected = false;
  if (dataArrived)
  {
    if (hasValueFromPost && valueFromPost.equals("selected"))
    {
      checkSelected = true;
    }
  }
  else
  {
    if (this->isChecked())
    {
      checkSelected = true;
    }
  }

  if (checkSelected)
  {
    this->customHtml = CheckboxParameter::_checkedStr;
  }
  else
  {
    this->customHtml = nullptr;
  }
  
  
  return TextParameter::renderHtml("checkbox", true, "selected");
}

void CheckboxParameter::update(WebRequestWrapper* webRequestWrapper)
{
  if (webRequestWrapper->hasArg(this->getId()))
  {
    String newValue = webRequestWrapper->arg(this->getId());
    return TextParameter::update(newValue);
  }
  else if (this->visible)
  {
    // HTML will not post back unchecked checkboxes.
    return TextParameter::update("");
  }
}

///////////////////////////////////////////////////////////////////////////////

OptionsParameter::OptionsParameter(
    const char* label, const char* id, char* valueBuffer, int length,
    const char* optionValues, const char* optionNames, size_t optionCount, size_t nameLength,
    const char* defaultValue)
  : TextParameter(label, id, valueBuffer, length, defaultValue,
  nullptr, nullptr)
{
  this->_optionValues = optionValues;
  this->_optionNames = optionNames;
  this->_optionCount = optionCount;
  this->_nameLength = nameLength;
}

///////////////////////////////////////////////////////////////////////////////

SelectParameter::SelectParameter(
    const char* label, const char* id, char* valueBuffer, int length,
    const char* optionValues, const char* optionNames, size_t optionCount, size_t nameLength,
    const char* defaultValue)
  : OptionsParameter(label, id, valueBuffer, length, optionValues, optionNames,
  optionCount, nameLength, defaultValue)
{
}

String SelectParameter::renderHtml(
  bool dataArrived,
  bool hasValueFromPost, String valueFromPost)
{
  TextParameter* current = this;

  String options = "";

  for (size_t i=0; i<this->_optionCount; i++)
  {
    const char *optionValue = (this->_optionValues + (i*this->getLength()) );
    const char *optionName = (this->_optionNames + (i*this->_nameLength) );
    String oitem = FPSTR(IOTWEBCONF_HTML_FORM_OPTION);
    oitem.replace("{v}", optionValue);
//    if (sizeof(this->_optionNames) > i)
    {
      oitem.replace("{n}", optionName);
    }
//    else
//    {
//      oitem.replace("{n}", "?");
//    }
    if ((hasValueFromPost && (valueFromPost == optionValue)) ||
      (strncmp(current->valueBuffer, optionValue, this->getLength()) == 0))
    {
      // -- Value from previous submit
      oitem.replace("{s}", " selected");
    }
    else
    {
      // -- Value from config
      oitem.replace("{s}", "");
    }

    options += oitem;
  }

  String pitem = FPSTR(IOTWEBCONF_HTML_FORM_SELECT_PARAM);

  pitem.replace("{b}", current->label);
  pitem.replace("{i}", current->getId());
  pitem.replace(
      "{c}", current->customHtml == nullptr ? "" : current->customHtml);
  pitem.replace(
      "{s}",
      current->errorMessage == nullptr ? "" : "de"); // Div style class.
  pitem.replace(
      "{e}",
      current->errorMessage == nullptr ? "" : current->errorMessage);
  pitem.replace("{o}", options);

  return pitem;
}

///////////////////////////////////////////////////////////////////////////////

PrefixStreamWrapper::PrefixStreamWrapper(
  Stream* originalStream,
  std::function<size_t(Stream* stream)> prefixWriter)
{
  this->_originalStream = originalStream;
  this->_prefixWriter = prefixWriter;
}
size_t PrefixStreamWrapper::write(uint8_t data)
{
  size_t sizeOut = checkNewLine();
  sizeOut += this->_originalStream->write(data);
  if (data == 10) // NewLine
  {
    this->_newLine = true;
  }
  return sizeOut;
}
size_t PrefixStreamWrapper::write(const uint8_t *buffer, size_t size)
{
  size_t sizeOut = checkNewLine();
  sizeOut += this->_originalStream->write(buffer, size);
  if (*(buffer + size-1) == 10) // Ends with new line
  {
    this->_newLine = true;
  }
  return sizeOut;
}
size_t PrefixStreamWrapper::checkNewLine()
{
  if (this->_newLine)
  {
    this->_newLine = false;
    return this->_prefixWriter(this->_originalStream);
  }
  return 0;
}

} // end namespace