uploadScript method

Future<void> uploadScript(
  1. String fileName,
  2. String fileContents
)

Implementation

Future<void> uploadScript(String fileName, String fileContents) async {
  try {
    _log.info("Uploading script: $fileName");
    // TODO temporarily observe memory usage
    // await sendString(
    //     'print("Frame Mem: " .. tostring(collectgarbage("count")))',
    //     awaitResponse: true);

    String file = fileContents;

    file = file.replaceAll('\\', '\\\\');
    file = file.replaceAll("\r\n", "\\n");
    file = file.replaceAll("\n", "\\n");
    file = file.replaceAll("'", "\\'");
    file = file.replaceAll('"', '\\"');

    var resp = await sendString(
        'f=frame.file.open("$fileName", "w");print(2)',
        awaitResponse: true,
        log: false);

    if (resp != "2") {
      throw ("Error opening file: $resp");
    }

    // Chunk by UTF-8 byte length (not string length) so that characters
    // that expand to multiple bytes can't push a packet over the MTU
    for (final chunk
        in chunkLuaString(utf8.encode(file), maxStringLength! - 22)) {
      resp = await sendString("f:write('$chunk');print(2)", awaitResponse: true, log: false);

      if (resp != "2") {
        throw ("Error writing file: $resp");
      }
    }

    resp = await sendString("f:close();print(2)", awaitResponse: true, log: false);

    if (resp != "2") {
      throw ("Error closing file: $resp");
    }

    // TODO temporarily observe memory usage
    // await sendString(
    //     'print("Frame Mem: " .. tostring(collectgarbage("count")))',
    //     awaitResponse: true);
  } catch (error) {
    _log.warning("Couldn't upload script. $error");
    return Future.error(BrilliantBluetoothException(error.toString()));
  }
}