firmware_updater.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. /// No STK500 bootloader answered GET_SYNC; nothing was written.
  84. noBootloader,
  85. }
  86. class FirmwareUpdateException implements Exception {
  87. final FirmwareUpdateError code;
  88. final String message;
  89. final Object? cause;
  90. const FirmwareUpdateException(this.code, this.message, {this.cause});
  91. @override
  92. String toString() => 'FirmwareUpdateException(${code.name}): $message';
  93. }
  94. /// Sequential STK500v1 programmer. The transport must already be in bootloader
  95. /// mode and deliver only bootloader bytes, closing/erroring on disconnection.
  96. ///
  97. /// A failed programmer is terminal: reconnect and create a new instance rather
  98. /// than retrying an ambiguous page write. No chip-erase command is issued.
  99. class FirmwareUpdater {
  100. static const int expectedSignature = 0x1e950f;
  101. static const int pageSize = 128;
  102. static const int _maxBufferedBytes = 4096;
  103. final Future<void> Function(List<int>) write;
  104. final Duration timeout;
  105. /// GET_SYNC is retried this many times, each waiting [syncInterval], because
  106. /// the bootloader only starts after the reconnect resets the controller.
  107. final int syncAttempts;
  108. final Duration syncInterval;
  109. /// After sync, late answers to earlier GET_SYNC attempts are discarded.
  110. final Duration syncSettle;
  111. final Queue<int> _buffer = Queue<int>();
  112. late final StreamSubscription<List<int>> _subscription;
  113. Completer<List<int>>? _reply;
  114. int _replyLength = 0;
  115. FirmwareUpdateException? _failure;
  116. bool _flashing = false;
  117. bool _disposed = false;
  118. bool _finished = false;
  119. bool _syncing = false;
  120. FirmwareUpdater({
  121. required this.write,
  122. required Stream<List<int>> received,
  123. this.timeout = const Duration(seconds: 3),
  124. this.syncAttempts = 12,
  125. this.syncInterval = const Duration(milliseconds: 250),
  126. this.syncSettle = const Duration(milliseconds: 100),
  127. }) {
  128. if (timeout <= Duration.zero) {
  129. throw ArgumentError.value(timeout, 'timeout', 'Must be positive');
  130. }
  131. if (syncAttempts < 1 || syncInterval <= Duration.zero) {
  132. throw ArgumentError('GET_SYNC needs at least one positive attempt');
  133. }
  134. // Install before the first write, including synchronous transport replies.
  135. _subscription = received.listen(
  136. _receive,
  137. onError: (Object error, StackTrace stack) => _fail(
  138. FirmwareUpdateException(
  139. FirmwareUpdateError.transport,
  140. 'Bootloader input failed',
  141. cause: error,
  142. ),
  143. ),
  144. onDone: () => _fail(
  145. const FirmwareUpdateException(
  146. FirmwareUpdateError.disconnected,
  147. 'Bootloader transport disconnected',
  148. ),
  149. ),
  150. );
  151. }
  152. void _fail(FirmwareUpdateException failure) {
  153. _failure ??= failure;
  154. _buffer.clear();
  155. final reply = _reply;
  156. if (reply != null && !reply.isCompleted) reply.completeError(_failure!);
  157. }
  158. void _receive(List<int> bytes) {
  159. if (_failure != null || _disposed) return;
  160. if (_buffer.length + bytes.length > _maxBufferedBytes) {
  161. _fail(
  162. const FirmwareUpdateException(
  163. FirmwareUpdateError.bufferOverflow,
  164. 'Bootloader receive buffer exceeded its limit',
  165. ),
  166. );
  167. return;
  168. }
  169. if (bytes.any((byte) => byte < 0 || byte > 255)) {
  170. _fail(
  171. const FirmwareUpdateException(
  172. FirmwareUpdateError.protocol,
  173. 'Transport supplied a non-byte value',
  174. ),
  175. );
  176. return;
  177. }
  178. _buffer.addAll(bytes);
  179. _drain();
  180. }
  181. void _drain() {
  182. final reply = _reply;
  183. if (reply == null || reply.isCompleted || _buffer.isEmpty) return;
  184. if (_syncing) {
  185. // Before sync, skip application output and partial replies until an
  186. // STK_INSYNC/STK_OK pair arrives.
  187. while (_buffer.isNotEmpty) {
  188. if (_buffer.first != 0x14) {
  189. _buffer.removeFirst();
  190. continue;
  191. }
  192. if (_buffer.length < 2) return;
  193. _buffer.removeFirst();
  194. if (_buffer.first == 0x10) {
  195. _buffer.removeFirst();
  196. reply.complete(const []);
  197. return;
  198. }
  199. }
  200. return;
  201. }
  202. if (_buffer.first != 0x14) {
  203. _fail(
  204. const FirmwareUpdateException(
  205. FirmwareUpdateError.protocol,
  206. 'Bootloader did not respond with STK_INSYNC',
  207. ),
  208. );
  209. return;
  210. }
  211. if (_buffer.length < _replyLength + 2) return;
  212. _buffer.removeFirst();
  213. final payload = <int>[
  214. for (var i = 0; i < _replyLength; i++) _buffer.removeFirst(),
  215. ];
  216. if (_buffer.removeFirst() != 0x10) {
  217. _fail(
  218. const FirmwareUpdateException(
  219. FirmwareUpdateError.protocol,
  220. 'Bootloader did not respond with STK_OK',
  221. ),
  222. );
  223. return;
  224. }
  225. reply.complete(payload);
  226. }
  227. Future<List<int>> _exchange(
  228. List<int> command, {
  229. int responseLength = 0,
  230. }) async {
  231. if (_failure case final failure?) throw failure;
  232. final reply = Completer<List<int>>();
  233. _reply = reply;
  234. _replyLength = responseLength;
  235. try {
  236. final results =
  237. await Future.wait<Object?>([
  238. reply.future,
  239. Future<void>.sync(() => write(List<int>.unmodifiable(command))),
  240. ], eagerError: true).timeout(
  241. timeout,
  242. onTimeout: () => throw const FirmwareUpdateException(
  243. FirmwareUpdateError.timeout,
  244. 'Timed out waiting for bootloader command delivery/response',
  245. ),
  246. );
  247. if (_failure case final failure?) throw failure;
  248. return results.first! as List<int>;
  249. } on FirmwareUpdateException catch (error) {
  250. _fail(error);
  251. rethrow;
  252. } catch (error) {
  253. final failure = FirmwareUpdateException(
  254. FirmwareUpdateError.transport,
  255. 'Bootloader command delivery failed',
  256. cause: error,
  257. );
  258. _fail(failure);
  259. throw failure;
  260. } finally {
  261. _reply = null;
  262. }
  263. }
  264. Future<void> _synchronize() async {
  265. for (var attempt = 0; attempt < syncAttempts; attempt++) {
  266. if (_failure case final failure?) throw failure;
  267. final reply = Completer<List<int>>();
  268. _reply = reply;
  269. _replyLength = 0;
  270. _syncing = true;
  271. try {
  272. final exchange = Future.wait<Object?>([
  273. reply.future,
  274. Future<void>.sync(() => write(const [0x30, 0x20])),
  275. ], eagerError: true);
  276. // A write still pending when this attempt times out must not surface
  277. // later as an unhandled error.
  278. exchange.ignore();
  279. await exchange.timeout(syncInterval);
  280. _reply = null;
  281. _syncing = false;
  282. await Future<void>.delayed(syncSettle);
  283. if (_failure case final failure?) throw failure;
  284. _buffer.clear();
  285. return;
  286. } on TimeoutException {
  287. if (reply.isCompleted) {
  288. // The bootloader answered but the transport never finished the
  289. // write: a stalled link, not a missing bootloader.
  290. const failure = FirmwareUpdateException(
  291. FirmwareUpdateError.timeout,
  292. 'Timed out waiting for bootloader command delivery/response',
  293. );
  294. _fail(failure);
  295. throw failure;
  296. }
  297. continue;
  298. } on FirmwareUpdateException catch (error) {
  299. _fail(error);
  300. rethrow;
  301. } catch (error) {
  302. final failure = FirmwareUpdateException(
  303. FirmwareUpdateError.transport,
  304. 'Bootloader command delivery failed',
  305. cause: error,
  306. );
  307. _fail(failure);
  308. throw failure;
  309. } finally {
  310. _reply = null;
  311. _syncing = false;
  312. }
  313. }
  314. final failure = FirmwareUpdateException(
  315. FirmwareUpdateError.noBootloader,
  316. 'No STK500 bootloader answered GET_SYNC after $syncAttempts attempts',
  317. );
  318. _fail(failure);
  319. throw failure;
  320. }
  321. Future<void> _loadAddress(int byteAddress) async {
  322. final wordAddress = byteAddress ~/ 2;
  323. await _exchange([0x55, wordAddress & 0xff, wordAddress >> 8, 0x20]);
  324. }
  325. Future<void> flash(
  326. IntelHexFirmware firmware, {
  327. void Function(double)? onProgress,
  328. }) async {
  329. if (_disposed) {
  330. throw const FirmwareUpdateException(
  331. FirmwareUpdateError.disposed,
  332. 'Programmer has been disposed',
  333. );
  334. }
  335. if (_flashing || _finished) {
  336. throw const FirmwareUpdateException(
  337. FirmwareUpdateError.busy,
  338. 'Programmer is already running or has completed',
  339. );
  340. }
  341. if (_failure case final failure?) throw failure;
  342. _flashing = true;
  343. try {
  344. onProgress?.call(0);
  345. await _synchronize();
  346. await _exchange([0x50, 0x20]);
  347. final signature = await _exchange([0x75, 0x20], responseLength: 3);
  348. final actual = (signature[0] << 16) | (signature[1] << 8) | signature[2];
  349. if (actual != expectedSignature) {
  350. final failure = FirmwareUpdateException(
  351. FirmwareUpdateError.signatureMismatch,
  352. 'Expected ATmega328P signature 1e950f, received '
  353. '${actual.toRadixString(16).padLeft(6, '0')}',
  354. );
  355. _fail(failure);
  356. throw failure;
  357. }
  358. final pageCount = (firmware.bytes.length + pageSize - 1) ~/ pageSize;
  359. for (var page = 0; page < pageCount; page++) {
  360. final address = page * pageSize;
  361. final bytes = List<int>.filled(pageSize, 0xff);
  362. for (
  363. var i = 0;
  364. i < pageSize && address + i < firmware.bytes.length;
  365. i++
  366. ) {
  367. bytes[i] = firmware.bytes[address + i];
  368. }
  369. await _loadAddress(address);
  370. await _exchange([0x64, 0, pageSize, 0x46, ...bytes, 0x20]);
  371. await _loadAddress(address);
  372. final readBack = await _exchange([
  373. 0x74,
  374. 0,
  375. pageSize,
  376. 0x46,
  377. 0x20,
  378. ], responseLength: pageSize);
  379. for (var i = 0; i < pageSize; i++) {
  380. if (readBack[i] != bytes[i]) {
  381. final failure = FirmwareUpdateException(
  382. FirmwareUpdateError.verificationFailed,
  383. 'Flash read-back mismatch at byte 0x'
  384. '${(address + i).toRadixString(16)}',
  385. );
  386. _fail(failure);
  387. throw failure;
  388. }
  389. }
  390. // Reserve completion for a successfully acknowledged LEAVE_PROGMODE.
  391. onProgress?.call((page + 1) / (pageCount + 1));
  392. }
  393. await _exchange([0x51, 0x20]);
  394. _finished = true;
  395. onProgress?.call(1);
  396. } catch (error) {
  397. _fail(
  398. error is FirmwareUpdateException
  399. ? error
  400. : FirmwareUpdateException(
  401. FirmwareUpdateError.transport,
  402. 'Firmware update interrupted',
  403. cause: error,
  404. ),
  405. );
  406. rethrow;
  407. } finally {
  408. _flashing = false;
  409. }
  410. }
  411. Future<void> dispose() async {
  412. if (_disposed) return;
  413. _disposed = true;
  414. _fail(
  415. const FirmwareUpdateException(
  416. FirmwareUpdateError.disposed,
  417. 'Programmer has been disposed',
  418. ),
  419. );
  420. await _subscription.cancel();
  421. }
  422. }