Read Firmware from SD card and flash to P1 or Photon

@ScruffR One oddity is that file.file_length is assigned the value of fileSize

file.file_length = fileSize; 

Because fileSize is 3832, file.file_length should return 3832, but instead it routinely returns 262144. I’m guessing this has some impact on whether or not the file is flashed properly.

Oddly enough, 262144 = 512^2, so perhaps it is being manipulated by the chunk size? I’m going to dig into this more. Here is the code for that function:

void updateFirmwareFromFile(uint8_t* file_bytes) {
  delay(5000);

  FileTransfer::Descriptor file;

  Serial.printlnf("starting flash size=%d", fileSize);

  file.file_length = fileSize;
  file.file_address = 0; // Automatically set to HAL_OTA_FlashAddress if store is FIRMWARE
  file.chunk_address = 0;
  file.chunk_size = 0; // use default
  file.store = FileTransfer::Store::FIRMWARE;

  int result = Spark_Prepare_For_Firmware_Update(file, 0, NULL);
  if (result != 0) {
    Serial.printlnf("prepare failed %d", result);
    return;
  }

  Serial.printlnf("chunk_size=%d file_address=0x%x fileSize=%d", file.chunk_size, file.file_address, fileSize);
  if (file.chunk_size == 0) {
    file.chunk_size = 512;
  }

  // Note that Spark_Prepare_For_Firmware_Update sets file.file_address so it's not really zero here
  // even though it's what we initialize it to above!
  file.chunk_address = file.file_address;

  size_t offset = 0;

  while(offset < fileSize) {
    if (file.chunk_size > (fileSize - offset)) {
      file.chunk_size = (fileSize - offset);
    }

    Serial.printlnf("chunk_address=0x%x chunk_size=%d (%d < %d == %s)", file.chunk_address, file.chunk_size, offset, file.file_length, (offset < file.file_length) ? "continue" : "break");
    result = Spark_Save_Firmware_Chunk(file, &file_bytes[offset], NULL);

    if (result != 0) {
      Serial.printlnf("save chunk failed %d", result);
      return;
    }
    file.chunk_address += file.chunk_size;
    offset += file.chunk_size;
  }

  result = Spark_Finish_Firmware_Update(file, 0x1, NULL);
  if (result != 0) {
    Serial.printlnf("finish failed %d", result);
    return;
  }

  Serial.printlnf("update complete");

}

And here is the output:

starting flash size=3832
chunk_size=512 file_address=0x80c0000 fileSize=3832
chunk_address=0x80c0000 chunk_size=512 (0 < 262144 == continue)
chunk_address=0x80c0200 chunk_size=512 (512 < 262144 == continue)
chunk_address=0x80c0400 chunk_size=512 (1024 < 262144 == continue)
chunk_address=0x80c0600 chunk_size=512 (1536 < 262144 == continue)
chunk_address=0x80c0800 chunk_size=512 (2048 < 262144 == continue)
chunk_address=0x80c0a00 chunk_size=512 (2560 < 262144 == continue)
chunk_address=0x80c0c00 chunk_size=512 (3072 < 262144 == continue)
chunk_address=0x80c0e00 chunk_size=248 (3584 < 262144 == continue)
0000020648 [hal] WARN: OTA module not applied
finish failed 1