firmware_updater.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. import 'dart:async';
  2. import 'dart:collection';
  3. /// A validated, immutable ATmega328P application image.
  4. ///
  5. /// Gaps are erased-flash bytes (0xff). The final 512 bytes are reserved for a
  6. /// compatible STK500v1 bootloader; images targeting that area are rejected.
  7. class IntelHexFirmware {
  8. static const int maxApplicationSize = 0x7e00;
  9. final List<int> bytes;
  10. IntelHexFirmware._(List<int> bytes) : bytes = List.unmodifiable(bytes);
  11. factory IntelHexFirmware.parse(String source) {
  12. final data = <int, int>{};
  13. var baseAddress = 0;
  14. var ended = false;
  15. var lineNumber = 0;
  16. for (final rawLine in source.split('\n')) {
  17. lineNumber++;
  18. final line = rawLine.trim();
  19. if (line.isEmpty) continue;
  20. Never invalid(String reason) =>
  21. throw FormatException('Intel HEX line $lineNumber: $reason');
  22. if (ended) invalid('record after EOF');
  23. if (!RegExp(r'^:[0-9a-fA-F]+$').hasMatch(line) ||
  24. line.length < 11 ||
  25. line.length.isEven) {
  26. invalid('malformed or truncated record');
  27. }
  28. final record = <int>[
  29. for (var i = 1; i < line.length; i += 2)
  30. int.parse(line.substring(i, i + 2), radix: 16),
  31. ];
  32. final count = record[0];
  33. if (record.length != count + 5) invalid('incorrect record length');
  34. if (record.fold<int>(0, (sum, byte) => sum + byte) & 0xff != 0) {
  35. invalid('incorrect checksum');
  36. }
  37. final address = (record[1] << 8) | record[2];
  38. switch (record[3]) {
  39. case 0:
  40. if (count == 0) invalid('empty data record');
  41. if (address + count > 0x10000 ||
  42. baseAddress + address + count > maxApplicationSize) {
  43. invalid('address outside application flash');
  44. }
  45. for (var i = 0; i < count; i++) {
  46. final target = baseAddress + address + i;
  47. if (data.containsKey(target)) invalid('overlapping data');
  48. data[target] = record[4 + i];
  49. }
  50. case 1:
  51. if (count != 0 || address != 0) invalid('invalid EOF');
  52. ended = true;
  53. case 2:
  54. case 4:
  55. if (count != 2 || address != 0) invalid('invalid extended address');
  56. final extended = (record[4] << 8) | record[5];
  57. baseAddress = extended << (record[3] == 2 ? 4 : 16);
  58. if (baseAddress >= maxApplicationSize) {
  59. invalid('extended address outside application flash');
  60. }
  61. default:
  62. invalid('unsupported record type ${record[3]}');
  63. }
  64. }
  65. if (!ended) throw const FormatException('Intel HEX missing EOF');
  66. if (data.isEmpty) throw const FormatException('Intel HEX empty image');
  67. final lastAddress = data.keys.reduce((a, b) => a > b ? a : b);
  68. final bytes = List<int>.filled(lastAddress + 1, 0xff);
  69. data.forEach((address, value) => bytes[address] = value);
  70. return IntelHexFirmware._(bytes);
  71. }
  72. }
  73. enum FirmwareUpdateError {
  74. busy,
  75. disposed,
  76. disconnected,
  77. transport,
  78. timeout,
  79. protocol,
  80. bufferOverflow,
  81. signatureMismatch,
  82. verificationFailed,
  83. }
  84. class FirmwareUpdateException implements Exception {
  85. final FirmwareUpdateError code;
  86. final String message;
  87. final Object? cause;
  88. const FirmwareUpdateException(this.code, this.message, {this.cause});
  89. @override
  90. String toString() => 'FirmwareUpdateException(${code.name}): $message';
  91. }
  92. /// Sequential STK500v1 programmer. The transport must already be in bootloader
  93. /// mode and deliver only bootloader bytes, closing/erroring on disconnection.
  94. ///
  95. /// A failed programmer is terminal: reconnect and create a new instance rather
  96. /// than retrying an ambiguous page write. No chip-erase command is issued.
  97. class FirmwareUpdater {
  98. static const int expectedSignature = 0x1e950f;
  99. static const int pageSize = 128;
  100. static const int _maxBufferedBytes = 4096;
  101. final Future<void> Function(List<int>) write;
  102. final Duration timeout;
  103. final Queue<int> _buffer = Queue<int>();
  104. late final StreamSubscription<List<int>> _subscription;
  105. Completer<List<int>>? _reply;
  106. int _replyLength = 0;
  107. FirmwareUpdateException? _failure;
  108. bool _flashing = false;
  109. bool _disposed = false;
  110. bool _finished = false;
  111. FirmwareUpdater({
  112. required this.write,
  113. required Stream<List<int>> received,
  114. this.timeout = const Duration(seconds: 3),
  115. }) {
  116. if (timeout <= Duration.zero) {
  117. throw ArgumentError.value(timeout, 'timeout', 'Must be positive');
  118. }
  119. // Install before the first write, including synchronous transport replies.
  120. _subscription = received.listen(
  121. _receive,
  122. onError: (Object error, StackTrace stack) => _fail(
  123. FirmwareUpdateException(
  124. FirmwareUpdateError.transport,
  125. 'Bootloader input failed',
  126. cause: error,
  127. ),
  128. ),
  129. onDone: () => _fail(
  130. const FirmwareUpdateException(
  131. FirmwareUpdateError.disconnected,
  132. 'Bootloader transport disconnected',
  133. ),
  134. ),
  135. );
  136. }
  137. void _fail(FirmwareUpdateException failure) {
  138. _failure ??= failure;
  139. _buffer.clear();
  140. final reply = _reply;
  141. if (reply != null && !reply.isCompleted) reply.completeError(_failure!);
  142. }
  143. void _receive(List<int> bytes) {
  144. if (_failure != null || _disposed) return;
  145. if (_buffer.length + bytes.length > _maxBufferedBytes) {
  146. _fail(
  147. const FirmwareUpdateException(
  148. FirmwareUpdateError.bufferOverflow,
  149. 'Bootloader receive buffer exceeded its limit',
  150. ),
  151. );
  152. return;
  153. }
  154. if (bytes.any((byte) => byte < 0 || byte > 255)) {
  155. _fail(
  156. const FirmwareUpdateException(
  157. FirmwareUpdateError.protocol,
  158. 'Transport supplied a non-byte value',
  159. ),
  160. );
  161. return;
  162. }
  163. _buffer.addAll(bytes);
  164. _drain();
  165. }
  166. void _drain() {
  167. final reply = _reply;
  168. if (reply == null || reply.isCompleted || _buffer.isEmpty) return;
  169. if (_buffer.first != 0x14) {
  170. _fail(
  171. const FirmwareUpdateException(
  172. FirmwareUpdateError.protocol,
  173. 'Bootloader did not respond with STK_INSYNC',
  174. ),
  175. );
  176. return;
  177. }
  178. if (_buffer.length < _replyLength + 2) return;
  179. _buffer.removeFirst();
  180. final payload = <int>[
  181. for (var i = 0; i < _replyLength; i++) _buffer.removeFirst(),
  182. ];
  183. if (_buffer.removeFirst() != 0x10) {
  184. _fail(
  185. const FirmwareUpdateException(
  186. FirmwareUpdateError.protocol,
  187. 'Bootloader did not respond with STK_OK',
  188. ),
  189. );
  190. return;
  191. }
  192. reply.complete(payload);
  193. }
  194. Future<List<int>> _exchange(
  195. List<int> command, {
  196. int responseLength = 0,
  197. }) async {
  198. if (_failure case final failure?) throw failure;
  199. final reply = Completer<List<int>>();
  200. _reply = reply;
  201. _replyLength = responseLength;
  202. try {
  203. final results =
  204. await Future.wait<Object?>([
  205. reply.future,
  206. Future<void>.sync(() => write(List<int>.unmodifiable(command))),
  207. ], eagerError: true).timeout(
  208. timeout,
  209. onTimeout: () => throw const FirmwareUpdateException(
  210. FirmwareUpdateError.timeout,
  211. 'Timed out waiting for bootloader command delivery/response',
  212. ),
  213. );
  214. if (_failure case final failure?) throw failure;
  215. return results.first! as List<int>;
  216. } on FirmwareUpdateException catch (error) {
  217. _fail(error);
  218. rethrow;
  219. } catch (error) {
  220. final failure = FirmwareUpdateException(
  221. FirmwareUpdateError.transport,
  222. 'Bootloader command delivery failed',
  223. cause: error,
  224. );
  225. _fail(failure);
  226. throw failure;
  227. } finally {
  228. _reply = null;
  229. }
  230. }
  231. Future<void> _loadAddress(int byteAddress) async {
  232. final wordAddress = byteAddress ~/ 2;
  233. await _exchange([0x55, wordAddress & 0xff, wordAddress >> 8, 0x20]);
  234. }
  235. Future<void> flash(
  236. IntelHexFirmware firmware, {
  237. void Function(double)? onProgress,
  238. }) async {
  239. if (_disposed) {
  240. throw const FirmwareUpdateException(
  241. FirmwareUpdateError.disposed,
  242. 'Programmer has been disposed',
  243. );
  244. }
  245. if (_flashing || _finished) {
  246. throw const FirmwareUpdateException(
  247. FirmwareUpdateError.busy,
  248. 'Programmer is already running or has completed',
  249. );
  250. }
  251. if (_failure case final failure?) throw failure;
  252. _flashing = true;
  253. try {
  254. onProgress?.call(0);
  255. await _exchange([0x30, 0x20]);
  256. await _exchange([0x50, 0x20]);
  257. final signature = await _exchange([0x75, 0x20], responseLength: 3);
  258. final actual = (signature[0] << 16) | (signature[1] << 8) | signature[2];
  259. if (actual != expectedSignature) {
  260. final failure = FirmwareUpdateException(
  261. FirmwareUpdateError.signatureMismatch,
  262. 'Expected ATmega328P signature 1e950f, received '
  263. '${actual.toRadixString(16).padLeft(6, '0')}',
  264. );
  265. _fail(failure);
  266. throw failure;
  267. }
  268. final pageCount = (firmware.bytes.length + pageSize - 1) ~/ pageSize;
  269. for (var page = 0; page < pageCount; page++) {
  270. final address = page * pageSize;
  271. final bytes = List<int>.filled(pageSize, 0xff);
  272. for (
  273. var i = 0;
  274. i < pageSize && address + i < firmware.bytes.length;
  275. i++
  276. ) {
  277. bytes[i] = firmware.bytes[address + i];
  278. }
  279. await _loadAddress(address);
  280. await _exchange([0x64, 0, pageSize, 0x46, ...bytes, 0x20]);
  281. await _loadAddress(address);
  282. final readBack = await _exchange([
  283. 0x74,
  284. 0,
  285. pageSize,
  286. 0x46,
  287. 0x20,
  288. ], responseLength: pageSize);
  289. for (var i = 0; i < pageSize; i++) {
  290. if (readBack[i] != bytes[i]) {
  291. final failure = FirmwareUpdateException(
  292. FirmwareUpdateError.verificationFailed,
  293. 'Flash read-back mismatch at byte 0x'
  294. '${(address + i).toRadixString(16)}',
  295. );
  296. _fail(failure);
  297. throw failure;
  298. }
  299. }
  300. // Reserve completion for a successfully acknowledged LEAVE_PROGMODE.
  301. onProgress?.call((page + 1) / (pageCount + 1));
  302. }
  303. await _exchange([0x51, 0x20]);
  304. _finished = true;
  305. onProgress?.call(1);
  306. } catch (error) {
  307. _fail(
  308. error is FirmwareUpdateException
  309. ? error
  310. : FirmwareUpdateException(
  311. FirmwareUpdateError.transport,
  312. 'Firmware update interrupted',
  313. cause: error,
  314. ),
  315. );
  316. rethrow;
  317. } finally {
  318. _flashing = false;
  319. }
  320. }
  321. Future<void> dispose() async {
  322. if (_disposed) return;
  323. _disposed = true;
  324. _fail(
  325. const FirmwareUpdateException(
  326. FirmwareUpdateError.disposed,
  327. 'Programmer has been disposed',
  328. ),
  329. );
  330. await _subscription.cancel();
  331. }
  332. }