-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
1787 lines (1503 loc) · 49.8 KB
/
main.cpp
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
/* mbed Microcontroller Library
* Copyright (c) 2018 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ****************************************************************************
// Workplace Environmental Monitor
//
// This is a reference deployment application utilizing mbed cloud 1.2.
//
// By the ARM Reference Design Team
// ****************************************************************************
#include <mbed.h>
#include "compat.h"
#include "commander.h"
#include "displayman.h"
#include "fs.h"
#include "keystore.h"
#include "lcdprogress.h"
#include "m2mclient.h"
#include "rapidjson/allocators.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <algorithm> /* std::min */
#include <errno.h>
#include <factory_configurator_client.h>
#include <fcc_defs.h>
#include <mbed_stats.h>
#include <mbedtls/sha256.h>
#include <mbed-trace-helper.h>
#include <mbed-trace/mbed_trace.h>
#include <OdinWiFiInterface.h>
#include "TSL2591.h"
#include "Sht31/Sht31.h"
#define TRACE_GROUP "main"
// Convert the value of a C macro to a string that can be printed. This trick
// is straight out of the GNU C documentation.
// (https://gcc.gnu.org/onlinedocs/gcc-4.9.0/cpp/Stringification.html)
#define xstr(s) str(s)
#define str(s) #s
#ifndef DEVTAG
#error "No dev tag created"
#endif
namespace json = rapidjson;
// ****************************************************************************
// DEFINEs and type definitions
// ****************************************************************************
#ifndef MBED_CONF_APP_FACTORY_RESET_BUTTON_PRESS_SECS
#define MBED_CONF_APP_FACTORY_RESET_BUTTON_PRESS_SECS 5
#endif
#define MACADDR_STRLEN 18
#define SSID_KEY "wifi.ssid"
#define PASSWORD_KEY "wifi.key"
#define SECURITY_KEY "wifi.encryption"
#define APP_LABEL_KEY "app.label"
#define APP_LABEL_SENSOR_NAME "Label"
#ifndef MBED_CONF_APP_APP_LABEL
#define MBED_CONF_APP_APP_LABEL "dragonfly"
#endif
#define GEO_LAT_KEY "geo.lat"
#define GEO_LONG_KEY "geo.long"
#define GEO_ACCURACY_KEY "geo.accuracy"
#ifndef MBED_CONF_APP_MAX_REPORTED_APS
#define MBED_CONF_APP_MAX_REPORTED_APS 8
#endif
#define JSON_MEM_POOL_INC 64
#define WEM_VERBOSE_PRINTF(type, fmt, ...) \
do {\
if (wem_ ##type ## _verbose_enabled) {\
cmd.printf(fmt, __VA_ARGS__); \
}\
} while(0)
enum WEM_THREADS {
WEM_THREAD_DISPLAY = 0,
WEM_THREAD_SENSOR_LIGHT,
WEM_THREAD_DHT,
WEM_THREAD_COUNT
};
struct dht_sensor {
uint8_t h_id;
uint8_t t_id;
Sht31 *sensor;
M2MResource *h_res;
M2MResource *t_res;
};
struct light_sensor {
uint8_t id;
TSL2591 *sensor;
M2MResource *res;
};
struct sensors {
int event_queue_id_light, event_queue_id_dht;
struct dht_sensor dht;
struct light_sensor light;
};
// ****************************************************************************
// Globals
// ****************************************************************************
static DisplayMan display;
static M2MClient *m2mclient;
static NetworkInterface *net;
static EventQueue evq;
static struct sensors sensors;
/* used to stop auto display refresh during firmware downloads */
static int display_evq_id;
static bool wem_sensors_verbose_enabled = false;
static I2C i2c(I2C_SDA, I2C_SCL);
static TSL2591 tsl2591(i2c, TSL2591_ADDR);
static Sht31 sht31(I2C_SDA, I2C_SCL);
//our serial interface cli class
Commander cmd;
// ****************************************************************************
// Generic Helpers
// ****************************************************************************
/**
* Processes an event queue callback for updating the display
*/
static void display_refresh(DisplayMan *display)
{
display->refresh();
}
/**
* Sets the app label on the LCD and Mbed Client
*/
static void set_app_label(M2MClient *m2m, const char *label)
{
display.set_sensor_status(APP_LABEL_SENSOR_NAME, label);
m2m->set_resource_value(M2MClient::M2MClientResourceAppLabel, label);
}
// ****************************************************************************
// Sensors
// ****************************************************************************
/**
* Inits the light sensor object
*/
static void light_init(struct light_sensor *s, M2MClient *mbed_client)
{
/* add to the display */
s->id = display.register_sensor("Light", IND_LIGHT);
/* init the driver */
s->sensor = &tsl2591;
s->sensor->init();
s->sensor->enable();
s->res = m2mclient->get_resource(M2MClient::M2MClientResourceLightValue);
m2mclient->set_resource_value(s->res, "0", 1);
}
/**
* Converts light sensor reading to Lux units
*
* Empirical measurement against a light meter under 17
* different lighting conditions led to the following
* conversion table
* Reading Lux
* 0.128 392
* 0.211 767
* 0.264 1145
* 0.292 1294
* 0.317 1407
* 0.349 1665
* 0.402 1959
* 0.457 2580
* 0.517 2690
* 0.570 3540
* 0.592 3770
* 0.628 4310
* 0.702 5040
* 0.816 5880
* 0.856 6150
* 0.917 7610
* 0.958 8330
*
* This data is best fit by the power equation
* Lux = 8251*(reading)^1.5108
* This equation fits with an R^2 value of 0.9962
*/
unsigned int light_sensor_to_lux(float reading) {
return lroundf(8250.0 * pow(reading, 1.51));
}
/**
* Reads a value from the light sensor and publishes to the display
*/
static void light_read(struct light_sensor *s)
{
size_t size;
char res_buffer[33] = {0};
unsigned int lux;
s->sensor->getALS();
s->sensor->calcLux();
//light sensor uses a multiplier to adjust for the lightpipe
lux = s->sensor->lux*3.7;
WEM_VERBOSE_PRINTF(sensors, "light: %u\n", lux);
size = snprintf(res_buffer, sizeof(res_buffer), "%u lux", lux);
display.set_sensor_status(s->id, res_buffer);
m2mclient->set_resource_value(s->res, res_buffer, size);
}
/**
* Inits the temp/humidity combo sensor
*/
static void dht_init(struct dht_sensor *s, M2MClient *mbed_client)
{
/* add to the display */
s->t_id = display.register_sensor("Temp", IND_TEMP);
s->h_id = display.register_sensor("Humidity", IND_HUMIDITY);
/* init the driver */
s->sensor = &sht31;
s->t_res = mbed_client->get_resource(
M2MClient::M2MClientResourceTempValue);
s->h_res = mbed_client->get_resource(
M2MClient::M2MClientResourceHumidityValue);
/* set default values */
display.set_sensor_status(s->t_id, "0");
mbed_client->set_resource_value(s->t_res, "0", 1);
display.set_sensor_status(s->h_id, "0");
mbed_client->set_resource_value(s->h_res, "0", 1);
}
/**
* Reads temp and humidity values publishes to the display
*/
static void dht_read(struct dht_sensor *dht)
{
int size = 0;
float temperature, humidity;
char res_buffer[33] = {0};
//temp and humidity have multiplier to adjust for the case
temperature = dht->sensor->readTemperature() * .68;
humidity = dht->sensor->readHumidity() * 1.9;
tr_debug("DHT: temp = %fC, humi = %f%%\n", temperature, humidity);
/* verbose printing to screen of sensor values */
WEM_VERBOSE_PRINTF(sensors, "DHT: temp = %.2fC, humidity = %.2f%%\n", temperature, humidity);
size = snprintf(res_buffer, sizeof(res_buffer), "%.1f C", temperature);
m2mclient->set_resource_value(dht->t_res, res_buffer, size);
display.set_sensor_status(dht->t_id, (char *)res_buffer);
size = snprintf(res_buffer, sizeof(res_buffer), "%.0f%%", humidity);
m2mclient->set_resource_value(dht->h_res, res_buffer, size);
display.set_sensor_status(dht->h_id, (char *)res_buffer);
}
/**
* Inits all sensors, making them ready to read
*/
static void sensors_init(struct sensors *sensors, M2MClient *mbed_client)
{
dht_init(&sensors->dht, mbed_client);
light_init(&sensors->light, mbed_client);
}
/**
* Starts the periodic sampling of sensor data
*/
static void sensors_start(struct sensors *s, EventQueue *q)
{
cmd.printf("starting all sensors\n");
// the periods are prime number multiples so that the LED flashing is more appealing
s->event_queue_id_light = q->call_every(4700, light_read, &s->light);
s->event_queue_id_dht = q->call_every(5300, dht_read, &s->dht);
}
/**
* Stops the periodic sampling of sensor data
*/
static void sensors_stop(struct sensors *s, EventQueue *q)
{
cmd.printf("stopping all sensors\n");
q->cancel(s->event_queue_id_light);
q->cancel(s->event_queue_id_dht);
s->event_queue_id_light = 0;
s->event_queue_id_dht = 0;
}
// ****************************************************************************
// Network
// ****************************************************************************
static void network_disconnect(NetworkInterface *net)
{
net->disconnect();
}
static char *network_get_macaddr(NetworkInterface *net, char *macstr)
{
memcpy(macstr, net->get_mac_address(), MACADDR_STRLEN);
return macstr;
}
static nsapi_security_t wifi_security_str2sec(const char *security)
{
if (0 == strcmp("WPA/WPA2", security)) {
return NSAPI_SECURITY_WPA_WPA2;
} else if (0 == strcmp("WPA2", security)) {
return NSAPI_SECURITY_WPA_WPA2;
} else if (0 == strcmp("WPA", security)) {
return NSAPI_SECURITY_WPA;
} else if (0 == strcmp("WEP", security)) {
return NSAPI_SECURITY_WEP;
} else if (0 == strcmp("NONE", security)) {
return NSAPI_SECURITY_NONE;
} else if (0 == strcmp("OPEN", security)) {
return NSAPI_SECURITY_NONE;
}
cmd.printf("warning: unknown wifi security type (%s), assuming NONE\n",
security);
return NSAPI_SECURITY_NONE;
}
/**
* brings up wifi
* */
static WiFiInterface *new_wifi_interface()
{
return new OdinWiFiInterface();
}
static WiFiInterface *network_create(void)
{
Keystore k;
string ssid;
ssid = MBED_CONF_APP_WIFI_SSID;
k.open();
if (k.exists("wifi.ssid")) {
ssid = k.get("wifi.ssid");
}
k.close();
display.init_network("WiFi");
display.set_network_status(ssid);
return new_wifi_interface();
}
/** Scans the wireless network for nearby APs.
*
* @param net The network interface to scan on.
* @param mbed_client The mBed Client cloud interface for uploading data.
* @return Returns the number of nearby APs on success,
* -errno for failure.
*/
static int network_scan(NetworkInterface *net, M2MClient *mbed_client)
{
int reported;
int available;
WiFiAccessPoint *ap;
WiFiInterface *wifi = (WiFiInterface *)net;
/* scan for a list of available APs */
available = wifi->scan(NULL, 0);
/* cap the number of APs reported */
reported = min(available, MBED_CONF_APP_MAX_REPORTED_APS);
/* allocate and scan again */
ap = new WiFiAccessPoint[reported];
reported = wifi->scan(ap, reported);
cmd.printf("Found %d devices, reporting info on %d (max=%d)\n",
available, reported, MBED_CONF_APP_MAX_REPORTED_APS);
/* setup the json document and custom allocator */
json::MemoryPoolAllocator<json::CrtAllocator> allocator(JSON_MEM_POOL_INC);
json::Document doc(&allocator);
doc.SetArray();
/* create a json record for each AP which contains a
* macAddress and signalStrength key.
*/
for (int idx = 0; idx < reported; ++idx)
{
char macaddr[MACADDR_STRLEN] = {0};
snprintf(macaddr, sizeof(macaddr), "%02X:%02X:%02X:%02X:%02X:%02X",
ap[idx].get_bssid()[0], ap[idx].get_bssid()[1], ap[idx].get_bssid()[2],
ap[idx].get_bssid()[3], ap[idx].get_bssid()[4], ap[idx].get_bssid()[5]);
/* not the prettiest thing in the world, but it avoids having to create
* a number of variables to hold some these values.
* The first argument is a JSON object to be pushed back: this object has
* two members, the first of which is the macAddress key-value pair; the
* second member is the signalStrength key-value pair.
* Both the PushBack and AddMember calls require allocators which are
* retrieved from the JSON doc.
*/
doc.PushBack(
json::Value(json::kObjectType).
AddMember(
"macAddress",
json::Value().SetString(
macaddr,
strlen(macaddr),
doc.GetAllocator()),
doc.GetAllocator()).
AddMember(
"signalStrength",
ap[idx].get_rssi(),
doc.GetAllocator()
),
doc.GetAllocator()
);
}
/* We need a StringBuffer and Writer to generate the JSON output that will be sent */
json::StringBuffer buf;
json::Writer<json::StringBuffer> writer(buf);
doc.Accept(writer);
#if MBED_CONF_APP_WIFI_DEBUG
cmd.printf("%s\n", buf.GetString());
#endif
/* update the M2MClient resource for network data and send it as a JSON array */
M2MResource *res = mbed_client->get_resource(
M2MClient::M2MClientResourceNetwork);
m2mclient->set_resource_value(res, buf.GetString(), buf.GetLength());
/* cleanup */
delete []ap;
return reported;
}
static int network_connect(NetworkInterface *net)
{
int ret;
char macaddr[MACADDR_STRLEN];
WiFiInterface *wifi;
/* code is compiled -fno-rtti so we have to use C cast */
wifi = (WiFiInterface *)net;
//wifi login info set to default values
string ssid = MBED_CONF_APP_WIFI_SSID;
string pass = MBED_CONF_APP_WIFI_PASSWORD;
string security = MBED_CONF_APP_WIFI_SECURITY;
//keystore db access
Keystore k;
//read the current state
k.open();
//use the keystore for ssid?
if (k.exists(SSID_KEY)) {
cmd.printf("Using %s from keystore\n", SSID_KEY);
ssid = k.get(SSID_KEY);
} else {
cmd.printf("Using default %s\n", SSID_KEY);
}
//use the keystore for pass?
if (k.exists(PASSWORD_KEY)) {
cmd.printf("Using %s from keystore\n", PASSWORD_KEY);
pass = k.get(PASSWORD_KEY);
} else {
cmd.printf("Using default %s\n", PASSWORD_KEY);
}
//use the keystor for security?
if (k.exists(SECURITY_KEY)) {
cmd.printf("Using %s from keystore\n", SECURITY_KEY);
security = k.get(SECURITY_KEY);
} else {
cmd.printf("Using default %s\n", SECURITY_KEY);
}
display.set_network_status(ssid);
cmd.printf("[WIFI] connecting: mac=%s, ssid=%s, encryption=%s\n",
network_get_macaddr(wifi, macaddr),
ssid.c_str(),
security.c_str());
ret = wifi->connect(ssid.c_str(),
pass.c_str(),
wifi_security_str2sec(security.c_str()));
if (0 != ret) {
cmd.printf("[WIFI] Failed to connect to: %s (%d)\n",
ssid.c_str(), ret);
return ret;
}
cmd.printf("[WIFI] connected: mac=%s, ssid=%s, ip=%s, netmask=%s, gateway=%s\n",
network_get_macaddr(net, macaddr),
ssid.c_str(),
net->get_ip_address(),
net->get_netmask(),
net->get_gateway());
return 0;
}
/**
* Continually attempt network connection until successful
*/
static void sync_network_connect(NetworkInterface *net)
{
int ret;
do {
display.set_network_connecting();
ret = network_connect(net);
if (0 != ret) {
display.set_network_fail();
cmd.printf("WARN: failed to init network, retrying...\n");
Thread::wait(2000);
}
} while (0 != ret);
}
// ****************************************************************************
// Cloud
// ****************************************************************************
static void mbed_client_keep_alive(M2MClient *m2m)
{
if (m2m->is_client_registered()) {
m2m->keep_alive();
}
}
/**
* Handles a M2M PUT request on the app label resource
*/
static void mbed_client_handle_put_app_label(M2MClient *m2m)
{
Keystore k;
std::string label;
label = m2m->get_resource_value_str(M2MClient::M2MClientResourceAppLabel);
if (label.length() == 0) {
return;
}
k.open();
k.set(APP_LABEL_KEY, label);
k.write();
k.close();
set_app_label(m2m, label.c_str());
}
/**
* Handles a M2M PUT request on Geo Latitude
*/
static void
mbed_client_handle_put_geo_lat(M2MClient *m2m)
{
Keystore k;
std::string val;
val = m2m->get_resource_value_str(M2MClient::M2MClientResourceGeoLat);
if (val.length() == 0) {
return;
}
k.open();
/* special case '-' means delete */
if (val.length() == 1 && val[0] == '-') {
k.del(GEO_LAT_KEY);
} else {
k.set(GEO_LAT_KEY, val);
}
k.write();
k.close();
}
/**
* Handles a M2M PUT request on Geo Longitude
*/
static void
mbed_client_handle_put_geo_long(M2MClient *m2m)
{
Keystore k;
std::string val;
val = m2m->get_resource_value_str(M2MClient::M2MClientResourceGeoLong);
if (val.length() == 0) {
return;
}
k.open();
/* special case '-' means delete */
if (val.length() == 1 && val[0] == '-') {
k.del(GEO_LONG_KEY);
} else {
k.set(GEO_LONG_KEY, val);
}
k.write();
k.close();
}
/**
* Handles a M2M PUT request on Geo Accuracy
*/
static void
mbed_client_handle_put_geo_accuracy(M2MClient *m2m)
{
Keystore k;
std::string val;
val = m2m->get_resource_value_str(M2MClient::M2MClientResourceGeoAccuracy);
if (val.length() == 0) {
return;
}
k.open();
/* special case '-' means delete */
if (val.length() == 1 && val[0] == '-') {
k.del(GEO_ACCURACY_KEY);
} else {
k.set(GEO_ACCURACY_KEY, val);
}
k.write();
k.close();
}
/**
* Readies the app for a firmware download
*/
void fota_auth_download(M2MClient *mbed_client)
{
cmd.printf("Firmware download requested\n");
sensors_stop(&sensors, &evq);
/* we'll need to manually refresh the display until the firmware
* update is complete. it seems that doing *anything* outside of
* the firmware download's thread context will result in a failed
* download. */
evq.cancel(display_evq_id);
display_evq_id = 0;
display.set_downloading();
display.refresh();
mbed_client->update_authorize(MbedCloudClient::UpdateRequestDownload);
cmd.printf("Authorization granted\n");
}
/**
* Readies the app for a firmware install
*/
void fota_auth_install(M2MClient *mbed_client)
{
cmd.printf("Firmware install requested\n");
display.set_installing();
/* firmware download is complete, restart the auto display updates */
display_evq_id = evq.call_every(DISPLAY_UPDATE_PERIOD_MS,
display_refresh,
&display);
mbed_client->set_fota_install_requested();
mbed_client->close();
}
/**
* Handles authorization requests from the mbed firmware updater
*/
void mbed_client_on_update_authorize(int32_t request)
{
switch (request) {
/* Cloud Client wishes to download new firmware. This can have a
* negative impact on the performance of the rest of the system.
*
* The user application is supposed to pause performance sensitive tasks
* before authorizing the download.
*
* Note: the authorization call can be postponed and called later.
* This doesn't affect the performance of the Cloud Client.
* */
case MbedCloudClient::UpdateRequestDownload:
m2mclient->set_fota_download_requested();
evq.call(fota_auth_download, m2mclient);
break;
/* Cloud Client wishes to reboot and apply the new firmware.
*
* The user application is supposed to save all current work before
* rebooting.
*
* Note: the authorization call can be postponed and called later.
* This doesn't affect the performance of the Cloud Client.
* */
case MbedCloudClient::UpdateRequestInstall:
m2mclient->set_fota_install_requested();
evq.call(fota_auth_install, m2mclient);
break;
default:
cmd.printf("ERROR: unknown request\n");
led_set_color(IND_FWUP, IND_COLOR_FAILED);
led_post();
break;
}
}
/**
* Handles progress updates from the mbed firmware updater
*/
void mbed_client_on_update_progress(uint32_t progress, uint32_t total)
{
uint32_t percent = progress * 100 / total;
static uint32_t last_percent = 0;
const char dl_message[] = "Downloading...";
const char done_message[] = "Saving (10s)...";
display.set_progress(dl_message, progress, total);
if (last_percent < percent) {
cmd.printf("Downloading: %lu\n", percent);
}
if (progress == total) {
cmd.printf("%s\n", done_message);
display.set_progress(done_message, 0, 100);
display.set_download_complete();
}
display.refresh();
last_percent = percent;
}
static void mbed_client_on_registered(void *context)
{
cmd.printf("mbed client registered\n");
display.set_cloud_registered();
}
static void mbed_client_on_unregistered(void *context)
{
M2MClient *m2m;
m2m = (M2MClient *)context;
if (m2m->is_fota_install_requested()) {
cmd.printf("Disconnecting network...\n");
network_disconnect(net);
m2m->update_authorize(MbedCloudClient::UpdateRequestInstall);
cmd.printf("Authorization granted\n");
}
cmd.printf("mbed client unregistered\n");
display.set_cloud_unregistered();
}
static void mbed_client_on_error(void *context, int err_code,
const char *err_name, const char *err_desc)
{
M2MClient *m2m;
m2m = (M2MClient *)context;
cmd.printf("ERROR: mbed client (%d) %s\n", err_code, err_name);
cmd.printf(" Error details : %s\n", err_desc);
display.set_cloud_error();
if ((err_code == MbedCloudClient::ConnectNetworkError) ||
(err_code == MbedCloudClient::ConnectDnsResolvingFailed)) {
if (m2m->is_fota_install_requested()) {
cmd.printf("Ignoring network error due to fota install\n");
return;
}
network_disconnect(net);
display.set_network_fail();
display.set_cloud_unregistered();
cmd.printf("Network connection failed. Attempting to reconnect.\n");
/* Because we are running in the mbed client thread context
* we want to disable our sensors from modifying the mbed
* client queue while we mess with the network. This will
* allow the main context to continue to refresh the display.
*
* Holding on to this thread context until netork connection
* is re-established will prevent the mbed client from backing
* off the time between connection retries.
*/
sensors_stop(&sensors, &evq);
sync_network_connect(net);
display.set_network_success();
sensors_start(&sensors, &evq);
/* CLoud client will automatically try to reconnect.*/
display.set_cloud_in_progress();
}
}
static void
mbed_client_on_resource_updated(void *context,
M2MClient::M2MClientResource resource)
{
M2MClient *m2m;
M2MResource *res;
m2m = (M2MClient *)context;
switch (resource) {
case M2MClient::M2MClientResourceAutoGeoLat:
case M2MClient::M2MClientResourceAutoGeoLong:
case M2MClient::M2MClientResourceAutoGeoAccuracy:
cmd.printf("INFO: auto geolocation data received\n");
break;
case M2MClient::M2MClientResourceAppLabel:
evq.call(mbed_client_handle_put_app_label, m2m);
break;
case M2MClient::M2MClientResourceGeoLat:
evq.call(mbed_client_handle_put_geo_lat, m2m);
break;
case M2MClient::M2MClientResourceGeoLong:
evq.call(mbed_client_handle_put_geo_long, m2m);
break;
case M2MClient::M2MClientResourceGeoAccuracy:
evq.call(mbed_client_handle_put_geo_accuracy, m2m);
break;
default:
res = m2m->get_resource(resource);
if (NULL != res) {
cmd.printf("WARN: unsupported PUT request: resource=%d, uri_path=%s\n",
resource, res->uri_path());
} else {
cmd.printf("WARN: unsupported PUT request on unregistered resource=%d\n",
resource);
}
break;
}
}
static int register_mbed_client(NetworkInterface *iface, M2MClient *mbed_client)
{
mbed_client->on_registered(NULL, mbed_client_on_registered);
mbed_client->on_unregistered(mbed_client, mbed_client_on_unregistered);
mbed_client->on_error(mbed_client, mbed_client_on_error);
mbed_client->on_update_authorize(mbed_client_on_update_authorize);
mbed_client->on_update_progress(mbed_client_on_update_progress);
mbed_client->on_resource_updated(mbed_client,
mbed_client_on_resource_updated);
display.set_cloud_in_progress();
mbed_client->call_register(iface);
/* set up a keep-alive interval to send registration updates to the
* mbed cloud server to avoid deregistration/registration issues. */
evq.call_every((MBED_CLOUD_CLIENT_LIFETIME / 4) * 1000,
mbed_client_keep_alive,
mbed_client);
return 0;
}
static int init_fcc(void)
{
fcc_status_e ret;
ret = fcc_init();
if (ret != FCC_STATUS_SUCCESS) {
cmd.printf("ERROR: fcc init failed: %d\n", ret);
return ret;
}
return 0;
}
void print_fcc_output_info(fcc_output_info_s *output_info)
{
fcc_warning_info_s *warning_list;
if (output_info == NULL) {
return;
}
/* print errors */
if (output_info->error_string_info != NULL) {
cmd.printf("ERROR: fcc: %s\n", output_info->error_string_info);
}
/* print warnings */
if (output_info->size_of_warning_info_list > 0) {
warning_list = output_info->head_of_warning_list;
while (warning_list != NULL) {
cmd.printf("WARN: fcc: %s\n", warning_list->warning_info_string);
warning_list = warning_list->next;
}
}
}
static int do_fcc(void)
{
fcc_status_e ret;
ret = fcc_developer_flow();
if (ret == FCC_STATUS_KCM_FILE_EXIST_ERROR) {
cmd.printf("fcc: developer credentials already exists\n");
} else if (ret != FCC_STATUS_SUCCESS) {
cmd.printf("ERROR: fcc failed to load developer credentials\n");
return ret;
}
ret = fcc_verify_device_configured_4mbed_cloud();
if (ret != FCC_STATUS_SUCCESS) {
cmd.printf("ERROR: fcc device not correctly configured for mbed cloud\n");
fcc_output_info_s* info = fcc_get_error_and_warning_data();
print_fcc_output_info(info);
return ret;
}
return 0;
}
// ****************************************************************************
// Generic Helpers
// ****************************************************************************
static void do_factory_reset()
{
int ret;
cmd.printf("FACTORY RESET\n");
ret = fs_format();
if (0 != ret) {
cmd.printf("ERROR: fs format failed: %d\n", ret);
return;
}
/* formatting the fs isn't enough to reset fcc */
fcc_init();
ret = fcc_storage_delete();
if (ret != FCC_STATUS_SUCCESS) {
cmd.printf("ERROR: fcc delete failed: %d\n", ret);
}
fcc_finalize();
display_evq_id = 0;
// Display "Factory Reset" message
display.set_erasing();
display.set_default_view();
}
static bool check_factory_reset()
{
int button_secs;
bool button_pressed;
DigitalIn button(PF_6);
button.mode(PullUp);
button_secs = 0;
/* since our button is PullUp, pressed==0 and not-pressed==1 */