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 bytes; IntelHexFirmware._(List bytes) : bytes = List.unmodifiable(bytes); factory IntelHexFirmware.parse(String source) { final data = {}; 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 = [ 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(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.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 Function(List) write; final Duration timeout; final Queue _buffer = Queue(); late final StreamSubscription> _subscription; Completer>? _reply; int _replyLength = 0; FirmwareUpdateException? _failure; bool _flashing = false; bool _disposed = false; bool _finished = false; FirmwareUpdater({ required this.write, required Stream> 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 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 = [ 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> _exchange( List command, { int responseLength = 0, }) async { if (_failure case final failure?) throw failure; final reply = Completer>(); _reply = reply; _replyLength = responseLength; try { final results = await Future.wait([ reply.future, Future.sync(() => write(List.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; } 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 _loadAddress(int byteAddress) async { final wordAddress = byteAddress ~/ 2; await _exchange([0x55, wordAddress & 0xff, wordAddress >> 8, 0x20]); } Future 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.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 dispose() async { if (_disposed) return; _disposed = true; _fail( const FirmwareUpdateException( FirmwareUpdateError.disposed, 'Programmer has been disposed', ), ); await _subscription.cancel(); } }