uploadScript method

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

Uploads a script to the device.

Implementation

Future<void> uploadScript(String fileName, String filePath) async {
  try {
    _log.info("Uploading script: $fileName");

    String file = await rootBundle.loadString(filePath);

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

    var resp =
        await sendString("f=frame.file.open('$fileName', 'w');print('\x02')");

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

    int index = 0;
    int chunkSize = maxStringLength! - 22;

    while (index < file.length) {
      // Don't go over the end of the string
      if (index + chunkSize > file.length) {
        chunkSize = file.length - index;
      }

      // Don't split on an escape character
      if (file[index + chunkSize - 1] == '\\') {
        chunkSize -= 1;
      }

      String chunk = file.substring(index, index + chunkSize);

      resp = await sendString("f:write('$chunk');print('\x02')");

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

      index += chunkSize;
    }

    resp = await sendString("f:close();print('\x02')");

    if (resp != "\x02") {
      throw ("Error closing file: $resp");
    }
  } catch (error) {
    _log.warning("Couldn't upload script. $error");
    return Future.error(BrilliantBluetoothException(error.toString()));
  }
}