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