-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThingSpeak.h
1611 lines (1281 loc) · 47.9 KB
/
ThingSpeak.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
/*
ThingSpeak(TM) Communication Library For Particle
Enables Particle hardware to write or read data to or from ThingSpeak,
an open data platform for the Internet of Things with MATLAB analytics and visualization.
ThingSpeak ( https://www.thingspeak.com ) is an analytic IoT platform service that allows you to aggregate, visualize and analyze live data streams in the cloud.
Copyright 2018, The MathWorks, Inc.
See the accompaning licence file for licensing information.
*/
//#define PRINT_DEBUG_MESSAGES
//#define PRINT_HTTP
#ifndef ThingSpeak_h
#define ThingSpeak_h
#define TS_VER "1.5"
// Create platform defines for Particle devices
#if PLATFORM_ID == 0
#define PARTICLE_CORE
#elif PLATFORM_ID == 6
#define PARTICLE_PHOTON
#define PARTICLE_PHOTONELECTRON
#elif PLATFORM_ID == 8
#define PARTICLE_P1
#define PARTICLE_PHOTONELECTRON
#elif PLATFORM_ID == 10
#define PARTICLE_ELECTRON
#define PARTICLE_PHOTONELECTRON
#elif PLATFORM_ID == 12
#define PARTICLE_ARGON
#define PARTICLE_PHOTONELECTRON
#elif PLATFORM_ID == 13
#define PARTICLE_BORON
#define PARTICLE_PHOTONELECTRON
#elif PLATFORM_ID == 14
#error TCP connection are not supported on mesh nodes (Xenon), only mesh gateways (Argon, Boron)
#else
#error Only Core/Photon/Electron/P1/Argon/Boron are supported.
#endif
#include "math.h"
#include "application.h"
#ifdef PARTICLE_PHOTONELECTRON
extern char* dtoa(double val, unsigned char prec, char *sout);
// On spark photon, There is no itoa, so map to ltoa.
#include "string_convert.h"
#define itoa ltoa
#else
// On spark core, a long and an int are equivalent, and so there's no "ltoa" function defined. Map it to itoa.
extern char * itoa(int a, char* buffer, unsigned char radix);
#define ltoa itoa
extern char *dtostrf (double val, signed char width, unsigned char prec, char *sout);
#endif
#define THINGSPEAK_URL "api.thingspeak.com"
#define THINGSPEAK_PORT_NUMBER 80
#ifdef PARTICLE_CORE
#define TS_USER_AGENT "tslib-arduino/" TS_VER " (particle core)"
#elif defined(PARTICLE_PHOTON)
#define TS_USER_AGENT "tslib-arduino/" TS_VER " (particle photon)"
#elif defined(PARTICLE_ELECTRON)
#define TS_USER_AGENT "tslib-arduino/" TS_VER " (particle electron)"
#elif defined(PARTICLE_P1)
#define TS_USER_AGENT "tslib-arduino/" TS_VER " (particle p1)"
#elif defined(PARTICLE_ARGON)
#define TS_USER_AGENT "tslib-arduino/" TS_VER " (particle argon)"
#elif defined(PARTICLE_BORON)
#define TS_USER_AGENT "tslib-arduino/" TS_VER " (particle boron)"
#else
#define TS_USER_AGENT "tslib-arduino/" TS_VER " (particle unknown)"
#endif
#define SPARK_PUBLISH_TTL 60 // Spark "time to live" for published messages
#define SPARK_PUBLISH_TOPIC "thingspeak-debug"
#define FIELDNUM_MIN 1
#define FIELDNUM_MAX 8
#define FIELDLENGTH_MAX 255 // Max length for a field in ThingSpeak is 255 bytes (UTF-8)
#define TIMEOUT_MS_SERVERRESPONSE 5000 // Wait up to five seconds for server to respond
#define OK_SUCCESS 200 // OK / Success
#define ERR_BADAPIKEY 400 // Incorrect API key (or invalid ThingSpeak server address)
#define ERR_BADURL 404 // Incorrect API key (or invalid ThingSpeak server address)
#define ERR_OUT_OF_RANGE -101 // Value is out of range or string is too long (> 255 bytes)
#define ERR_INVALID_FIELD_NUM -201 // Invalid field number specified
#define ERR_SETFIELD_NOT_CALLED -210 // setField() was not called before writeFields()
#define ERR_CONNECT_FAILED -301 // Failed to connect to ThingSpeak
#define ERR_UNEXPECTED_FAIL -302 // Unexpected failure during write to ThingSpeak
#define ERR_BAD_RESPONSE -303 // Unable to parse response
#define ERR_TIMEOUT -304 // Timeout waiting for server to respond
#define ERR_NOT_INSERTED -401 // Point was not inserted (most probable cause is the rate limit of once every 15 seconds)
// Enables Particle hardware to write or read data to or from ThingSpeak, an open data platform for the Internet of Things with MATLAB analytics and visualization.
class ThingSpeakClass
{
public:
ThingSpeakClass()
{
resetWriteFields();
this->lastReadStatus = OK_SUCCESS;
};
/*
Function: begin
Summary:
Initializes the ThingSpeak library and network settings using the ThingSpeak.com service.
Parameters:
client - TCPClient created earlier in the sketch
Returns:
Always returns true
Notes:
This does not validate the information passed in, or generate any calls to ThingSpeak.
*/
bool begin(Client & client)
{
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::tsBegin", SPARK_PUBLISH_TTL, PRIVATE);
#endif
this->setClient(&client);
this->setPort(THINGSPEAK_PORT_NUMBER);
resetWriteFields();
this->lastReadStatus = OK_SUCCESS;
return true;
};
/*
Function: begin
Summary:
Initializes the ThingSpeak library and network settings using the ThingSpeak.com service.
Parameters:
client - TCPClient created earlier in the sketch
port - TCP port of server
Returns:
Always returns true
Notes:
This does not validate the information passed in, or generate any calls to ThingSpeak.
*/
bool begin(Client & client, unsigned int port)
{
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::tsBegin" , SPARK_PUBLISH_TTL, PRIVATE);
#endif
this->setClient(&client);
this->setPort(port);
resetWriteFields();
this->lastReadStatus = OK_SUCCESS;
return true;
};
/*
Function: writeField
Summary:
Write an integer value to a single field in a ThingSpeak channel
Parameters:
channelNumber - Channel number
field - Field number (1-8) within the channel to write to.
value - Integer value (from -32,768 to 32,767) to write.
writeAPIKey - Write API key associated with the channel. *If you share code with others, do _not_ share this key*
Returns:
HTTP status code of 200 if successful.
Notes:
See getLastReadStatus() for other possible return values.
*/
int writeField(unsigned long channelNumber, unsigned int field, int value, const char * writeAPIKey)
{
// On Spark, int and long are the same, so map to the long version
return writeField(channelNumber, field, (long)value, writeAPIKey);
};
/*
Function: writeField
Summary:
Write a long value to a single field in a ThingSpeak channel
Parameters:
channelNumber - Channel number
field - Field number (1-8) within the channel to write to.
value - Long value (from -2,147,483,648 to 2,147,483,647) to write.
writeAPIKey - Write API key associated with the channel. *If you share code with others, do _not_ share this key*
Returns:
HTTP status code of 200 if successful.
Notes:
See getLastReadStatus() for other possible return values.
*/
int writeField(unsigned long channelNumber, unsigned int field, long value, const char * writeAPIKey)
{
char valueString[15]; // long range is -2147483648 to 2147483647, so 12 bytes including terminator
ltoa(value, valueString, 10);
return writeField(channelNumber, field, valueString, writeAPIKey);
};
/*
Function: writeField
Summary:
Write a floating point value to a single field in a ThingSpeak channel
Parameters:
channelNumber - Channel number
field - Field number (1-8) within the channel to write to.
value - Floating point value (from -999999000000 to 999999000000) to write. If you need more accuracy, or a wider range, you should format the number using <tt>dtostrf</tt> and writeField().
writeAPIKey - Write API key associated with the channel. *If you share code with others, do _not_ share this key*
Returns:
HTTP status code of 200 if successful.
Notes:
See getLastReadStatus() for other possible return values.
*/
int writeField(unsigned long channelNumber, unsigned int field, float value, const char * writeAPIKey)
{
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::writeField (channelNumber: " + String(channelNumber) + " writeAPIKey: " + String(writeAPIKey) + " field: " + String(field) + " value: " + String(value,5) + ")" , SPARK_PUBLISH_TTL, PRIVATE);
#endif
char valueString[20]; // range is -999999000000.00000 to 999999000000.00000, so 19 + 1 for the terminator
int status = convertFloatToChar(value, valueString);
if(status != OK_SUCCESS) return status;
return writeField(channelNumber, field, valueString, writeAPIKey);
};
/*
Function: writeField
Summary:
Write a string to a single field in a ThingSpeak channel
Parameters:
channelNumber - Channel number
field - Field number (1-8) within the channel to write to.
value - String to write (UTF8 string). ThingSpeak limits this field to 255 bytes.
writeAPIKey - Write API key associated with the channel. *If you share code with others, do _not_ share this key*
Returns:
HTTP status code of 200 if successful.
Notes:
See getLastReadStatus() for other possible return values.
*/
int writeField(unsigned long channelNumber, unsigned int field, const char * value, const char * writeAPIKey)
{
return writeField(channelNumber, field, String(value), writeAPIKey);
};
/*
Function: writeField
Summary:
Write a string to a single field in a ThingSpeak channel
Parameters:
channelNumber - Channel number
field - Field number (1-8) within the channel to write to.
value - String to write (UTF8 string). ThingSpeak limits this field to 255 bytes.
writeAPIKey - Write API key associated with the channel. *If you share code with others, do _not_ share this key*
Returns:
HTTP status code of 200 if successful.
Notes:
See getLastReadStatus() for other possible return values.
*/
int writeField(unsigned long channelNumber, unsigned int field, String value, const char * writeAPIKey)
{
// Invalid field number specified
if(field < FIELDNUM_MIN || field > FIELDNUM_MAX) return ERR_INVALID_FIELD_NUM;
// Max # bytes for ThingSpeak field is 255
if(value.length() > FIELDLENGTH_MAX) return ERR_OUT_OF_RANGE;
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "writeField (" + String(channelNumber) + ", " + String(writeAPIKey) + ", " + String(field) + ", " + escapeUrl(value) + ")", SPARK_PUBLISH_TTL, PRIVATE);
#endif
String postMessage = String("field") + String(field) + "=" + escapeUrl(value);
return writeRaw(channelNumber, postMessage, writeAPIKey);
};
/*
Function: setField
Summary:
Set the value of a single field that will be part of a multi-field update.
Parameters:
field - Field number (1-8) within the channel to set.
value - Integer value (from -32,768 to 32,767) to set.
Returns:
Code of 200 if successful.
Code of -101 if value is out of range or string is too long (> 255 bytes)
*/
int setField(unsigned int field, int value)
{
// On Spark, int and long are the same, so map to the long version
return setField(field, (long)value);
};
/*
Function: setField
Summary:
Set the value of a single field that will be part of a multi-field update.
Parameters:
field - Field number (1-8) within the channel to set.
value - Long value (from -2,147,483,648 to 2,147,483,647) to write.
Returns:
Code of 200 if successful.
Code of -101 if value is out of range or string is too long (> 255 bytes)
*/
int setField(unsigned int field, long value)
{
char valueString[15]; // long range is -2147483648 to 2147483647, so 12 bytes including terminator
ltoa(value, valueString, 10);
return setField(field, valueString);
};
/*
Function: setField
Summary:
Set the value of a single field that will be part of a multi-field update.
Parameters:
field - Field number (1-8) within the channel to set.
value - Floating point value (from -999999000000 to 999999000000) to write. If you need more accuracy, or a wider range, you should format the number yourself (using <tt>dtostrf</tt>) and setField() using the resulting string.
Returns:
Code of 200 if successful.
Code of -101 if value is out of range or string is too long (> 255 bytes)
*/
int setField(unsigned int field, float value)
{
char valueString[20]; // range is -999999000000.00000 to 999999000000.00000, so 19 + 1 for the terminator
int status = convertFloatToChar(value, valueString);
if(status != OK_SUCCESS) return status;
return setField(field, valueString);
};
/*
Function: setField
Summary:
Set the value of a single field that will be part of a multi-field update.
Parameters:
field - Field number (1-8) within the channel to set.
value - String to write (UTF8). ThingSpeak limits this to 255 bytes.
Returns:
Code of 200 if successful.
Code 0f -101 if value is out of range or string is too long (> 255 bytes)
*/
int setField(unsigned int field, const char * value)
{
return setField(field, String(value));
};
/*
Function: setField
Summary:
Set the value of a single field that will be part of a multi-field update.
Parameters:
field - Field number (1-8) within the channel to set.
value - String to write (UTF8). ThingSpeak limits this to 255 bytes.
Returns:
Code of 200 if successful.
Code of -101 if value is out of range or string is too long (> 255 bytes)
*/
int setField(unsigned int field, String value)
{
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "setField " + String(field) + " to " + String(value), SPARK_PUBLISH_TTL, PRIVATE);
#endif
if(field < FIELDNUM_MIN || field > FIELDNUM_MAX) return ERR_INVALID_FIELD_NUM;
// Max # bytes for ThingSpeak field is 255 (UTF-8)
if(value.length() > FIELDLENGTH_MAX) return ERR_OUT_OF_RANGE;
this->nextWriteField[field - 1] = value;
return OK_SUCCESS;
};
/*
Function: setLatitude
Summary:
Set the latitude of a multi-field update.
Parameters:
latitude - Latitude of the measurement as a floating point value (degrees N, use negative values for degrees S)
Returns:
Always return 200
Notes:
To record latitude, longitude and elevation of a write, call setField() for each of the fields you want to write. Then setLatitude(), setLongitude(), setElevation() and then call writeFields()
*/
int setLatitude(float latitude)
{
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::setLatitude(latitude: " + String(latitude,3) + "\")" , SPARK_PUBLISH_TTL, PRIVATE);
#endif
this->nextWriteLatitude = latitude;
return OK_SUCCESS;
};
/*
Function: setLongitude
Summary:
Set the longitude of a multi-field update.
Parameters:
longitude - Longitude of the measurement as a floating point value (degrees E, use negative values for degrees W)
Returns:
Always return 200
Notes:
To record latitude, longitude and elevation of a write, call setField() for each of the fields you want to write. Then setLatitude(), setLongitude(), setElevation() and then call writeFields()
*/
int setLongitude(float longitude)
{
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::setLongitude(longitude: " + String(longitude,3) + "\")" , SPARK_PUBLISH_TTL, PRIVATE);
#endif
this->nextWriteLongitude = longitude;
return OK_SUCCESS;
};
/*
Function: setElevation
Summary:
Set the elevation of a multi-field update.
Parameters:
elevation - Elevation of the measurement as a floating point value (meters above sea level)
Returns:
Always return 200
Notes:
To record latitude, longitude and elevation of a write, call setField() for each of the fields you want to write. Then setLatitude(), setLongitude(), setElevation() and then call writeFields()
*/
int setElevation(float elevation)
{
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::setElevation(elevation: " + String(elevation,3) + "\")" , SPARK_PUBLISH_TTL, PRIVATE);
#endif
this->nextWriteElevation = elevation;
return OK_SUCCESS;
};
/*
Function: setStatus
Summary:
Set the status field of a multi-field update.
Parameters:
status - String to write (UTF8). ThingSpeak limits this to 255 bytes.
Returns:
Code of 200 if successful.
Code of -101 if string is too long (> 255 bytes)
Notes:
To record a status message on a write, call setStatus() then call writeFields().
Use status to provide additonal details when writing a channel update.
Additonally, status can be used by the ThingTweet App to send a message to Twitter.
*/
int setStatus(const char * status)
{
return setStatus(String(status));
};
/*
Function: setStatus
Summary:
Set the status field of a multi-field update.
Parameters:
status - String to write (UTF8). ThingSpeak limits this to 255 bytes.
Returns:
Code of 200 if successful.
Code of -101 if string is too long (> 255 bytes)
Notes:
To record a status message on a write, call setStatus() then call writeFields().
Use status to provide additonal details when writing a channel update.
Additonally, status can be used by the ThingTweet App to send a message to Twitter.
*/
int setStatus(String status)
{
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::setStatus(status: " + status + "\")" , SPARK_PUBLISH_TTL, PRIVATE);
#endif
// Max # bytes for ThingSpeak field is 255 (UTF-8)
if(status.length() > FIELDLENGTH_MAX) return ERR_OUT_OF_RANGE;
this->nextWriteStatus = status;
return OK_SUCCESS;
};
/*
Function: setTwitterTweet
Summary:
Set the Twitter account and message to use for an update to be tweeted.
Parameters:
twitter - Twitter account name as a String.
tweet - Twitter message as a String (UTF-8) limited to 140 character.
Returns:
Code of 200 if successful.
Code of -101 if string is too long (> 255 bytes)
Notes:
To send a message to twitter call setTwitterTweet() then call writeFields().
Prior to using this feature, a twitter account must be linked to your ThingSpeak account. Do this by logging into ThingSpeak and going to Apps, then ThingTweet and clicking Link Twitter Account.
*/
int setTwitterTweet(const char * twitter, const char * tweet)
{
return setTwitterTweet(String(twitter), String(tweet));
};
/*
Function: setTwitterTweet
Summary:
Set the Twitter account and message to use for an update to be tweeted.
Parameters:
twitter - Twitter account name as a String.
tweet - Twitter message as a String (UTF-8) limited to 140 character.
Returns:
Code of 200 if successful.
Code of -101 if string is too long (> 255 bytes)
Notes:
To send a message to twitter call setTwitterTweet() then call writeFields().
Prior to using this feature, a twitter account must be linked to your ThingSpeak account. Do this by logging into ThingSpeak and going to Apps, then ThingTweet and clicking Link Twitter Account.
*/
int setTwitterTweet(String twitter, const char * tweet)
{
return setTwitterTweet(twitter, String(tweet));
};
/*
Function: setTwitterTweet
Summary:
Set the Twitter account and message to use for an update to be tweeted.
Parameters:
twitter - Twitter account name as a String.
tweet - Twitter message as a String (UTF-8) limited to 140 character.
Returns:
Code of 200 if successful.
Code of -101 if string is too long (> 255 bytes)
Notes:
To send a message to twitter call setTwitterTweet() then call writeFields().
Prior to using this feature, a twitter account must be linked to your ThingSpeak account. Do this by logging into ThingSpeak and going to Apps, then ThingTweet and clicking Link Twitter Account.
*/
int setTwitterTweet(const char * twitter, String tweet)
{
return setTwitterTweet(String(twitter), tweet);
};
/*
Function: setTwitterTweet
Summary:
Set the Twitter account and message to use for an update to be tweeted.
Parameters:
twitter - Twitter account name as a String.
tweet - Twitter message as a String (UTF-8) limited to 140 character.
Returns:
Code of 200 if successful.
Code of -101 if string is too long (> 255 bytes)
Notes:
To send a message to twitter call setTwitterTweet() then call writeFields().
Prior to using this feature, a twitter account must be linked to your ThingSpeak account. Do this by logging into ThingSpeak and going to Apps, then ThingTweet and clicking Link Twitter Account.
*/
int setTwitterTweet(String twitter, String tweet){
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::setTwitter(twitter: " + twitter + ", tweet: " + tweet + ")" , SPARK_PUBLISH_TTL, PRIVATE);
#endif
// Max # bytes for ThingSpeak field is 255 (UTF-8)
if((twitter.length() > FIELDLENGTH_MAX) || (tweet.length() > FIELDLENGTH_MAX)) return ERR_OUT_OF_RANGE;
this->nextWriteTwitter = twitter;
this->nextWriteTweet = tweet;
return OK_SUCCESS;
};
/*
Function: setCreatedAt
Summary:
Set the created-at date of a multi-field update.
Parameters:
createdAt - Desired timestamp to be included with the channel update as a String. The timestamp string must be in the ISO 8601 format. Example "2017-01-12 13:22:54"
Returns:
Code of 200 if successful.
Code of -101 if string is too long (> 255 bytes)
Notes:
Timezones can be set using the timezone hour offset parameter. For example, a timestamp for Eastern Standard Time is: "2017-01-12 13:22:54-05".
If no timezone hour offset parameter is used, UTC time is assumed.
*/
int setCreatedAt(const char * createdAt)
{
return setCreatedAt(String(createdAt));
}
/*
Function: setCreatedAt
Summary:
Set the created-at date of a multi-field update.
Parameters:
createdAt - Desired timestamp to be included with the channel update as a String. The timestamp string must be in the ISO 8601 format. Example "2017-01-12 13:22:54"
Returns:
Code of 200 if successful.
Code of -101 if string is too long (> 255 bytes)
Notes:
Timezones can be set using the timezone hour offset parameter. For example, a timestamp for Eastern Standard Time is: "2017-01-12 13:22:54-05".
If no timezone hour offset parameter is used, UTC time is assumed.
*/
int setCreatedAt(String createdAt)
{
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::setCreatedAt(createdAt: " + createdAt + "\")" , SPARK_PUBLISH_TTL, PRIVATE);
#endif
// the ISO 8601 format is too complicated to check for valid timestamps here
// we'll need to reply on the api to tell us if there is a problem
// Max # bytes for ThingSpeak field is 255 (UTF-8)
if(createdAt.length() > FIELDLENGTH_MAX) return ERR_OUT_OF_RANGE;
this->nextWriteCreatedAt = createdAt;
return OK_SUCCESS;
}
/*
Function: writeFields
Summary:
Write a multi-field update.
Parameters:
channelNumber - Channel number
writeAPIKey - Write API key associated with the channel. *If you share code with others, do _not_ share this key*
Returns:
200 - successful.
404 - Incorrect API key (or invalid ThingSpeak server address)
-101 - Value is out of range or string is too long (> 255 characters)
-201 - Invalid field number specified
-210 - setField() was not called before writeFields()
-301 - Failed to connect to ThingSpeak
-302 - Unexpected failure during write to ThingSpeak
-303 - Unable to parse response
-304 - Timeout waiting for server to respond
-401 - Point was not inserted (most probable cause is the rate limit of once every 15 seconds)
Notes:
Call setField(), setLatitude(), setLongitude(), setElevation() and/or setStatus() and then call writeFields()
*/
int writeFields(unsigned long channelNumber, const char * writeAPIKey)
{
String postMessage = String("");
bool fFirstItem = true;
for(size_t iField = 0; iField < 8; iField++)
{
if(this->nextWriteField[iField].length() > 0)
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("field") + String(iField + 1) + String("=") + escapeUrl(this->nextWriteField[iField]);
fFirstItem = false;
this->nextWriteField[iField] = "";
}
}
if(!isnan(nextWriteLatitude))
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("lat=") + String(this->nextWriteLatitude);
fFirstItem = false;
this->nextWriteLatitude = NAN;
}
if(!isnan(this->nextWriteLongitude))
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("long=") + String(this->nextWriteLongitude);
fFirstItem = false;
this->nextWriteLongitude = NAN;
}
if(!isnan(this->nextWriteElevation))
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("elevation=") + String(this->nextWriteElevation);
fFirstItem = false;
this->nextWriteElevation = NAN;
}
if(this->nextWriteStatus.length() > 0)
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("status=") + escapeUrl(this->nextWriteStatus);
fFirstItem = false;
this->nextWriteStatus = "";
}
if(this->nextWriteTwitter.length() > 0)
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("twitter=") + escapeUrl(this->nextWriteTwitter);
fFirstItem = false;
this->nextWriteTwitter = "";
}
if(this->nextWriteTweet.length() > 0)
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("tweet=") + escapeUrl(this->nextWriteTweet);
fFirstItem = false;
this->nextWriteTweet = "";
}
if(this->nextWriteCreatedAt.length() > 0)
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("created_at=") + String(this->nextWriteCreatedAt);
fFirstItem = false;
this->nextWriteCreatedAt = "";
}
if(fFirstItem)
{
// setField was not called before writeFields
return ERR_SETFIELD_NOT_CALLED;
}
return writeRaw(channelNumber, postMessage, writeAPIKey);
};
/*
Function: writeRaw
Summary:
Write a raw POST to a ThingSpeak channel
Parameters:
channelNumber - Channel number
postMessage - Raw URL to write to ThingSpeak as a string. See the documentation at https://thingspeak.com/docs/channels#update_feed.
writeAPIKey - Write API key associated with the channel. *If you share code with others, do _not_ share this key*
Returns:
200 - successful.
404 - Incorrect API key (or invalid ThingSpeak server address)
-101 - Value is out of range or string is too long (> 255 characters)
-201 - Invalid field number specified
-210 - setField() was not called before writeFields()
-301 - Failed to connect to ThingSpeak
-302 - Unexpected failure during write to ThingSpeak
-303 - Unable to parse response
-304 - Timeout waiting for server to respond
-401 - Point was not inserted (most probable cause is the rate limit of once every 15 seconds)
Notes:
This is low level functionality that will not be required by most users.
*/
int writeRaw(unsigned long channelNumber, const char * postMessage, const char * writeAPIKey)
{
return writeRaw(channelNumber, String(postMessage), writeAPIKey);
};
/*
Function: writeRaw
Summary:
Write a raw POST to a ThingSpeak channel
Parameters:
channelNumber - Channel number
postMessage - Raw URL to write to ThingSpeak as a string. See the documentation at https://thingspeak.com/docs/channels#update_feed.
writeAPIKey - Write API key associated with the channel. *If you share code with others, do _not_ share this key*
Returns:
200 - successful.
404 - Incorrect API key (or invalid ThingSpeak server address)
-101 - Value is out of range or string is too long (> 255 characters)
-201 - Invalid field number specified
-210 - setField() was not called before writeFields()
-301 - Failed to connect to ThingSpeak
-302 - Unexpected failure during write to ThingSpeak
-303 - Unable to parse response
-304 - Timeout waiting for server to respond
-401 - Point was not inserted (most probable cause is the rate limit of once every 15 seconds)
Notes:
This is low level functionality that will not be required by most users.
*/
int writeRaw(unsigned long channelNumber, String postMessage, const char * writeAPIKey)
{
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::writeRaw (channelNumber: " + String(channelNumber) + " writeAPIKey: " + String(writeAPIKey) + " postMessage: \"" + postMessage + "\")" , SPARK_PUBLISH_TTL, PRIVATE);
#endif
if(!connectThingSpeak())
{
// Failed to connect to ThingSpeak
return ERR_CONNECT_FAILED;
}
postMessage = postMessage + String("&headers=false");
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "Post " + postMessage, SPARK_PUBLISH_TTL, PRIVATE);
#endif
// Post data to thingspeak
if(!this->client->print("POST /update HTTP/1.1\r\n")) return abortWriteRaw();
if(!writeHTTPHeader(writeAPIKey)) return abortWriteRaw();
if(!this->client->print("Content-Type: application/x-www-form-urlencoded\r\n")) return abortWriteRaw();
if(!this->client->print("Content-Length: ")) return abortWriteRaw();
if(!this->client->print(postMessage.length())) return abortWriteRaw();
if(!this->client->print("\r\n\r\n")) return abortWriteRaw();
if(!this->client->print(postMessage)) return abortWriteRaw();
String entryIDText = String();
int status = getHTTPResponse(entryIDText);
if(status != OK_SUCCESS)
{
client->stop();
return status;
}
long entryID = entryIDText.toInt();
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, " Entry ID \"" + entryIDText + "\" (" + String(entryID) + ")" , SPARK_PUBLISH_TTL, PRIVATE);
#endif
client->stop();
#ifdef PRINT_DEBUG_MESSAGES
Particle.publish(SPARK_PUBLISH_TOPIC, "disconnected.", SPARK_PUBLISH_TTL, PRIVATE);
#endif
if(entryID == 0)
{
// ThingSpeak did not accept the write
status = ERR_NOT_INSERTED;
}
return status;
};
/*
Function: readStringField
Summary:
Read the latest string from a private ThingSpeak channel
Parameters:
channelNumber - Channel number
field - Field number (1-8) within the channel to read from.
readAPIKey - Read API key associated with the channel. *If you share code with others, do _not_ share this key*
Returns:
Value read (UTF8 string), or empty string if there is an error. Use getLastReadStatus() to get more specific information.
*/
String readStringField(unsigned long channelNumber, unsigned int field, const char * readAPIKey)
{
if(field < FIELDNUM_MIN || field > FIELDNUM_MAX)
{
this->lastReadStatus = ERR_INVALID_FIELD_NUM;
return("");
}
#ifdef PRINT_DEBUG_MESSAGES
if(NULL != readAPIKey)
{
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::readStringField(channelNumber: " + String(channelNumber) + " readAPIKey: " + String(readAPIKey) + " field: " + String(field) +")", SPARK_PUBLISH_TTL, PRIVATE);
}
else{
Particle.publish(SPARK_PUBLISH_TOPIC, "ts::readStringField(channelNumber: " + String(channelNumber) + " field: " + String(field) + ")", SPARK_PUBLISH_TTL, PRIVATE);
}
#endif
return readRaw(channelNumber, String(String("/fields/") + String(field) + String("/last")), readAPIKey);
}
/*
Function: readStringField
Summary:
Read the latest string from a private ThingSpeak channel
Parameters:
channelNumber - Channel number
field - Field number (1-8) within the channel to read from.
Returns:
Value read (UTF8 string), or empty string if there is an error. Use getLastReadStatus() to get more specific information.
*/