import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_reactive_ble/flutter_reactive_ble.dart'; import 'package:nordic_dfu/nordic_dfu.dart'; import 'package:nrf/app_subscription_state.dart'; class DFU extends StatefulWidget { final DiscoveredDevice device; final File file; const DFU({Key? key, required this.device, required this.file}) : super(key: key); @override State createState() => _State(); } class _State extends State with SubscriptionState { final ScrollController _scrollController = ScrollController(); final List _log = []; late int start; @override void initState() { super.initState(); doDfu(widget.device.id, widget.file.path); } _addLog(String msg) { setState(() { int now = DateTime.now().millisecondsSinceEpoch; _log.add("${(now - start).toString().padLeft(8, "0")} -- $msg"); _scrollController.jumpTo(_scrollController.position.maxScrollExtent); }); } Future doDfu(String deviceId, String filePath) async { await Future.delayed(const Duration(seconds: 3)); start = DateTime.now().millisecondsSinceEpoch; _addLog("DFU start!"); return await NordicDfu().startDfu( deviceId, filePath, fileInAsset: false, onEnablingDfuMode: (deviceAddress) { _addLog("EnablingDfuMode"); }, onDfuProcessStarted: (deviceAddress) { _addLog("DfuProcessStarted"); }, onDfuProcessStarting: (deviceAddress) { _addLog("DfuProcessStarting"); }, onDeviceConnecting: (deviceAddress) { _addLog("DeviceConnecting"); }, onDeviceConnected: (deviceAddress) { _addLog("DeviceConnected"); }, onDfuCompleted: (deviceAddress) { _addLog("DfuCompleted"); }, onFirmwareValidating: (deviceAddress) { _addLog("FirmwareValidating"); }, onProgressChanged: ( deviceAddress, percent, speed, avgSpeed, currentPart, partsTotal, ) { _addLog("ProgressChanged $percent ${speed.toStringAsFixed(2)} ${avgSpeed.toStringAsFixed(2)} $currentPart $partsTotal"); }, onError: ( String? deviceAddress, int? error, int? errorType, String? message, ) { _addLog("Error $error $errorType $message"); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("${widget.device.name}"), ), body: ListView.builder( controller: _scrollController, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4.0), child: Text(_log[index]), ); }, itemCount: _log.length, ), ); } }