| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351 |
- import 'dart:async';
- import 'dart:collection';
- /// A validated, immutable ATmega328P application image.
- ///
- /// Gaps are erased-flash bytes (0xff). The final 512 bytes are reserved for a
- /// compatible STK500v1 bootloader; images targeting that area are rejected.
- class IntelHexFirmware {
- static const int maxApplicationSize = 0x7e00;
- final List<int> bytes;
- IntelHexFirmware._(List<int> bytes) : bytes = List.unmodifiable(bytes);
- factory IntelHexFirmware.parse(String source) {
- final data = <int, int>{};
- var baseAddress = 0;
- var ended = false;
- var lineNumber = 0;
- for (final rawLine in source.split('\n')) {
- lineNumber++;
- final line = rawLine.trim();
- if (line.isEmpty) continue;
- Never invalid(String reason) =>
- throw FormatException('Intel HEX line $lineNumber: $reason');
- if (ended) invalid('record after EOF');
- if (!RegExp(r'^:[0-9a-fA-F]+$').hasMatch(line) ||
- line.length < 11 ||
- line.length.isEven) {
- invalid('malformed or truncated record');
- }
- final record = <int>[
- for (var i = 1; i < line.length; i += 2)
- int.parse(line.substring(i, i + 2), radix: 16),
- ];
- final count = record[0];
- if (record.length != count + 5) invalid('incorrect record length');
- if (record.fold<int>(0, (sum, byte) => sum + byte) & 0xff != 0) {
- invalid('incorrect checksum');
- }
- final address = (record[1] << 8) | record[2];
- switch (record[3]) {
- case 0:
- if (count == 0) invalid('empty data record');
- if (address + count > 0x10000 ||
- baseAddress + address + count > maxApplicationSize) {
- invalid('address outside application flash');
- }
- for (var i = 0; i < count; i++) {
- final target = baseAddress + address + i;
- if (data.containsKey(target)) invalid('overlapping data');
- data[target] = record[4 + i];
- }
- case 1:
- if (count != 0 || address != 0) invalid('invalid EOF');
- ended = true;
- case 2:
- case 4:
- if (count != 2 || address != 0) invalid('invalid extended address');
- final extended = (record[4] << 8) | record[5];
- baseAddress = extended << (record[3] == 2 ? 4 : 16);
- if (baseAddress >= maxApplicationSize) {
- invalid('extended address outside application flash');
- }
- default:
- invalid('unsupported record type ${record[3]}');
- }
- }
- if (!ended) throw const FormatException('Intel HEX missing EOF');
- if (data.isEmpty) throw const FormatException('Intel HEX empty image');
- final lastAddress = data.keys.reduce((a, b) => a > b ? a : b);
- final bytes = List<int>.filled(lastAddress + 1, 0xff);
- data.forEach((address, value) => bytes[address] = value);
- return IntelHexFirmware._(bytes);
- }
- }
- enum FirmwareUpdateError {
- busy,
- disposed,
- disconnected,
- transport,
- timeout,
- protocol,
- bufferOverflow,
- signatureMismatch,
- verificationFailed,
- }
- class FirmwareUpdateException implements Exception {
- final FirmwareUpdateError code;
- final String message;
- final Object? cause;
- const FirmwareUpdateException(this.code, this.message, {this.cause});
- @override
- String toString() => 'FirmwareUpdateException(${code.name}): $message';
- }
- /// Sequential STK500v1 programmer. The transport must already be in bootloader
- /// mode and deliver only bootloader bytes, closing/erroring on disconnection.
- ///
- /// A failed programmer is terminal: reconnect and create a new instance rather
- /// than retrying an ambiguous page write. No chip-erase command is issued.
- class FirmwareUpdater {
- static const int expectedSignature = 0x1e950f;
- static const int pageSize = 128;
- static const int _maxBufferedBytes = 4096;
- final Future<void> Function(List<int>) write;
- final Duration timeout;
- final Queue<int> _buffer = Queue<int>();
- late final StreamSubscription<List<int>> _subscription;
- Completer<List<int>>? _reply;
- int _replyLength = 0;
- FirmwareUpdateException? _failure;
- bool _flashing = false;
- bool _disposed = false;
- bool _finished = false;
- FirmwareUpdater({
- required this.write,
- required Stream<List<int>> received,
- this.timeout = const Duration(seconds: 3),
- }) {
- if (timeout <= Duration.zero) {
- throw ArgumentError.value(timeout, 'timeout', 'Must be positive');
- }
- // Install before the first write, including synchronous transport replies.
- _subscription = received.listen(
- _receive,
- onError: (Object error, StackTrace stack) => _fail(
- FirmwareUpdateException(
- FirmwareUpdateError.transport,
- 'Bootloader input failed',
- cause: error,
- ),
- ),
- onDone: () => _fail(
- const FirmwareUpdateException(
- FirmwareUpdateError.disconnected,
- 'Bootloader transport disconnected',
- ),
- ),
- );
- }
- void _fail(FirmwareUpdateException failure) {
- _failure ??= failure;
- _buffer.clear();
- final reply = _reply;
- if (reply != null && !reply.isCompleted) reply.completeError(_failure!);
- }
- void _receive(List<int> bytes) {
- if (_failure != null || _disposed) return;
- if (_buffer.length + bytes.length > _maxBufferedBytes) {
- _fail(
- const FirmwareUpdateException(
- FirmwareUpdateError.bufferOverflow,
- 'Bootloader receive buffer exceeded its limit',
- ),
- );
- return;
- }
- if (bytes.any((byte) => byte < 0 || byte > 255)) {
- _fail(
- const FirmwareUpdateException(
- FirmwareUpdateError.protocol,
- 'Transport supplied a non-byte value',
- ),
- );
- return;
- }
- _buffer.addAll(bytes);
- _drain();
- }
- void _drain() {
- final reply = _reply;
- if (reply == null || reply.isCompleted || _buffer.isEmpty) return;
- if (_buffer.first != 0x14) {
- _fail(
- const FirmwareUpdateException(
- FirmwareUpdateError.protocol,
- 'Bootloader did not respond with STK_INSYNC',
- ),
- );
- return;
- }
- if (_buffer.length < _replyLength + 2) return;
- _buffer.removeFirst();
- final payload = <int>[
- for (var i = 0; i < _replyLength; i++) _buffer.removeFirst(),
- ];
- if (_buffer.removeFirst() != 0x10) {
- _fail(
- const FirmwareUpdateException(
- FirmwareUpdateError.protocol,
- 'Bootloader did not respond with STK_OK',
- ),
- );
- return;
- }
- reply.complete(payload);
- }
- Future<List<int>> _exchange(
- List<int> command, {
- int responseLength = 0,
- }) async {
- if (_failure case final failure?) throw failure;
- final reply = Completer<List<int>>();
- _reply = reply;
- _replyLength = responseLength;
- try {
- final results =
- await Future.wait<Object?>([
- reply.future,
- Future<void>.sync(() => write(List<int>.unmodifiable(command))),
- ], eagerError: true).timeout(
- timeout,
- onTimeout: () => throw const FirmwareUpdateException(
- FirmwareUpdateError.timeout,
- 'Timed out waiting for bootloader command delivery/response',
- ),
- );
- if (_failure case final failure?) throw failure;
- return results.first! as List<int>;
- } on FirmwareUpdateException catch (error) {
- _fail(error);
- rethrow;
- } catch (error) {
- final failure = FirmwareUpdateException(
- FirmwareUpdateError.transport,
- 'Bootloader command delivery failed',
- cause: error,
- );
- _fail(failure);
- throw failure;
- } finally {
- _reply = null;
- }
- }
- Future<void> _loadAddress(int byteAddress) async {
- final wordAddress = byteAddress ~/ 2;
- await _exchange([0x55, wordAddress & 0xff, wordAddress >> 8, 0x20]);
- }
- Future<void> flash(
- IntelHexFirmware firmware, {
- void Function(double)? onProgress,
- }) async {
- if (_disposed) {
- throw const FirmwareUpdateException(
- FirmwareUpdateError.disposed,
- 'Programmer has been disposed',
- );
- }
- if (_flashing || _finished) {
- throw const FirmwareUpdateException(
- FirmwareUpdateError.busy,
- 'Programmer is already running or has completed',
- );
- }
- if (_failure case final failure?) throw failure;
- _flashing = true;
- try {
- onProgress?.call(0);
- await _exchange([0x30, 0x20]);
- await _exchange([0x50, 0x20]);
- final signature = await _exchange([0x75, 0x20], responseLength: 3);
- final actual = (signature[0] << 16) | (signature[1] << 8) | signature[2];
- if (actual != expectedSignature) {
- final failure = FirmwareUpdateException(
- FirmwareUpdateError.signatureMismatch,
- 'Expected ATmega328P signature 1e950f, received '
- '${actual.toRadixString(16).padLeft(6, '0')}',
- );
- _fail(failure);
- throw failure;
- }
- final pageCount = (firmware.bytes.length + pageSize - 1) ~/ pageSize;
- for (var page = 0; page < pageCount; page++) {
- final address = page * pageSize;
- final bytes = List<int>.filled(pageSize, 0xff);
- for (
- var i = 0;
- i < pageSize && address + i < firmware.bytes.length;
- i++
- ) {
- bytes[i] = firmware.bytes[address + i];
- }
- await _loadAddress(address);
- await _exchange([0x64, 0, pageSize, 0x46, ...bytes, 0x20]);
- await _loadAddress(address);
- final readBack = await _exchange([
- 0x74,
- 0,
- pageSize,
- 0x46,
- 0x20,
- ], responseLength: pageSize);
- for (var i = 0; i < pageSize; i++) {
- if (readBack[i] != bytes[i]) {
- final failure = FirmwareUpdateException(
- FirmwareUpdateError.verificationFailed,
- 'Flash read-back mismatch at byte 0x'
- '${(address + i).toRadixString(16)}',
- );
- _fail(failure);
- throw failure;
- }
- }
- // Reserve completion for a successfully acknowledged LEAVE_PROGMODE.
- onProgress?.call((page + 1) / (pageCount + 1));
- }
- await _exchange([0x51, 0x20]);
- _finished = true;
- onProgress?.call(1);
- } catch (error) {
- _fail(
- error is FirmwareUpdateException
- ? error
- : FirmwareUpdateException(
- FirmwareUpdateError.transport,
- 'Firmware update interrupted',
- cause: error,
- ),
- );
- rethrow;
- } finally {
- _flashing = false;
- }
- }
- Future<void> dispose() async {
- if (_disposed) return;
- _disposed = true;
- _fail(
- const FirmwareUpdateException(
- FirmwareUpdateError.disposed,
- 'Programmer has been disposed',
- ),
- );
- await _subscription.cancel();
- }
- }
|