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

#ifndef IotWebConfTParameter_h
#define IotWebConfTParameter_h

// TODO: This file is a mess. Help wanted to organize thing!

Eric Duminil's avatar
Eric Duminil committed
18
#include "IotWebConfParameter.h"
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#include <Arduino.h>
#include <IPAddress.h>
#include <errno.h>

// At least in PlatformIO, strtoimax/strtoumax are defined, but not implemented.
#if 1
#define strtoimax strtoll
#define strtoumax strtoull
#endif

namespace iotwebconf
{

/**
 * This class is to hide web related properties from the
 *  data manipulation.
 */
class ConfigItemBridge : public ConfigItem
{
public:
  virtual void update(WebRequestWrapper* webRequestWrapper) override
  {
      if (webRequestWrapper->hasArg(this->getId()))
      {
        String newValue = webRequestWrapper->arg(this->getId());
        this->update(newValue);
      }
  }
  void debugTo(Stream* out) override
  {
    out->print("'");
    out->print(this->getId());
    out->print("' with value: '");
    out->print(this->toString());
    out->println("'");
  }

protected:
  ConfigItemBridge(const char* id) : ConfigItem(id) { }
  virtual int getInputLength() { return 0; };
  virtual bool update(String newValue, bool validateOnly = false) = 0;
  virtual String toString() = 0;
};

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

/**
 * DataType is the data related part of the parameter.
 * It does not care about web and visualization, but takes care of the
 *  data validation and storing.
 */
template <typename ValueType, typename _DefaultValueType = ValueType>
class DataType : virtual public ConfigItemBridge
{
public:
  using DefaultValueType = _DefaultValueType;

  DataType(const char* id, DefaultValueType defaultValue) :
    ConfigItemBridge(id),
    _defaultValue(defaultValue)
  {
  }

  /**
   * value() can be used to get the value, but it can also
   * be used set it like this: p.value() = newValue
   */
  ValueType& value() { return this->_value; }
  ValueType& operator*() { return this->_value; }

protected:
  int getStorageSize() override
  {
    return sizeof(ValueType);
  }

  virtual bool update(String newValue, bool validateOnly = false) = 0;
  bool validate(String newValue) { return update(newValue, true); }
  virtual String toString() override { return String(this->_value); }

  ValueType _value;
  const DefaultValueType _defaultValue;
};

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

class StringDataType : public DataType<String>
{
public:
  using DataType<String>::DataType;

protected:
  virtual bool update(String newValue, bool validateOnly) override {
    if (!validateOnly)
    {
      this->_value = newValue;
    }
    return true;
  }
  virtual String toString() override { return this->_value; }
};

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

template <size_t len>
class CharArrayDataType : public DataType<char[len], const char*>
{
public:
using DataType<char[len], const char*>::DataType;
  CharArrayDataType(const char* id, const char* defaultValue) :
    ConfigItemBridge::ConfigItemBridge(id),
    DataType<char[len], const char*>::DataType(id, defaultValue) { };
  virtual void applyDefaultValue() override
  {
    strncpy(this->_value, this->_defaultValue, len);
  }

protected:
  virtual bool update(String newValue, bool validateOnly) override
  {
    if (newValue.length() + 1 > len)
    {
      return false;
    }
    if (!validateOnly)
    {
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
      Serial.print(this->getId());
      Serial.print(": ");
      Serial.println(newValue);
#endif
      strncpy(this->_value, newValue.c_str(), len);
    }
    return true;
  }
  void storeValue(std::function<void(
    SerializationData* serializationData)> doStore) override
  {
    SerializationData serializationData;
    serializationData.length = len;
    serializationData.data = (byte*)this->_value;
    doStore(&serializationData);
  }
  void loadValue(std::function<void(
    SerializationData* serializationData)> doLoad) override
  {
    SerializationData serializationData;
    serializationData.length = len;
    serializationData.data = (byte*)this->_value;
    doLoad(&serializationData);
  }
  virtual int getInputLength() override { return len; };
};

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

/**
 * All non-complex types should be inherited from this base class.
 */
template <typename ValueType>
class PrimitiveDataType : public DataType<ValueType>
{
public:
using DataType<ValueType>::DataType;
  PrimitiveDataType(const char* id, ValueType defaultValue) :
    ConfigItemBridge::ConfigItemBridge(id),
    DataType<ValueType>::DataType(id, defaultValue) { };

  void setMax(ValueType val) { this->_max = val; this->_maxDefined = true; }
  void setMin(ValueType val) { this->_min = val; this->_minDefined = true; }

  virtual void applyDefaultValue() override
  {
    this->_value = this->_defaultValue;
  }

protected:
  virtual bool update(String newValue, bool validateOnly) override
  {
    errno = 0;
    ValueType val = fromString(newValue);
    if ((errno == ERANGE)
      || (this->_minDefined && (val < this->_min))
      || (this->_maxDefined && (val > this->_max)))
    {
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
      Serial.print(this->getId());
      Serial.print(" value not accepted: ");
      Serial.println(val);
#endif
      return false;
    }
    if (!validateOnly)
    {
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
      Serial.print(this->getId());
      Serial.print(": ");
      Serial.println((ValueType)val);
#endif
      this->_value = (ValueType) val;
    }
    return true;
  }
  void storeValue(std::function<void(
    SerializationData* serializationData)> doStore) override
  {
    SerializationData serializationData;
    serializationData.length = this->getStorageSize();
    serializationData.data =
      reinterpret_cast<byte*>(&this->_value);
    doStore(&serializationData);
  }
  void loadValue(std::function<void(
    SerializationData* serializationData)> doLoad) override
  {
    byte buf[this->getStorageSize()];
    SerializationData serializationData;
    serializationData.length = this->getStorageSize();
    serializationData.data = buf;
    doLoad(&serializationData);
    ValueType* valuePointer = reinterpret_cast<ValueType*>(buf);
    this->_value = *valuePointer;
  }
  virtual ValueType fromString(String stringValue) = 0;

  ValueType getMax() { return this->_max; }
  ValueType getMin() { return this->_min; }
  ValueType isMaxDefined() { return this->_maxDefined; }
  ValueType isMinDefined() { return this->_minDefined; }

private:
  ValueType _min;
  ValueType _max;
  bool _minDefined = false;
  bool _maxDefined = false;
};

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

template <typename ValueType, int base = 10>
class SignedIntDataType : public PrimitiveDataType<ValueType>
{
public:
  SignedIntDataType(const char* id, ValueType defaultValue) :
    ConfigItemBridge::ConfigItemBridge(id),
    PrimitiveDataType<ValueType>::PrimitiveDataType(id, defaultValue) { };

protected:
  virtual ValueType fromString(String stringValue)
  {
    return (ValueType)strtoimax(stringValue.c_str(), nullptr, base);
  }
};

template <typename ValueType, int base = 10>
class UnsignedIntDataType : public PrimitiveDataType<ValueType>
{
public:
  UnsignedIntDataType(const char* id, ValueType defaultValue) :
    ConfigItemBridge::ConfigItemBridge(id),
    PrimitiveDataType<ValueType>::PrimitiveDataType(id, defaultValue) { };

protected:
  virtual ValueType fromString(String stringValue)
  {
    return (ValueType)strtoumax(stringValue.c_str(), nullptr, base);
  }
};

class BoolDataType : public PrimitiveDataType<bool>
{
public:
  BoolDataType(const char* id, bool defaultValue) :
    ConfigItemBridge::ConfigItemBridge(id),
    PrimitiveDataType<bool>::PrimitiveDataType(id, defaultValue) { };

protected:
  virtual bool fromString(String stringValue)
  {
    return stringValue.c_str()[0] == 1;
  }
};

class FloatDataType : public PrimitiveDataType<float>
{
public:
  FloatDataType(const char* id, float defaultValue) :
    ConfigItemBridge::ConfigItemBridge(id),
    PrimitiveDataType<float>::PrimitiveDataType(id, defaultValue) { };

protected:
  virtual float fromString(String stringValue)
  {
    return atof(stringValue.c_str());
  }
};

class DoubleDataType : public PrimitiveDataType<double>
{
public:
  DoubleDataType(const char* id, double defaultValue) :
    ConfigItemBridge::ConfigItemBridge(id),
    PrimitiveDataType<double>::PrimitiveDataType(id, defaultValue) { };

protected:
  virtual double fromString(String stringValue)
  {
    return strtod(stringValue.c_str(), nullptr);
  }
};

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

class IpDataType : public DataType<IPAddress>
{
using DataType<IPAddress>::DataType;

protected:
  virtual bool update(String newValue, bool validateOnly) override
  {
    if (validateOnly)
    {
      IPAddress ip;
      return ip.fromString(newValue);
    }
    else
    {
      return this->_value.fromString(newValue);
    }
  }

  virtual String toString() override { return this->_value.toString(); }
};

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

/**
 * Input parameter is the part of the parameter that is responsible
 * for the appearance of the parameter in HTML.
 */
class InputParameter : virtual public ConfigItemBridge
{
public:
  InputParameter(const char* id, const char* label) :
    ConfigItemBridge::ConfigItemBridge(id),
    label(label) { }

  virtual void renderHtml(
    bool dataArrived, WebRequestWrapper* webRequestWrapper) override
  {
    String content = this->renderHtml(
      dataArrived,
      webRequestWrapper->hasArg(this->getId()),
      webRequestWrapper->arg(this->getId()));
    webRequestWrapper->sendContent(content);
  }

  const char* label;

  /**
   * This variable is meant to store a value that is displayed in an empty
   *   (not filled) field.
   */
  const char* placeholder = nullptr;
  virtual void setPlaceholder(const char* placeholder) { this->placeholder = placeholder; }

  /**
   * Usually this variable is used when rendering the form input field
   *   so one can customize the rendered outcome of this particular item.
   */
  const char* customHtml = nullptr;

  /**
   * Used when rendering the input field. Is is overridden by different
   *   implementations.
   */
  virtual String getCustomHtml()
  {
    return String(customHtml == nullptr ? "" : customHtml);
  }

  const char* errorMessage = nullptr;

protected:
  void clearErrorMessage() override
  {
    this->errorMessage = nullptr;
  }

  virtual String renderHtml(
    bool dataArrived, bool hasValueFromPost, String valueFromPost)
  {
    String pitem = String(this->getHtmlTemplate());

    pitem.replace("{b}", this->label);
    pitem.replace("{t}", this->getInputType());
    pitem.replace("{i}", this->getId());
    pitem.replace(
      "{p}", this->placeholder == nullptr ? "" : this->placeholder);
    int length = this->getInputLength();
    if (length > 0)
    {
      char parLength[11];
422
      snprintf(parLength, 11, "%d", length - 1); // To allow "\0" at the end of the string.
423
424
425
426
427
428
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
      String maxLength = String("maxlength=") + parLength;
      pitem.replace("{l}", maxLength);
    }
    else
    {
      pitem.replace("{l}", "");
    }
    if (hasValueFromPost)
    {
      // -- Value from previous submit
      pitem.replace("{v}", valueFromPost);
    }
    else
    {
      // -- Value from config
      pitem.replace("{v}", this->toString());
    }
    pitem.replace("{c}", this->getCustomHtml());
    pitem.replace(
        "{s}",
        this->errorMessage == nullptr ? "" : "de"); // Div style class.
    pitem.replace(
        "{e}",
        this->errorMessage == nullptr ? "" : this->errorMessage);

    return pitem;
  }

  /**
   * One can override this method in case a specific HTML template is required
   * for a parameter.
   */
  virtual String getHtmlTemplate() { return FPSTR(IOTWEBCONF_HTML_FORM_PARAM); };
  virtual const char* getInputType() = 0;
};

template <size_t len>
class TextTParameter : public CharArrayDataType<len>, public InputParameter
{
public:
using CharArrayDataType<len>::CharArrayDataType;
  TextTParameter(const char* id, const char* label, const char* defaultValue) :
    ConfigItemBridge(id),
    CharArrayDataType<len>::CharArrayDataType(id, defaultValue),
    InputParameter::InputParameter(id, label) { }

protected:
  virtual const char* getInputType() override { return "text"; }
};

class CheckboxTParameter : public BoolDataType, public InputParameter
{
public:
  CheckboxTParameter(const char* id, const char* label, const bool defaultValue) :
    ConfigItemBridge(id),
    BoolDataType::BoolDataType(id, defaultValue),
    InputParameter::InputParameter(id, label) { }
  bool isChecked() { return this->value(); }

protected:
  virtual const char* getInputType() override { return "checkbox"; }

  virtual void update(WebRequestWrapper* webRequestWrapper) override
  {
      bool selected = false;
      if (webRequestWrapper->hasArg(this->getId()))
      {
        String valueFromPost = webRequestWrapper->arg(this->getId());
        selected = valueFromPost.equals("selected");
      }
//      this->update(String(selected ? "1" : "0"));
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
      Serial.print(this->getId());
      Serial.print(": ");
      Serial.println(selected ? "selected" : "not selected");
#endif
      this->_value = selected;
  }

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

    if (checkSelected)
    {
      this->customHtml = CheckboxTParameter::_checkedStr;
    }
    else
    {
      this->customHtml = nullptr;
    }
    
    return InputParameter::renderHtml(dataArrived, true, String("selected"));
  }
private:
  const char* _checkedStr = "checked='checked'";
};

template <size_t len>
class PasswordTParameter : public CharArrayDataType<len>, public InputParameter
{
public:
using CharArrayDataType<len>::CharArrayDataType;
  PasswordTParameter(const char* id, const char* label, const char* defaultValue) :
    ConfigItemBridge(id),
    CharArrayDataType<len>::CharArrayDataType(id, defaultValue),
    InputParameter::InputParameter(id, label)
  {
    this->customHtml = _customHtmlPwd;
  }

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

  virtual bool update(String newValue, bool validateOnly) override
  {
    if (newValue.length() + 1 > len)
    {
      return false;
    }
    if (validateOnly)
    {
      return true;
    }

#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
    Serial.print(this->getId());
    Serial.print(": ");
#endif
578
    if (newValue != this->_value)
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
    {
      // -- Value was set.
      strncpy(this->_value, newValue.c_str(), len);
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
# ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL
      Serial.println(this->_value);
# else
      Serial.println("<updated>");
# endif
#endif
    }
    else
    {
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
      Serial.println("<was not changed>");
#endif
    }
    return true;
  }

protected:
  virtual const char* getInputType() override { return "password"; }
  virtual String renderHtml(
    bool dataArrived, bool hasValueFromPost, String valueFromPost) override
  {
604
    return InputParameter::renderHtml(dataArrived, true, String(this->_value));
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
  }
private:
  const char* _customHtmlPwd = "ondblclick=\"pw(this.id)\"";
};

/**
 * All non-complex type input parameters should be inherited from this
 *  base class.
 */
template <typename ValueType>
class PrimitiveInputParameter :
  public InputParameter
{
public:
  PrimitiveInputParameter(const char* id, const char* label) :
    ConfigItemBridge::ConfigItemBridge(id),
    InputParameter::InputParameter(id, label) { }

  virtual String getCustomHtml() override
  {
    String modifiers = String(this->customHtml);

    if (this->isMinDefined())
    {
      modifiers += " min='" ;
      modifiers += this->getMin();
      modifiers += "'";
    }
    if (this->isMaxDefined())
    {
      modifiers += " max='";
      modifiers += this->getMax();
      modifiers += "'";
    }
    if (this->step != 0)
    {
      modifiers += " step='";
      modifiers += this->step;
      modifiers += "'";
    }

    return modifiers;
  }

  ValueType step = 0;
  void setStep(ValueType step) { this->step = step; }
  virtual ValueType getMin() = 0;
  virtual ValueType getMax() = 0;
  virtual bool isMinDefined() = 0;
  virtual bool isMaxDefined() = 0;
};

template <typename ValueType, int base = 10>
class IntTParameter :
  public virtual SignedIntDataType<ValueType, base>,
  public PrimitiveInputParameter<ValueType>
{
public:
  IntTParameter(const char* id, const char* label, ValueType defaultValue) :
    ConfigItemBridge(id),
    SignedIntDataType<ValueType, base>::SignedIntDataType(id, defaultValue),
    PrimitiveInputParameter<ValueType>::PrimitiveInputParameter(id, label) { }

  // TODO: somehow organize these methods into common parent.
  virtual ValueType getMin() override
  {
    return PrimitiveDataType<ValueType>::getMin();
  }
  virtual ValueType getMax() override
  {
    return PrimitiveDataType<ValueType>::getMax();
  }

  virtual bool isMinDefined() override
  {
    return PrimitiveDataType<ValueType>::isMinDefined();
  }
  virtual bool isMaxDefined() override
  {
    return PrimitiveDataType<ValueType>::isMaxDefined();
  }

protected:
  virtual const char* getInputType() override { return "number"; }
};

template <typename ValueType, int base = 10>
class UIntTParameter :
  public virtual UnsignedIntDataType<ValueType, base>,
  public PrimitiveInputParameter<ValueType>
{
public:
  UIntTParameter(const char* id, const char* label, ValueType defaultValue) :
    ConfigItemBridge(id),
    UnsignedIntDataType<ValueType, base>::UnsignedIntDataType(id, defaultValue),
    PrimitiveInputParameter<ValueType>::PrimitiveInputParameter(id, label) { }

  // TODO: somehow organize these methods into common parent.
  virtual ValueType getMin() override
  {
    return PrimitiveDataType<ValueType>::getMin();
  }
  virtual ValueType getMax() override
  {
    return PrimitiveDataType<ValueType>::getMax();
  }

  virtual bool isMinDefined() override
  {
    return PrimitiveDataType<ValueType>::isMinDefined();
  }
  virtual bool isMaxDefined() override
  {
    return PrimitiveDataType<ValueType>::isMaxDefined();
  }

protected:
  virtual const char* getInputType() override { return "number"; }
};

class FloatTParameter :
  public FloatDataType,
  public PrimitiveInputParameter<float>
{
public:
  FloatTParameter(const char* id, const char* label, float defaultValue) :
    ConfigItemBridge(id),
    FloatDataType::FloatDataType(id, defaultValue),
    PrimitiveInputParameter<float>::PrimitiveInputParameter(id, label) { }

  virtual float getMin() override
  {
    return PrimitiveDataType<float>::getMin();
  }
  virtual float getMax() override
  {
    return PrimitiveDataType<float>::getMax();
  }

  virtual bool isMinDefined() override
  {
    return PrimitiveDataType<float>::isMinDefined();
  }
  virtual bool isMaxDefined() override
  {
    return PrimitiveDataType<float>::isMaxDefined();
  }

protected:
  virtual const char* getInputType() override { return "number"; }
};

/**
 * Options parameter is a structure, that handles multiple values when redering
 * the HTML representation.
 */
template <size_t len>
class OptionsTParameter : public TextTParameter<len>
{
public:
  /**
   * @optionValues - List of values to choose from with, where each value
   *   can have a maximal size of 'length'. Contains 'optionCount' items.
   * @optionNames - List of names to render for the values, where each
   *   name can have a maximal size of 'nameLength'. Contains 'optionCount'
   *   items.
   * @optionCount - Size of both 'optionValues' and 'optionNames' lists.
   * @nameLength - Size of any item in optionNames list.
   * (See TextParameter for arguments!)
   */
  OptionsTParameter(
    const char* id, const char* label, const char* defaultValue,
    const char* optionValues, const char* optionNames,
    size_t optionCount, size_t nameLength) :
    ConfigItemBridge(id),
    TextTParameter<len>(id, label, defaultValue)
  {
    this->_optionValues = optionValues;
    this->_optionNames = optionNames;
    this->_optionCount = optionCount;
    this->_nameLength = nameLength;
  }

  // TODO: make these protected
  void setOptionValues(const char* optionValues) { this->_optionValues = optionValues; }
  void setOptionNames(const char* optionNames) { this->_optionNames = optionNames; }
  void setOptionCount(size_t optionCount) { this->_optionCount = optionCount; }
  void setNameLength(size_t nameLength) { this->_nameLength = nameLength; }
protected:
  OptionsTParameter(
    const char* id, const char* label, const char* defaultValue) :
    ConfigItemBridge(id),
    TextTParameter<len>(id, label, defaultValue)
  {
  }

  const char* _optionValues;
  const char* _optionNames;
  size_t _optionCount;
  size_t _nameLength;
};

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

/**
 * Select parameter is an option parameter, that rendered as HTML SELECT.
 * Basically it is a dropdown combobox.
 */
template <size_t len>
class SelectTParameter : public OptionsTParameter<len>
{
public:
  /**
   * Create a select parameter for the config portal.
   *
   * (See OptionsParameter for arguments!)
   */
  SelectTParameter(
    const char* id, const char* label, const char* defaultValue,
    const char* optionValues, const char* optionNames,
    size_t optionCount, size_t nameLength) :
    ConfigItemBridge(id),
    OptionsTParameter<len>(
      id, label, defaultValue, optionValues, optionNames, optionCount, nameLength)
    { }
  // TODO: make this protected
  SelectTParameter(
    const char* id, const char* label, const char* defaultValue) :
    ConfigItemBridge(id),
    OptionsTParameter<len>(id, label, defaultValue) { }

protected:
  // Overrides
  virtual String renderHtml(
    bool dataArrived, bool hasValueFromPost, String valueFromPost) override
  {
    String options = "";

    for (size_t i=0; i<this->_optionCount; i++)
    {
      const char *optionValue = (this->_optionValues + (i*len) );
      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(this->value(), optionValue, len) == 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}", this->label);
    pitem.replace("{i}", this->getId());
    pitem.replace(
        "{c}", this->customHtml == nullptr ? "" : this->customHtml);
    pitem.replace(
        "{s}",
        this->errorMessage == nullptr ? "" : "de"); // Div style class.
    pitem.replace(
        "{e}",
        this->errorMessage == nullptr ? "" : this->errorMessage);
    pitem.replace("{o}", options);

    return pitem;
  }

private:
};


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

/**
 * Color chooser.
 */
class ColorTParameter : public CharArrayDataType<8>, public InputParameter
{
public:
using CharArrayDataType<8>::CharArrayDataType;
  ColorTParameter(const char* id, const char* label, const char* defaultValue) :
    ConfigItemBridge(id),
    CharArrayDataType<8>::CharArrayDataType(id, defaultValue),
    InputParameter::InputParameter(id, label) { }

protected:
  virtual const char* getInputType() override { return "color"; }
};

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

/**
 * Date chooser.
 */
class DateTParameter : public CharArrayDataType<11>, public InputParameter
{
public:
using CharArrayDataType<11>::CharArrayDataType;
  DateTParameter(const char* id, const char* label, const char* defaultValue) :
    ConfigItemBridge(id),
    CharArrayDataType<11>::CharArrayDataType(id, defaultValue),
    InputParameter::InputParameter(id, label) { }

protected:
  virtual const char* getInputType() override { return "date"; }
};

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

/**
 * Time chooser.
 */
class TimeTParameter : public CharArrayDataType<6>, public InputParameter
{
public:
using CharArrayDataType<6>::CharArrayDataType;
  TimeTParameter(const char* id, const char* label, const char* defaultValue) :
    ConfigItemBridge(id),
    CharArrayDataType<6>::CharArrayDataType(id, defaultValue),
    InputParameter::InputParameter(id, label) { }

protected:
  virtual const char* getInputType() override { return "time"; }
};

} // end namespace

Eric Duminil's avatar
Eric Duminil committed
949
#include "IotWebConfTParameterBuilder.h"
950
951

#endif