-
Notifications
You must be signed in to change notification settings - Fork 279
/
aREST.h
2084 lines (1571 loc) · 46.4 KB
/
aREST.h
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
/*
aREST Library for Arduino
See the README file for more details.
Written in 2014 by Marco Schwartz.
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License:
http://creativecommons.org/licenses/by-sa/4.0/
Version 2.9.7
Changelog:
Version 2.9.7: Added URL for mqtt server
Version 2.9.6: Add ID generator for ESP32
Version 2.9.5: Compatibility with latest ESP8266 library
Version 2.9.4: Publish() fixes
Version 2.9.3: Compatibility fix
Version 2.9.2: Fixes for cloud examples
Version 2.9.1: Compatibility fix for the new aREST cloud broker (Aedes)
Version 2.9.0: Compatibility fix for the new aREST cloud server
Version 2.8.1: Updated examples with publish()
Version 2.8.0: Compatibility with the new aREST cloud server
Version 2.7.5: Added rate-limitation for publish()
Version 2.7.4: Fix for the Arduino Ethernet 2.0 library
Version 2.7.3: Added support to set your own ID when using API key
Version 2.7.2: Bug fixes for aREST.io
Version 2.7.1: Additional fixes & optimisations by @eykamp
Version 2.7.0: Several fixes & optimisations by @eykamp
Version 2.6.0: Added support for new aREST cloud app
Version 2.5.0: Added support for the ESP32 WiFi chip (local & cloud)
Version 2.4.2: Added publish() support for MKR1000
Version 2.4.1: Additional fixes for Pro plans
Version 2.4.0: Added support for aREST Pro & several fixes
Version 2.3.1: Fixed pin mapping for NodeMCU/Wemos boards
Version 2.3.0: Implement required changes for the cloud server upgrade
Version 2.2.1: Added compatibility with the WINC1500 chip
Version 2.2.0: Added compatibility with the Arduino MKR1000 board
Version 2.1.2: Added data about hardware type in JSON answer
Version 2.1.1: Fixed analogWrite() for ESP8266 chips
Version 2.1.0: Added publish() function
Version 2.0.2: Able to change MQTT remote server
Version 2.0.2: Added cloud access support for the Ethernet library
Version 2.0.1: Added beta support for cloud access via cloud.arest.io
Version 2.0.0: Added beta support for MQTT communications
Version 1.9.10: Added support for floats & Strings for Uno (without the CC3000 chip)
Version 1.9.8: Added support for ESP8266 chip
Version 1.9.7: Added support for Arduino 1.6.2
Version 1.9.6: Added support for float variables for Arduino Mega
Version 1.9.5: Added compatibility with Arduino IDE 1.5.8
Version 1.9.4: Bug fixes & added support for configuring analog pints as digital outputs
Version 1.9.3: Added description of available variables for the /id and / routes
Version 1.9.2: Added compatibility with the Arduino WiFi library
Version 1.9.1: Added compatibility with CORS
Version 1.9: New speedup of the library (answers 2x faster in HTTP compared to version 1.8)
Version 1.8: Speedup of the library (answers 2.5x faster with the CC3000 WiFi chip)
Version 1.7.5: Reduced memory footprint of the library
Version 1.7.4: Added a function to read all analog & digital inputs at once
Version 1.7.3: Added LIGHTWEIGHT mode to only send limited data back
Version 1.7.2: Added possibility to assign a status pin connected to a LED
Version 1.7.1: Added possibility to change number of exposed variables & functions
Version 1.7: Added compatibility with the Arduino Due & Teensy 3.x
Version 1.6: Added compatibility with the Arduino Yun
Version 1.5: Size reduction, and added compatibility with Adafruit BLE
Version 1.4: Added authentification with API key
Version 1.3: Added support for the Ethernet shield
Version 1.2: Added support of Serial communications
Version 1.1: Added variables & functions support
Version 1.0: First working version of the library
*/
#ifndef aRest_h
#define aRest_h
// Include Arduino header
#include "Arduino.h"
// MQTT packet size
#undef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 512
// Using ESP8266 ?
#if defined(ESP8266) || defined(ESP32)
#include "stdlib_noniso.h"
#endif
// Which board?
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(CORE_WILDFIRE) || defined(ESP8266) || defined(ESP32)
#define NUMBER_ANALOG_PINS 16
#define NUMBER_DIGITAL_PINS 54
#define OUTPUT_BUFFER_SIZE 2000
#elif defined(__AVR_ATmega328P__) && !defined(ADAFRUIT_CC3000_H)
#define NUMBER_ANALOG_PINS 6
#define NUMBER_DIGITAL_PINS 14
#define OUTPUT_BUFFER_SIZE 350
#elif defined(ADAFRUIT_CC3000_H)
#define NUMBER_ANALOG_PINS 6
#define NUMBER_DIGITAL_PINS 14
#define OUTPUT_BUFFER_SIZE 275
#else
#define NUMBER_ANALOG_PINS 6
#define NUMBER_DIGITAL_PINS 14
#define OUTPUT_BUFFER_SIZE 350
#endif
// Hardware data
#if defined(ESP8266)
#define HARDWARE "esp8266"
#elif defined(ESP32)
#define HARDWARE "esp32"
#else
#define HARDWARE "arduino"
#endif
// Size of name & ID
#define NAME_SIZE 20
#define ID_SIZE 10
// Subscriptions
#define NUMBER_SUBSCRIPTIONS 4
// Debug mode
#ifndef DEBUG_MODE
#define DEBUG_MODE 0
#endif
// Use AREST_PARAMS_MODE to control how parameters are parsed when using the function() method.
// Use 0 for standard operation, where everything before the first "=" is stripped before passing the parameter string to the function.
// Useful for simple functions, where only the value is important
// function?params=hello ==> hello gets passed to the function
//
// Use 1 to pass the entire parameter string to the function, which will be responsible for parsing the parameter string
// Useful for more complex situations, where the key name as well as its value is important, or there are mutliple key-value pairs
// function?params=hello ==> params=hello gets passed to the function
#ifndef AREST_PARAMS_MODE
#define AREST_PARAMS_MODE 0
#endif
// Use light answer mode
#ifndef LIGHTWEIGHT
#define LIGHTWEIGHT 0
#endif
#ifdef AREST_NUMBER_VARIABLES
#define NUMBER_VARIABLES AREST_NUMBER_VARIABLES
#endif
#ifdef AREST_NUMBER_FUNCTIONS
#define NUMBER_FUNCTIONS AREST_NUMBER_FUNCTIONS
#endif
// Default number of max. exposed variables
#ifndef NUMBER_VARIABLES
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(CORE_WILDFIRE) || defined(ESP8266)|| defined(ESP32) || !defined(ADAFRUIT_CC3000_H)
#define NUMBER_VARIABLES 10
#else
#define NUMBER_VARIABLES 5
#endif
#endif
// Default number of max. exposed functions
#ifndef NUMBER_FUNCTIONS
#if defined(__AVR_ATmega1280__) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(CORE_WILDFIRE) || defined(ESP8266)
#define NUMBER_FUNCTIONS 10
#else
#define NUMBER_FUNCTIONS 5
#endif
#endif
#ifdef AREST_BUFFER_SIZE
#define OUTPUT_BUFFER_SIZE AREST_BUFFER_SIZE
#endif
class aREST {
private:
struct Variable {
virtual void addToBuffer(aREST *arest) const = 0;
};
template<typename T>
struct TypedVariable: Variable {
T *var;
bool quotable;
TypedVariable(T *v, bool q) : var{v} { quotable = q; }
void addToBuffer(aREST *arest) const override {
arest->addToBuffer(*var, quotable);
}
};
public:
public:
aREST() {
initialize();
}
aREST(char* rest_remote_server, int rest_port) {
initialize();
remote_server = rest_remote_server;
port = rest_port;
}
template<typename T>
void variable(const char *name, T *var, bool quotable) {
variables[variables_index] = new TypedVariable<T>(var, quotable);
variable_names[variables_index] = name;
variables_index++;
}
template<typename T>
void variable(const char *name, T *var) {
variable(name, var, true);
}
private:
void initialize() {
reset();
status_led_pin = 255;
}
// Used when resetting object back to oringial state
void reset() {
command = 'u';
state = 'u';
pin_selected = false;
}
public:
#if defined(PubSubClient_h)
// With default server
aREST(PubSubClient& client) {
initialize();
private_mqtt_server = false;
client.setServer(mqtt_server, 1883);
}
// With another server
aREST(PubSubClient& client, char* new_mqtt_server) {
initialize();
private_mqtt_server = true;
setMQTTServer(new_mqtt_server);
client.setServer(new_mqtt_server, 1883);
}
// Get topic
String get_topic() {
return out_topic;
}
// Subscribe to events
void subscribe(const String& device, const String& eventName) {
// Build topic
String topic = device + "_" + eventName + "_in";
// Subscribe
char charBuf[50];
topic.toCharArray(charBuf, 50);
subscriptions_names[subscriptions_index] = charBuf;
subscriptions_index++;
}
// Publish to cloud
template <typename T>
void publish(PubSubClient& client, const String& eventName, T data) {
uint32_t currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// Get event data
if (DEBUG_MODE) {
Serial.print("Publishing event " + eventName + " with data: ");
Serial.println(data);
}
// Build message
String message = "{\"client_id\": \"" + id + "\", \"event_name\": \"" + eventName + "\", \"data\": \"" + String(data) + "\"}";
if (DEBUG_MODE) {
Serial.print("Sending message via MQTT: ");
Serial.println(message);
}
// Convert
char charBuf[100];
message.toCharArray(charBuf, 100);
// Publish
client.publish(publish_topic.c_str(), charBuf);
}
}
template <typename T>
void publish(PubSubClient& client, const String& eventName, T data, uint32_t customInterval) {
uint32_t currentMillis = millis();
if (currentMillis - previousMillis >= customInterval) {
previousMillis = currentMillis;
// Get event data
if (DEBUG_MODE) {
Serial.print("Publishing event " + eventName + " with data: ");
Serial.println(data);
}
// Build message
String message = "{\"client_id\": \"" + id + "\", \"event_name\": \"" + eventName + "\", \"data\": \"" + String(data) + "\"}";
if (DEBUG_MODE) {
Serial.print("Sending message via MQTT: ");
Serial.println(message);
}
// Convert
char charBuf[100];
message.toCharArray(charBuf, 100);
// Publish
client.publish(publish_topic.c_str(), charBuf);
}
}
void setKey(char* api_key) {
// Set
proKey = String(api_key);
if (id.length() == 0) {
// Generate MQTT random ID
id = gen_random(6);
}
// Build topics IDs
in_topic = id + String(api_key) + String("_in");
out_topic = id + String(api_key) + String("_out");
publish_topic = id + String(api_key) + String("_event");
// strcpy(in_topic, inTopic.c_str());
// strcpy(out_topic, outTopic.c_str());
// Build client ID
client_id = id + String(api_key);
}
// void setKey(char* api_key, PubSubClient& client) {
// // Set
// proKey = String(api_key);
// if (id.length() == 0) {
// // Generate MQTT random ID
// id = gen_random(6);
// }
// // Build topics IDs
// String inTopic = id + String(api_key) + String("_in");
// String outTopic = id + String(api_key) + String("_out");
// strcpy(in_topic, inTopic.c_str());
// strcpy(out_topic, outTopic.c_str());
// // Build client ID
// client_id = id + String(api_key);
// client_id = id + String(proKey);
// }
#endif
// Set status LED
void set_status_led(uint8_t pin){
// Set variables
status_led_pin = pin;
// Set pin as output
pinMode(status_led_pin, OUTPUT);
}
#if !defined(ESP32)
// Glow status LED
void glow_led() {
if(status_led_pin != 255){
unsigned long i = millis();
int j = i % 4096;
if (j > 2048) { j = 4096 - j;}
analogWrite(status_led_pin,j/8);
}
}
#endif
void addToBufferF(const __FlashStringHelper *toAdd){
if (DEBUG_MODE) {
#if defined(ESP8266)|| defined (ESP32)
Serial.print("Memory loss:");
Serial.println(freeMemory - ESP.getFreeHeap(),DEC);
freeMemory = ESP.getFreeHeap();
#endif
Serial.print(F("Added to buffer as progmem: "));
Serial.println(toAdd);
}
uint8_t idx = 0;
PGM_P p = reinterpret_cast<PGM_P>(toAdd);
for ( unsigned char c = pgm_read_byte(p++);
c != 0 && index < OUTPUT_BUFFER_SIZE;
c = pgm_read_byte(p++), index++) {
buffer[index] = c;
}
}
// Send HTTP headers for Ethernet & WiFi
void send_http_headers(){
addToBufferF(F("HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: POST, GET, PUT, OPTIONS\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n"));
}
// Reset variables after a request
void reset_status() {
if (DEBUG_MODE) {
#if defined(ESP8266)|| defined (ESP32)
Serial.print("Memory loss before reset:");
Serial.println(freeMemory - ESP.getFreeHeap(),DEC);
freeMemory = ESP.getFreeHeap();
#endif
}
reset();
answer = "";
arguments = "";
index = 0;
//memset(&buffer[0], 0, sizeof(buffer));
if (DEBUG_MODE) {
#if defined(ESP8266)|| defined (ESP32)
Serial.print("Memory loss after reset:");
Serial.println(freeMemory - ESP.getFreeHeap(),DEC);
freeMemory = ESP.getFreeHeap();
Serial.print("Memory free:");
Serial.println(freeMemory, DEC);
#endif
}
}
// Handle request with the Adafruit CC3000 WiFi library
#ifdef ADAFRUIT_CC3000_H
void handle(Adafruit_CC3000_ClientRef& client) {
if (client.available()) {
// Handle request
handle_proto(client,true,0,false);
// Answer
sendBuffer(client,32,20);
client.stop();
// Reset variables for the next command
reset_status();
}
}
template <typename T>
void publish(Adafruit_CC3000_ClientRef& client, const String& eventName, T value) {
// Publish request
publish_proto(client, eventName, value);
}
// Handle request with the Arduino Yun
#elif defined(_YUN_CLIENT_H_)
void handle(YunClient& client) {
if (client.available()) {
// Handle request
handle_proto(client,false,0,false);
// Answer
sendBuffer(client,25,10);
client.stop();
// Reset variables for the next command
reset_status();
}
}
template <typename T>
void publish(YunClient& client, const String& eventName, T value) {
// Publish request
publish_proto(client, eventName, value);
}
// Handle request with the Adafruit BLE board
#elif defined(_ADAFRUIT_BLE_UART_H_)
void handle(Adafruit_BLE_UART& serial) {
if (serial.available()) {
// Handle request
handle_proto(serial,false,0,false);
// Answer
sendBuffer(serial,100,1);
// Reset variables for the next command
reset_status();
}
}
// template <typename T>
// void publish(Adafruit_BLE_UART& serial, const String& eventName, T value) {
// // Publish request
// publish_proto(client, eventName, value);
// }
// Handle request for the Arduino Ethernet shield
#elif defined(ethernet_h_)
void handle(EthernetClient& client){
if (client.available()) {
// Handle request
handle_proto(client,true,0,false);
// Answer
sendBuffer(client,50,0);
client.stop();
// Reset variables for the next command
reset_status();
}
}
template <typename T>
void publish(EthernetClient& client, const String& eventName, T value) {
// Publish request
publish_proto(client, eventName, value);
}
// Handle request for the Cytron Clone ESP8266
#elif defined(_CYTRONWIFISERVER_H_)
void handle(ESP8266Client& client){
if (client.available()) {
// Handle request
handle_proto(client,true,0,true);
// Answer
sendBuffer(client,0,0);
client.stop();
// Reset variables for the next command
reset_status();
}
}
// Handle request for the ESP8266 chip
#elif defined(ESP8266) || defined (ESP32)
void handle(WiFiClient& client){
if (DEBUG_MODE) {
Serial.print("Memory loss before available:");
Serial.println(freeMemory - ESP.getFreeHeap(),DEC);
freeMemory = ESP.getFreeHeap();
}
if (client.available()) {
if (DEBUG_MODE) {
Serial.print("Memory loss before handling:");
Serial.println(freeMemory - ESP.getFreeHeap(),DEC);
freeMemory = ESP.getFreeHeap();
}
// Handle request
handle_proto(client,true,0,true);
if (DEBUG_MODE) {
Serial.print("Memory loss after handling:");
Serial.println(freeMemory - ESP.getFreeHeap(),DEC);
freeMemory = ESP.getFreeHeap();
}
// Answer
sendBuffer(client,0,0);
client.stop();
// Reset variables for the next command
reset_status();
}
}
// Handle request on the Serial port
void handle(HardwareSerial& serial){
if (serial.available()) {
// Handle request
handle_proto(serial,false,1,false);
// Answer
sendBuffer(serial,25,1);
// Reset variables for the next command
reset_status();
}
}
template <typename T>
void publish(WiFiClient& client, const String& eventName, T value) {
// Publish request
publish_proto(client, eventName, value);
}
// Handle request for the Arduino MKR1000 board
#elif defined(WIFI_H)
void handle(WiFiClient& client){
if (client.available()) {
if (DEBUG_MODE) {Serial.println("Request received");}
// Handle request
handle_proto(client,true,0,true);
// Answer
sendBuffer(client,0,0);
client.stop();
// Reset variables for the next command
reset_status();
}
}
template <typename T>
void publish(WiFiClient& client, const String& eventName, T value) {
// Publish request
publish_proto(client, eventName, value);
}
// Handle request for the Arduino WiFi shield
#elif defined(WiFi_h)
void handle(WiFiClient& client){
if (client.available()) {
if (DEBUG_MODE) {Serial.println("Request received");}
// Handle request
handle_proto(client,true,0,true);
// Answer
sendBuffer(client,50,1);
client.stop();
// Reset variables for the next command
reset_status();
}
}
template <typename T>
void publish(WiFiClient& client, const String& eventName, T value) {
// Publish request
publish_proto(client, eventName, value);
}
#elif defined(CORE_TEENSY)
// Handle request on the Serial port
void handle(usb_serial_class& serial){
if (serial.available()) {
// Handle request
handle_proto(serial,false,1,false);
// Answer
sendBuffer(serial,25,1);
// Reset variables for the next command
reset_status();
}
}
template <typename T>
void publish(usb_serial_class& client, const String& eventName, T value) {
// Publish request
publish_proto(client, eventName, value);
}
#elif defined(__AVR_ATmega32U4__)
// Handle request on the Serial port
void handle(Serial_& serial){
if (serial.available()) {
// Handle request
handle_proto(serial,false,1,false);
// Answer
sendBuffer(serial,25,1);
// Reset variables for the next command
reset_status();
}
}
template <typename T>
void publish(Serial_& client, const String& eventName, T value) {
// Publish request
publish_proto(client, eventName, value);
}
#else
// Handle request on the Serial port
void handle(HardwareSerial& serial){
if (serial.available()) {
// Handle request
handle_proto(serial,false,1,false);
// Answer
sendBuffer(serial,25,1);
// Reset variables for the next command
reset_status();
}
}
template <typename T>
void publish(HardwareSerial& client, const String& eventName, T value) {
// Publish request
publish_proto(client, eventName, value);
}
#endif
void handle(char * string) {
// Process String
handle_proto(string);
// Reset variables for the next command
reset_status();
}
void handle_proto(char * string) {
// Check if there is data available to read
for (int i = 0; i < strlen(string); i++){
char c = string[i];
answer = answer + c;
// Process data
process(c);
}
// Send command
send_command(false, false);
}
template <typename T, typename V>
void publish_proto(T& client, const String& eventName, V value) {
// Format data
String data = "name=" + eventName + "&data=" + String(value);
Serial.println("POST /" + id + "/events HTTP/1.1");
Serial.println("Host: " + String(remote_server) + ":" + String(port));
Serial.println(F("Content-Type: application/x-www-form-urlencoded"));
Serial.print(F("Content-Length: "));
Serial.println(data.length());
Serial.println();
Serial.print(data);
// Send request
client.println(F("POST /1/events HTTP/1.1"));
client.println("Host: " + String(remote_server) + ":" + String(port));
client.println(F("Content-Type: application/x-www-form-urlencoded"));
client.print(F("Content-Length: "));
client.println(data.length());
client.println();
client.print(data);
}
template <typename T>
void handle_proto(T& serial, bool headers, uint8_t read_delay, bool decode)
{
// Check if there is data available to read
while (serial.available()) {
// Get the server answer
char c = serial.read();
delay(read_delay);
answer = answer + c;
//if (DEBUG_MODE) {Serial.print(c);}
// Process data
process(c);
}
// Send command
send_command(headers, decode);
}
#if defined(PubSubClient_h)
// Process callback
void handle_callback(PubSubClient& client, char* topic, byte* payload, unsigned int length) {
// Process received message
int i;
char mqtt_msg[100];
for(i = 0; i < length; i++) {
mqtt_msg[i] = payload[i];
}
mqtt_msg[i] = '\0';
String msgString = String(mqtt_msg);
if (DEBUG_MODE) {
Serial.print("Received message via MQTT: ");
Serial.println(msgString);
}
// Process aREST commands
String modified_message = String(msgString) + " /";
char char_message[100];
modified_message.toCharArray(char_message, 100);
// Handle command with aREST
handle(char_message);
// Read answer
char * answer = getBuffer();
// Send response
if (DEBUG_MODE) {
Serial.print("Sending message via MQTT: ");
Serial.println(answer);
Serial.print("Size of MQTT message: ");
Serial.println(strlen(answer));
Serial.print("Size of client ID: ");
Serial.println(client_id.length());
}
int max_message_size = 128 - 20 - client_id.length();
if (strlen(answer) < max_message_size) {
client.publish(out_topic.c_str(), answer);
}
else {
// Max iteration
uint8_t max_iteration = (int)(strlen(answer)/max_message_size) + 1;
// Send data
for (uint8_t i = 0; i < max_iteration; i++) {
char intermediate_buffer[max_message_size+1];
memcpy(intermediate_buffer, buffer + i*max_message_size, max_message_size);
intermediate_buffer[max_message_size] = '\0';
if (DEBUG_MODE) {
Serial.print("Intermediate buffer: ");
Serial.println(intermediate_buffer);
Serial.print("Intermediate buffer size: ");
Serial.println(strlen(intermediate_buffer));
}
client.publish(out_topic.c_str(), intermediate_buffer);
}
}
// Send message
// client.publish(out_topic, answer);
// Reset buffer
resetBuffer();
}
// Handle request on the Serial port
void loop(PubSubClient& client){
// Connect to cloud
if (!client.connected()) {
reconnect(client);
}
client.loop();
}
void handle(PubSubClient& client){
// Connect to cloud
if (!client.connected()) {
reconnect(client);
}
client.loop();
}
void reconnect(PubSubClient& client) {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print(F("Attempting MQTT connection..."));
// Attempt to connect
if (client.connect(client_id.c_str())) {
if (private_mqtt_server) {
Serial.println(F("Connected to MQTT server"));
}
else {
Serial.println(F("Connected to aREST.io"));
}
client.subscribe(in_topic.c_str());
// Subscribe to all