/
DeviceServerEsp32.ino
4512 lines (3999 loc) · 150 KB
/
DeviceServerEsp32.ino
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
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
422
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
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
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
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
VoffCon is a system for controlling devices and appliances from anywhere.
It consists of two programs. A "node server" and a "device server".
Copyright (C) 2016 Gudjon Holm Sigurdsson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact the author by sending email to gudjonholm@gmail.com or
by regular post to the address Haseyla 27, 260 Reykjanesbar, Iceland.
Program for Board: ESP32 Dev Module
*/
#include <WiFi.h>
#include <HTTPClient.h>
//#include <stddef.h> //for linked list
/*
Board: ESP32 DEV Module
*/
const char* deviceId = DEVICE_ID;
// Name of the wifi (accesspoint)network
// example: "guttisWiFi"
const char* ssid = WIFI_ACCESSPOINT;
// Wifi password
// example: "mypasswordToTheWifi"
const char* password = WIFI_PASSWORD;
// port number which this device will be operating on.
// example: 5100
const int PORT = PORT_NUMBER;
// example: 6100
const int voffconServerPort = VOFFCON_SERVER_PORT;
IPAddress
// ip address which this device will be operating on.
// Example: "192.168.1.158"
myIp(IPV4_IPADDRESS),
//the default gateway which this device will be operating on.
// example: "192.168.1.254"
gateway(IPV4_GATEWAY),
// the default gatway on this network.
// On windows goto command
// prompt and type "ipconfig"
// example: "255.255.255.0"
subnet(IPV4_SUBNET),
// example: "192.168.1.127"
voffconServerIp(VOFFCON_SERVER_IP);
/*boolean grantAccessToEverybody:
* Set to true if you want to allow all clients where the first 3 numbers
* in a client IP address are the same same as myIp (this server IP address).
.*/
boolean grantAccessToEveryone = false;
boolean grantAccessToAllClientsOnSameSubnet = true;
/*boolean grantAccessToFirstCaller:
* set to true if you want to allow the first client to call the "/setup" method
* to be automaticly granted access. that is, client IP address will be whitelisted.
.*/
WiFiServer server(PORT);
const int ERROR_NUMBER = -9999;
enum OBJECTTYPE {
OBJECTTYPE_KEYVALUE_STRING,
OBJECTTYPE_KEYVALUE_INT,
OBJECTTYPE_PINS_ARRAY,
OBJECTTYPE_PIN,
OBJECTTYPE_PINS,
OBJECTTYPE_DATE,
OBJECTTYPE_WHITELIST_ARRAY,
OBJECTTYPE_STATUS,
OBJECTTYPE_LOG_PINS,
OBJECTTYPE_INFORMATION,
OBJECTTYPE_WARNING,
OBJECTTYPE_ERROR,
/*add next type above this line*/
OBJECTTYPE_COUNT
};
enum JSONTYPEKEY {
KEYVALUE_STRING,
KEYVALUE_INT,
KEYVALUE_DOUBLE
};
#ifndef CODE_BLOCK_LinkedList
//do not remove the comment below this line
//INSERT_FROM_HERE
// ---------------------------------------------------------------
// LinkedList.h - V1.1 - Generic LinkedList implementation
// For instructions, go to https://github.com/ivanseidel/LinkedList
// Created by Ivan Seidel Gomes, March, 2013.
// Released into the public domain.
// ---------------------------------------------------------------
template<class T>
struct ListNode
{
T data;
ListNode<T> *next;
};
/// <summary>
/// A general linked list ready to be used or Inherited
/// </summary>
template <typename T>
class LinkedList {
protected:
int _size;
ListNode<T> *root;
ListNode<T> *last;
// Helps "get" method, by saving last position
ListNode<T> *lastNodeGot;
int lastIndexGot;
// isCached should be set to FALSE
// everytime the list suffer changes
bool isCached;
ListNode<T>* getNode(int index);
public:
/// <summary>
/// The list constructor
/// </summary>
LinkedList();
~LinkedList();
/// <summary>
/// Returns current size of LinkedList
/// </summary>
/// <returns>a int number</returns>
virtual int size();
/// <summary>
/// Adds a T object in the specified index;
/// Unlinkand link the LinkedList correcly;
/// Increment _size
/// </summary>
/// <param name="index">Where to add the object in the zero based index</param>
/// <param name="T">The object to be added</param>
/// <returns>Success: true. Fail: false.</returns>
virtual bool add(int index, T);
/// <summary>
/// Adds a T object in the end of the LinkedList;
/// Increment _size;
/// </summary>
/// <param name="T">The object</param>
virtual bool add(T);
/// <summary>
/// Adds a T object in the start of the LinkedList;
/// Increment _size;
/// </summary>
/// <param name="T">The object to be added at beginning of list</param>
/// <returns></returns>
virtual bool unshift(T);
/// <summary>
/// Set the object at index, with T;
/// Increment _size;
/// </summary>
/// <param name="index">Zero based index of where the object is</param>
/// <param name="T">The object which values will be overwritten</param>
/// <returns></returns>
virtual bool set(int index, T);
/// <summary>
/// Remove object at index;
/// If index is not reachable, returns false;
/// else, decrement _size
/// </summary>
/// <param name="index"></param>
/// <returns>Success: The object which was removed. Fail: an object created with the default constructor</returns>
virtual T remove(int index);
/// <summary>
/// Remove last object;
/// </summary>
/// <returns>The data of the removed object</returns>
virtual T pop();
/// <summary>
/// Remove first object;
/// </summary>
virtual T shift();
/// /// <summary>
/// Get the index'th element on the list;
/// Return Element if accessible,
/// else, return false;
/// </summary>
/// <param name="index">Zero based index if the object in the list</param>
/// <returns>Success: the object. Fail: A object created with a default constructor</returns>
virtual T get(int index);
/// <summary>
/// Clear the entire array
/// That is remove all objects from the list and delete them from memory
/// </summary>
virtual void clear();
};
// Initialize LinkedList with false values
template<typename T>
LinkedList<T>::LinkedList()
{
root = NULL;
last = NULL;
_size = 0;
lastNodeGot = root;
lastIndexGot = 0;
isCached = false;
}
// Clear Nodes and free Memory
template<typename T>
LinkedList<T>::~LinkedList()
{
ListNode<T>* tmp;
while (root != NULL)
{
tmp = root;
root = root->next;
delete tmp;
}
last = NULL;
_size = 0;
isCached = false;
}
/*
Actualy "logic" coding
*/
template<typename T>
ListNode<T>* LinkedList<T>::getNode(int index) {
int _pos = 0;
ListNode<T>* current = root;
// Check if the node trying to get is
// immediatly AFTER the previous got one
if (isCached && lastIndexGot <= index) {
_pos = lastIndexGot;
current = lastNodeGot;
}
while (_pos < index && current) {
current = current->next;
_pos++;
}
// Check if the object index got is the same as the required
if (_pos == index) {
isCached = true;
lastIndexGot = index;
lastNodeGot = current;
return current;
}
return NULL;
}
template<typename T>
int LinkedList<T>::size() {
return _size;
}
template<typename T>
bool LinkedList<T>::add(int index, T _t) {
if (index >= _size)
return add(_t);
if (index == 0)
return unshift(_t);
ListNode<T> *tmp = new ListNode<T>(),
*_prev = getNode(index - 1);
tmp->data = _t;
tmp->next = _prev->next;
_prev->next = tmp;
_size++;
isCached = false;
return true;
}
template<typename T>
bool LinkedList<T>::add(T _t) {
ListNode<T> *tmp = new ListNode<T>();
tmp->data = _t;
tmp->next = NULL;
if (root) {
// Already have elements inserted
last->next = tmp;
last = tmp;
}
else {
// First element being inserted
root = tmp;
last = tmp;
}
_size++;
isCached = false;
return true;
}
template<typename T>
bool LinkedList<T>::unshift(T _t) {
if (_size == 0)
return add(_t);
ListNode<T> *tmp = new ListNode<T>();
tmp->next = root;
tmp->data = _t;
root = tmp;
_size++;
isCached = false;
return true;
}
template<typename T>
bool LinkedList<T>::set(int index, T _t) {
// Check if index position is in bounds
if (index < 0 || index >= _size)
return false;
getNode(index)->data = _t;
return true;
}
template<typename T>
T LinkedList<T>::pop() {
if (_size <= 0)
return T();
isCached = false;
if (_size >= 2) {
ListNode<T> *tmp = getNode(_size - 2);
T ret = tmp->next->data;
delete(tmp->next);
tmp->next = NULL;
last = tmp;
_size--;
return ret;
}
else {
// Only one element left on the list
T ret = root->data;
delete(root);
root = NULL;
last = NULL;
_size = 0;
return ret;
}
}
template<typename T>
T LinkedList<T>::shift() {
if (_size <= 0)
return T();
if (_size > 1) {
ListNode<T> *_next = root->next;
T ret = root->data;
delete(root);
root = _next;
_size--;
isCached = false;
return ret;
}
else {
// Only one left, then pop()
return pop();
}
}
template<typename T>
T LinkedList<T>::remove(int index) {
if (index < 0 || index >= _size)
{
return T();
}
if (index == 0)
return shift();
if (index == _size - 1)
{
return pop();
}
ListNode<T> *tmp = getNode(index - 1);
ListNode<T> *toDelete = tmp->next;
T ret = toDelete->data;
tmp->next = tmp->next->next;
delete(toDelete);
_size--;
isCached = false;
return ret;
}
template<typename T>
T LinkedList<T>::get(int index) {
ListNode<T> *tmp = getNode(index);
return (tmp ? tmp->data : T());
}
template<typename T>
void LinkedList<T>::clear() {
while (size() > 0)
shift();
}
#endif //CODE_BLOCK_LinkedList
/// <summary>
/// A list to store IP addresses
/// </summary>
class IPAddressList : public LinkedList<IPAddress*> {
private:
void destory();
public:
bool add(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet);
bool add(IPAddress address);
bool add(const char* strIpAddress);
bool exists(IPAddress address);
bool exists(String strIpaddress);
int indexOf(IPAddress address);
bool isEmpty();
bool remove(const char *strIpAddress);
bool remove(IPAddress address);
String toJson();
~IPAddressList();
};
/// <summary>
/// Possible types of a pin are:
/// <para/>PINTYPE_INPUT_ANALOG : "Read method analogRead shall be used"
/// <para/>PINTYPE_INPUT_DIGITAL : "Read method digitalRead shall be used"
/// <para/>PINTYPE_OUTPUT_ANALOG : "Write method analogWrite shall be used"
/// <para/>PINTYPE_OUTPUT_DIGITAL : "Write method digitalWrite shall be used"
/// <para/>PINTYPE_OUTPUT_VIRTUAL : "A pin not connected to hardware, but can store values"
/// </summary>
enum PINTYPE {
PINTYPE_INPUT_ANALOG,
PINTYPE_INPUT_DIGITAL,
PINTYPE_OUTPUT_ANALOG,
PINTYPE_OUTPUT_DIGITAL,
PINTYPE_OUTPUT_VIRTUAL
};
/// <summary>
/// Class for handling GPIO pins
/// Use it to read from or write to a pin
/// </summary>
class GPin {
private:
int mNumber;
int mValue;
PINTYPE mType;
char *mName;
#ifdef ESP32
#define LEDC_TIMER_13_BIT 13
#define LEDC_BASE_FREQ 8100
int mChannel;
void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 255);
void analogWriteEsp32();
#endif
void init(const char*strPinName, PINTYPE pinType, int pinNumber, int pinValue);
void set(int number, int value);
String jsonKeyValue(String key, int value);
void destroy();
public:
#ifdef ESP32
GPin(const char*strPinName, PINTYPE pinType, int pinNumber, int pinValue, uint8_t pinChannel);
#else
GPin(const char *strPinName, PINTYPE pinType, int pinNumber, int pinValue);
#endif
~GPin();
void setName(const char*strPinName);
String getName();
void setValue(int value);
int getValue(bool readValueFromHardware = true);
int getNumber();
int getType();
String toJson();
String toJsonKeyValue();
};
/// <summary>
/// This class stores GPin objects which connect the server to device hardware pins
///<para/>
/// </summary>
class GPins {
private:
int mLength = 0;
#ifdef ESP32
int mChannelCount = 0;
#endif
GPin *mPins[30];//todo: I make this dynamic, instead of a fixed size
int indexOf(int pinNumber);
public:
int addPin(const char *strPinName, PINTYPE pinType, int pinNumber, int pinValue);
boolean setValue(int pinNumber, int newValue);
boolean exists(int pinNumber);
GPin *get(int pinNumber);
int getValue(int pinNumber);
int count();
String toJson();
String JsonPinout();
GPins();
};
/// <summary>
/// Used to store time.
/// Depended on which constuctor is used, values can be eather a "date and time" or a "counter" up to 49 days.
/// </summary>
class GTime {
///////////////////////////////////////////////////////////
private:
int mYear = 0;
int mMonth = 0;
int mDay = 0;
int mHours = 0;
int mMinutes = 0;
int mSeconds = 0;
public:
GTime() { }
GTime(const GTime& gTime);
GTime(unsigned long milliSeconds);
void setTime(unsigned long milliSeconds);
boolean setTime(String strTime);
int strToMonth(String month);
static int toNumber(String str);
String toString();
String toStreng();
String toJson();
int getYear();
int getMonth();
int getDay();
int getHours();
int getMinutes();
int getSeconds();
};
/// <summary>
/// Used to store only Number and value of a pin
/// </summary>
struct PinValue
{
int pinNumber;
int pinValue;
};
class GUrl {
private:
int mLength = 0;
public:
GUrl() { }
int toNumber(String str);
String jsonKeyValue(String key, String value);
String jsonKeyValue(String key, int value);
String jsonObjectType(unsigned int uiType);
String makeStatusResponceJson(String jsonPins, String jsonWhitelist, String jsonDate);
String makePostLogPinsJson(String deviceId, String jsonPins);
String makeHttpStatusCodeString(unsigned int uiStatusCode);
String jsonRoot(unsigned int uiType, String key, String value);
};
/// <summary>
/// The errornumber to return when a numberfunction fails;
/// Like: toInt(), toFloat(), toLong(), toULong()
/// </summary>
#define JSONDATA_ERRORNUMBER 999999999
//See informanation on JSON on https://www.json.org (nice pictures)
//See more info here : https://www.crockford.com/mckeeman.html
//todo: Hexadecimal digits can be represented as u and then 4 hexadecimal digits. (\u hex hex hex hex)
// hex can be ('0'..'9' or 'A'..'F' or 'a'..'f')
//todo: Exponent numbers see second answser: https://stackoverflow.com/questions/19554972/json-standard-floating-point-numbers
// example1: 1e-005 example2: 2.99792458e8 Exponent can be ('E' sign digits) or ('e' sign digits)
/// <summary>
/// Enumeration for which type of json object the json data is.
/// </summary>
enum JSONTYPE {
JSONTYPE_INVALID,
JSONTYPE_ARRAY,
JSONTYPE_OBJECT,
JSONTYPE_KEY_VALUE,
JSONTYPE_STRING,
JSONTYPE_ULONG,
JSONTYPE_LONG,
JSONTYPE_FLOAT,
JSONTYPE_BOOL,
JSONTYPE_NULL,
};
/// <summary>
/// Class for representing elements and objects in a json object.
/// You can use it to browse and get values and add and remove objects from a json.
/// </summary>
/// <example>
/// Example hello World:
/// @code{.xml}
/// // Create an json object with one key named "hello"
/// // and one value which is the string "world"
/// JsonData js("{\"hello\":\"world\"}");
/// @endcode
/// </example>
class JsonData
{
private:
String mValue;
JSONTYPE mType;
JSONTYPE mValueType;
JsonData *mFirstChild{},
*mNext{},
*mParent{};
JsonData(JSONTYPE type, JsonData* parent);
JsonData(String jsonString, JsonData* parent);
JsonData(String value, JSONTYPE type, JSONTYPE valueType, JsonData* parent);
static bool isClosingToken(char c);
static char getClosingToken(char openingToken);
static int getIndexOfClosingToken(String* string, bool ignoreStrings);
static bool isDigit(char c);
static bool removeLast(JsonData* pNode);
static bool destroyIncludingChildren(JsonData* pNode);
static JSONTYPE getValueTypeFromChar(char firstCharInValue);
static JSONTYPE getType(String strValue);
static JsonData *getLastChild(JsonData* parent);
static JsonData *getLastNode(JsonData* previous);
static JsonData *getPointingNode(JsonData* findMe);
static JsonData *findPointingNode(JsonData* startFrom, JsonData* findMe);
static JsonData *getRootNode(JsonData* current);
void init(JSONTYPE type, JSONTYPE valueType, JsonData* parent);
void parse(const String jsonString, JsonData* parent);
JsonData *setRootInvalid();
String valueToString();
JsonData *array(String* elements, JsonData* parent, bool canBeMoreThanOne);
JsonData *object(String* members, JsonData* parent);
JsonData *elements(String* values, JsonData* parent);
bool getPairIndexes(String* pairs, bool& thereIsAnotherPair,
int &keyIndexOfFirstChar, int& keyLength,
int &valueIndexOfFirstChar, int& valueLength,
int &pairLength);
JsonData *members(String* pairs, JsonData* parent);
JsonData *pair(String* keyValues, JsonData* parent);
static bool validateValue(const JSONTYPE jsonvaluetype, String string);
JsonData *value(String* valuesString, JsonData* parent);
static String jsonTypeString(JSONTYPE type);
String toTree(JsonData* current, int level);
static bool isWhitespace(const char c);
public:
JsonData(const char* jsonString);
~JsonData();
String toString();
String toTree();
static String trim(String jsonStringToTrim);
bool isValid() const;
/// <summary>
/// Checks if the current object has any child objects
/// </summary>
/// <returns>
/// true if this object has one ore more child object(s). Otherwize false
/// </returns>
bool hasChildren() { return this->mFirstChild != NULL; };
JsonData *getChildAt(unsigned int index);
JsonData *getChild(String value);
JsonData *getNext();
const String getValue();
String getValueAsString();
float getValueAsFloat();
unsigned long getValueAsULong();
long getValueAsLong();
int getValueAsInt();
JSONTYPE getType() const { return mType; }
JSONTYPE getValueType() const { return mValueType; }
};
/// <summary>
/// A class for parsing json strings
/// </summary>
/// <example>
/// Example on how to create a json object from a string:
/// @code{.xml}
/// Json json("{\"hello\":\"world\",\"array\":[1,2,-4,-5.22,\"string in a array\"]}");
/// @endcode
/// </example>
class Json
{
JsonData *mData;
public:
Json(const char *jsonString);
~Json();
String toString() const;
String toTree() const;
static String trim(String jsonStringToTrim);
bool isValid() const;
/// <summary>
/// Use this function access the root JsonData object
/// </summary>
/// <returns>
/// The root JsonData object.
/// If the object is invalid NULL is returned.
/// </returns>
JsonData *getRootObject() { return mData == NULL || !mData->isValid()? NULL: mData; };
};
/// <summary>
/// Used to monitor a pin.
/// Can monitor if a pin value changes more or less than something
/// and can monitor if a certain amount of time has passed.
/// </summary>
class PinWatch
{
private:
GPin* pin;
unsigned long sampleSum = 0; // Sum of pin value samples
unsigned int pinValueLast = 0; // The pin value which was last logged.
unsigned int pinValueMargin = 0; // How much must a sampleSum / sampleCount change from pinValueLast to trigger a log.
int sampleCount = 0; // How many times has the pinValueSum been summerized.
int sampleTotalCount = 0; // How many samples before we can average sampleSum and compare with pinValueLast
unsigned long nextSampleTime; // When should we get the next sample
unsigned long sampleInterval; // How long between samples
unsigned long minLogInterval; // The minimum time allowed to pass between logs. Set to 0 to disable
unsigned long nextLogTime; // If minLogInterval is > 0 then this will be the time when we must log
// This time must be reset after each log.
void resetAllValues();
void init(GPin* gPin, unsigned int pinValueMargin, int sampleTotalCount, unsigned long sampleInterval, unsigned long minLogInterval);
public:
PinWatch(GPin* gPin, unsigned int pinValueMargin, int sampleTotalCount, unsigned long sampleInterval, unsigned long minLogInterval);
PinWatch(const PinWatch& pinWatch);
void serialPrintValues();
void serialPrintLnValues();
bool check(unsigned long currentTimeInMillis);
void reset(unsigned long currentTimeInMillis, bool updateLastPinValue = true, bool updateMinLogInterval = true);
int getPinNumber();
int getPinValue();
int getPinType();
bool isValidPin();
String toJson();
};
/// <summary>
/// PinWatchList allows you to add one or more timers and/or monitor value changes on multiple pins
/// </summary>
/// <example>
/// Example:
/// @code{.xml}
/// PinWatchList watchList;
/// void setup(void) {
/// watchList.addPinValueMonitoring(devicePins.get(D0), 1, 1, 1000);
/// watchList.addPinValueMonitoringAndTimer(devicePins.get(D1), 2, 2, 1000, 1000 * 60 * 3);
/// watchList.addTimer(1000 * 30 * 9);
/// }
///
/// void loop(void) {
/// if (watchList.isAnyPinWatchDo()) {
/// // One item did trigger so you could log
/// watchList.resetAllChecks();
/// }
/// }
/// @endcode
/// </example>
class PinWatchList : public LinkedList<PinWatch*> {
private:
void destory();
bool removeByIndex(int index);
bool add(GPin* gPin, int pinValueMargin, int sampleTotalCount, unsigned long sampleInterval, unsigned long minLogInterval);
bool addJsonPinWatchToList(JsonData* jsonObject, GPins* devicePins);
PinWatch* NewPinWatchFromJsonObject(JsonData* jsonObject, GPins* devicePins);
public:
bool add(PinWatch pinWatch);
bool add(PinWatch* ptrPinWatch);
bool update(int index, PinWatch pinWatch);
bool addOrUpdate(PinWatch pinWatch);
bool addTimer(unsigned long minLogInterval);
bool addPinValueMonitoring(GPin* gPin, int pinValueMargin, int sampleTotalCount, unsigned long sampleInterval);
bool addPinValueMonitoringAndTimer(GPin* gPin, int pinValueMargin, int sampleTotalCount, unsigned long sampleInterval, unsigned long minLogInterval);
bool exists(int pinNumber);
int indexOfPin(int pinNumber);
bool isEmpty();
bool removePin(int pinNumber);
bool isAnyPinWatchDo();
int getFirstPinWatchDo();
int getNextPinWatchDo(int index);
void resetAllChecks();
int updateMonitorFromJsonObject(JsonData* root, GPins *devicePins);
int deleteMonitorFromJsonObject(JsonData* root);
String toJson();
~PinWatchList();
};
enum METHODS {
METHOD_NOTSET,
METHOD_GET,
METHOD_POST,
METHOD_DELETE
};
enum COMMANDS {
COMMANDS_NOTSET,
COMMANDS_POST_PINS,
COMMANDS_POST_WHITELIST,
COMMANDS_DELETE_WHITELIST
};
//INSERT_FROM_FILE_first.h
int contentLength = 0;
METHODS method = METHODS::METHOD_NOTSET;
COMMANDS command = COMMANDS::COMMANDS_NOTSET;
//////// GLOBAL VARIABLES /////////////////////////////////////////////////////
GPins devicePins;
IPAddressList whiteList;
GTime startTime;
GUrl urlTool;
PinWatchList monitors;
char linebuf[580];
int charcount = 0;
//////////////////////// Global Functions ///////////////////////////////
String reportIn() {
Serial.println("Reporting in ");
String ret = "Fri, 1 Jan 1971 00:00:00 GMT";
String data = "{" +
urlTool.jsonKeyValue("id", "\"" + String(deviceId) + "\",") +
urlTool.jsonKeyValue("ip", "\"" + WiFi.localIP().toString() + "\",") +
urlTool.jsonKeyValue("port", PORT) +
"}";
HTTPClient http;
String host = voffconServerIp.toString() + ":" + String(voffconServerPort);
String url = "http://" + host + "/devices/reportin";
http.begin(url); //Specify destination for HTTP request
http.addHeader("Content-Type", "application/json");
http.addHeader("Connection", "close");
Serial.println("sending");
Serial.println(data);
int httpResponseCode = http.POST(data); //Send the actual POST request
if (httpResponseCode>0) {
String response = http.getString(); //Get the response to the request
Serial.println(httpResponseCode); //Print return code
Serial.println(response); //Print request answer
ret = response; //responce should contain date.toUTCString()
}
else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end(); //Free resources
return ret;
}
void tellServerToSaveLog() {
Serial.println("Telling server to log the device pins");
HTTPClient http;
String host = voffconServerIp.toString() + ":" + String(voffconServerPort);
String url = "http://" + host + "/logs/pins/" + deviceId;
http.begin(url);
http.addHeader("Connection", "close");
Serial.print("Calling : "); Serial.println(url);
int httpResponseCode = http.GET(); //make the request to server
Serial.print("Responce code: "); Serial.println(httpResponseCode); //return code
Serial.println(http.getString()); //The response to the request
http.end(); //Free resources
}
void tellServerToSendMonitors() {
Serial.println("Telling server to send monitors");
HTTPClient http;
String host = voffconServerIp.toString() + ":" + String(voffconServerPort);
String url = "http://" + host + "/monitors/update/" + deviceId;
http.begin(url);
http.addHeader("Connection", "close");
Serial.print("Calling : "); Serial.println(url);
int httpResponseCode = http.GET(); //make the request to server
Serial.print("Responce code: "); Serial.println(httpResponseCode); //return code
Serial.println(http.getString()); //The response to the request
http.end(); //Free resources
}
void SerialPrint(String str, int value) {
Serial.print(str + " ");
Serial.print(value);
}
void SerialPrintLn(String str, String value, bool setMarkerAtBeginningAndEndOfValue = false) {
Serial.print(str + " ");
if (setMarkerAtBeginningAndEndOfValue)
value = "|" + value + "|";
Serial.println(value);
}
void SerialPrintLn(String str, int value) {
SerialPrint(str, value);
Serial.println();
}
/// <summary>
/// Parses Json text and extracts a key value from it.
/// The function assumes that the jsonText has only child objects of Json Key values.
/// Like so: {"key1":1,"key2":"string2"}
/// </summary>
/// <param name="jsonText"></param>
/// <param name="key"></param> The key of a Key value object;
/// <returns>Success: The value as a string. Fail: an empty string</returns>
String getKeyValueFromJsonAsString(String jsonText, String key) {
Json parser(jsonText.c_str());
JsonData* root = parser.getRootObject();
if (root == NULL || !root->isValid()) {
Serial.println("Invalid json root object");
return "";
};
JsonData* current = root->getChild(key);
if (current == NULL)
return "";
return current->getValueAsString();
}
/// <summary>
/// Extracts pin numbers and values from the given string
/// and sets the pin values according to what was extracted.
/// </summary>
/// <param name="unParsedJson">A json string on the form { "3":220}</param>
/// <returns>true if successful otherwhise false</returns>
bool setPinValues(String jsonString, GPins* devicePins) {
Json parser(jsonString.c_str());
JsonData* root = parser.getRootObject();