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