1#include <MKRNB.h>
2#include <SBU.h>
3
4static char const BINARY[] =
5{
6  #include "Binary.h"
7};
8
9static char const CHECK_FILE[] =
10{
11  "OK" 
12};
13
14static constexpr char CHECK_FILE_NAME[] = "UPDATE.OK";
15
16NBFileUtils fileUtils;
17bool update_available = false;
18
19void setup() {
20  Serial.begin(9600);
21  while(!Serial) { }
22
23  unsigned long const start = millis();
24  for(unsigned long now = millis(); !Serial && ((now - start) < 5000); now = millis()) { };
25
26  Serial.print("Accessing SARA Filesystem... ");
27  if(!fileUtils.begin(false)) {
28    Serial.println("failed.");
29    return;
30
31  }
32  Serial.println("OK");
33  Serial.print("Writing \"UPDATE.BIN\" ... ");
34  
35  uint32_t bytes_to_write = sizeof(BINARY);
36  Serial.print("Size of BINARY: ");
37  Serial.println(bytes_to_write);
38  int index = 0;
39  bool append = false;
40  int new_bytes = 0;
41  //int bytes_written = 0;
42  
43  for (int i=0; i<(bytes_to_write/512); i++) {
44    auto new_bytes = fileUtils.downloadFile("UPDATE.BIN", BINARY+index, 512, append);
45    if (new_bytes != 512) {
46      Serial.print("New_bytes = ");
47      Serial.print(new_bytes);
48      Serial.println(" != 512");
49    }
50    index = index + new_bytes;
51    append = true;
52  }
53  if ((bytes_to_write%512)!=0) {  
54    auto new_bytes = fileUtils.downloadFile("UPDATE.BIN", BINARY+index, bytes_to_write%512, append);
55    if (new_bytes != bytes_to_write%512) {
56      Serial.print("Last bytes read = ");
57      Serial.print(new_bytes);
58      Serial.print(". They should have been ");
59      Serial.println(bytes_to_write%512);
60    }
61    index = index + new_bytes;
62  }
63
64  if(index != bytes_to_write) {
65    Serial.print("Written only ");
66    Serial.println(index); //bytes_written
67    Serial.print(bytes_to_write);
68    Serial.println(" should have been written. System is restarting...");
69    delay(100);
70    NVIC_SystemReset();
71
72  } else {
73    Serial.print("Download complete! ");
74    Serial.print(index);
75    Serial.println(" bytes written");
76
77    auto status = 0;
78    while (status != 2) {
79      status = fileUtils.createFile(CHECK_FILE_NAME, CHECK_FILE, 2);
80      delay(100);
81    }
82    
83    Serial.println("Please type \"restart\" to apply the update");
84    update_available = true;
85  }
86  
87}
88
89void loop() {
90  if (update_available == true) {
91    String command = Serial.readStringUntil('\n');
92    if (command.indexOf("restart") >= 0) {
93      NVIC_SystemReset();
94    }
95  }
96}
97