1#include <MKRNB.h>
2#include <SBU.h>
3
4#include "lzssEncode.h"
5
6static char const BINARY[] =
7{
8#include "Binary.h"
9};
10
11static char const CHECK_FILE[] =
12{
13  "OK"
14};
15
16static constexpr char CHECK_FILE_NAME[] = "UPDATE.OK";
17const char * UPDATE_FILE_NAME_LZSS = "UPDATE.BIN.LZSS";
18
19NBFileUtils fileUtils;
20bool update_available = false;
21
22void setup() {
23  Serial.begin(9600);
24  while (!Serial) { }
25
26  unsigned long const start = millis();
27  for (unsigned long now = millis(); !Serial && ((now - start) < 5000); now = millis()) { };
28
29  Serial.print("Accessing SARA Filesystem... ");
30  if (!fileUtils.begin(false)) {
31    Serial.println("failed.");
32    return;
33
34  }
35  Serial.println("OK");
36
37  uint32_t bytes_to_write = sizeof(BINARY);
38  Serial.print("Size of BINARY.H: ");
39  Serial.println(bytes_to_write);
40
41  Serial.print("Encoding \"BINARY.H\" into \"UPDATE.BIN.LZSS\" and writing it into the Sara-R410M module ... ");
42  
43  //Encode into .lzss and write to the Sara modem
44  int bytes_written = lzss_encode(BINARY, bytes_to_write);
45
46  if (bytes_written == 0) {
47    Serial.println("something went wrong!");
48  } else {
49    Serial.println("OK!");
50  }
51
52  Serial.print("Size of UPDATE.BIN.LZSS: ");
53  Serial.println(bytes_written);
54
55  auto status = 0;
56  while (status != 2) {
57    status = fileUtils.createFile(CHECK_FILE_NAME, CHECK_FILE, 2);
58    delay(100);
59  }
60
61  Serial.println("Please type \"restart\" to apply the update");
62  update_available = true;
63}
64
65
66void loop() {
67  if (update_available == true) {
68    String command = Serial.readStringUntil('\n');
69    if (command.indexOf("restart") >= 0) {
70      NVIC_SystemReset();
71    }
72  }
73}
74