fix: remove unused variables and field
Build Release AAB / build (push) Canceled after 46s

This commit is contained in:
andrew committed 2026-09-16 10:42:11 +07:00
1 parent a463066573
commit ada8422d1d
2 files changed
+972 -975

No files matched your search

+351 -351
View File
@@ -1,351 +1,351 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../services/ble_service.dart'; import '../services/ble_service.dart';
class CLIScreen extends StatefulWidget { class CLIScreen extends StatefulWidget {
const CLIScreen({super.key}); const CLIScreen({super.key});
@override @override
State<CLIScreen> createState() => _CLIScreenState(); State<CLIScreen> createState() => _CLIScreenState();
} }
class _CLIScreenState extends State<CLIScreen> { class _CLIScreenState extends State<CLIScreen> {
final ScrollController _scrollController = ScrollController(); final ScrollController _scrollController = ScrollController();
final List<String> _logLines = []; final List<String> _logLines = [];
Timer? _statusTimer; Timer? _statusTimer;
bool _autoScroll = true; bool _autoScroll = true;
int _lastProcessedPacket = 0; int _lastProcessedPacket = 0;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_addHeader(); _addHeader();
_startStatusTimer(); _startStatusTimer();
} }
@override @override
void dispose() { void dispose() {
_statusTimer?.cancel(); _statusTimer?.cancel();
_scrollController.dispose(); _scrollController.dispose();
super.dispose(); super.dispose();
} }
String _repeatChar(String char, int count) { String _repeatChar(String char, int count) {
return List.filled(count, char).join(); return List.filled(count, char).join();
} }
void _addHeader() { void _addHeader() {
_addLogLine(_repeatChar('=', 70)); _addLogLine(_repeatChar('=', 70));
_addLogLine('Enhanced with automatic reconnection'); _addLogLine('Enhanced with automatic reconnection');
_addLogLine(_repeatChar('=', 70)); _addLogLine(_repeatChar('=', 70));
_addLogLine(''); _addLogLine('');
} }
void _addLogLine(String line) { void _addLogLine(String line) {
setState(() { setState(() {
_logLines.add(line); _logLines.add(line);
// Keep last 5000 lines // Keep last 5000 lines
if (_logLines.length > 5000) { if (_logLines.length > 5000) {
_logLines.removeAt(0); _logLines.removeAt(0);
} }
}); });
if (_autoScroll) { if (_autoScroll) {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) { if (_scrollController.hasClients) {
_scrollController.jumpTo(_scrollController.position.maxScrollExtent); _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
} }
}); });
} }
} }
void _startStatusTimer() { void _startStatusTimer() {
_statusTimer = Timer.periodic(const Duration(seconds: 1), (timer) { _statusTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (mounted) { if (mounted) {
final ble = Provider.of<BLEService>(context, listen: false); final ble = Provider.of<BLEService>(context, listen: false);
if (ble.isConnected) { if (ble.isConnected) {
_updateStatus(ble); _updateStatus(ble);
} }
} }
}); });
} }
void _updateStatus(BLEService ble) { void _updateStatus(BLEService ble) {
final stats = _getStatistics(ble); final stats = _getStatistics(ble);
final elapsed = stats['elapsed'] as double; final elapsed = stats['elapsed'] as double;
final packets = stats['packets'] as int; final packets = stats['packets'] as int;
final rate = stats['rate'] as double; final rate = stats['rate'] as double;
final connStatus = ble.isConnected ? '✓' : '✗'; final connStatus = ble.isConnected ? '✓' : '✗';
// Remove old status line if exists (lines ending with specific pattern) // Remove old status line if exists (lines ending with specific pattern)
if (_logLines.isNotEmpty && _logLines.last.startsWith('[STATUS]')) { if (_logLines.isNotEmpty && _logLines.last.startsWith('[STATUS]')) {
_logLines.removeLast(); _logLines.removeLast();
} }
if (packets > 0) { if (packets > 0) {
_addLogLine( _addLogLine(
'[STATUS] Packets: ${packets.toString().padLeft(5)} | ' '[STATUS] Packets: ${packets.toString().padLeft(5)} | '
'Rate: ${rate.toStringAsFixed(2).padLeft(5)} pkt/s | ' 'Rate: ${rate.toStringAsFixed(2).padLeft(5)} pkt/s | '
'Time: ${elapsed.toStringAsFixed(1).padLeft(7)}s | ' 'Time: ${elapsed.toStringAsFixed(1).padLeft(7)}s | '
'Conn: $connStatus', 'Conn: $connStatus',
); );
} else { } else {
_addLogLine('[STATUS] Waiting for data... (${elapsed.toStringAsFixed(1)}s)'); _addLogLine('[STATUS] Waiting for data... (${elapsed.toStringAsFixed(1)}s)');
} }
} }
Map<String, dynamic> _getStatistics(BLEService ble) { Map<String, dynamic> _getStatistics(BLEService ble) {
final now = DateTime.now(); final now = DateTime.now();
final startTime = ble.streamingDuration != null final startTime = ble.streamingDuration != null
? now.subtract(ble.streamingDuration!) ? now.subtract(ble.streamingDuration!)
: now; : now;
final elapsed = now.difference(startTime).inMilliseconds / 1000.0; final elapsed = now.difference(startTime).inMilliseconds / 1000.0;
final packets = ble.packetCount; final packets = ble.packetCount;
final rate = elapsed > 0 ? packets / elapsed : 0.0; final rate = elapsed > 0 ? packets / elapsed : 0.0;
return { return {
'elapsed': elapsed, 'elapsed': elapsed,
'packets': packets, 'packets': packets,
'rate': rate, 'rate': rate,
}; };
} }
String _formatTimestamp(DateTime dt) { String _formatTimestamp(DateTime dt) {
return '${dt.hour.toString().padLeft(2, '0')}:' return '${dt.hour.toString().padLeft(2, '0')}:'
'${dt.minute.toString().padLeft(2, '0')}:' '${dt.minute.toString().padLeft(2, '0')}:'
'${dt.second.toString().padLeft(2, '0')}'; '${dt.second.toString().padLeft(2, '0')}';
} }
void _onDataReceived(DataPacket packet) { void _onDataReceived(DataPacket packet) {
final timestamp = _formatTimestamp(packet.timestamp); final timestamp = _formatTimestamp(packet.timestamp);
final hexData = packet.hexString; final hexData = packet.hexString;
final packetNum = packet.packetNumber; final packetNum = packet.packetNumber;
final bytes = packet.data.length; final bytes = packet.data.length;
_addLogLine(''); _addLogLine('');
_addLogLine('[$timestamp] Packet #${packetNum.toString().padLeft(5, '0')}: $hexData ($bytes bytes)'); _addLogLine('[$timestamp] Packet #${packetNum.toString().padLeft(5, '0')}: $hexData ($bytes bytes)');
// Parse data formats (matching Python example) // Parse data formats (matching Python example)
if (packet.data.length >= 4) { if (packet.data.length >= 4) {
try { try {
final valueU32 = packet.value32BitUnsigned; // valueU32 = packet.value32BitUnsigned;
final valueS32 = packet.value32BitSigned; // valueS32 = packet.value32BitSigned;
final valueU16 = packet.value16BitUnsigned; // valueU16 = packet.value16BitUnsigned;
final valueS16 = packet.value16BitSigned; // valueS16 = packet.value16BitSigned;
// Commented out like in Python example // Commented out like in Python example
// _addLogLine(' → 32-bit unsigned: ${valueU32.toString().padLeft(10)} | 32-bit signed: ${valueS32.toString().padLeft(10)}'); // _addLogLine(' → 32-bit unsigned: ${valueU32.toString().padLeft(10)} | 32-bit signed: ${valueS32.toString().padLeft(10)}');
// _addLogLine(' → 16-bit unsigned: ${valueU16.toString().padLeft(10)} | 16-bit signed: ${valueS16.toString().padLeft(10)}'); // _addLogLine(' → 16-bit unsigned: ${valueU16.toString().padLeft(10)} | 16-bit signed: ${valueS16.toString().padLeft(10)}');
if (valueU32 != null && valueU32 > 0) { // if (valueU32 != null && valueU32 > 0) {
final floatVal = valueU32 / 100.0; // final floatVal = valueU32 / 100.0;
// _addLogLine(' → As float (÷100): ${floatVal.toStringAsFixed(2).padLeft(12)}'); // _addLogLine(' → As float (÷100): ${floatVal.toStringAsFixed(2).padLeft(12)}');
} // }
} catch (e) { } catch (e) {
_addLogLine(' → Parse error: $e'); _addLogLine(' → Parse error: $e');
} }
} }
// Show weight as 'timbang' in KG (matching Python example) // Show weight as 'timbang' in KG (matching Python example)
final weightKg = packet.weightKg; final weightKg = packet.weightKg;
if (weightKg != null) { if (weightKg != null) {
_addLogLine(' → timbang : ${weightKg.toStringAsFixed(1)} KG'); _addLogLine(' → timbang : ${weightKg.toStringAsFixed(1)} KG');
} else { } else {
// Fallback to showing raw bytes in decimal // Fallback to showing raw bytes in decimal
final byteStr = packet.data.map((b) => b.toString().padLeft(2, '0')).join(' '); final byteStr = packet.data.map((b) => b.toString().padLeft(2, '0')).join(' ');
_addLogLine(' → timbang : $byteStr'); _addLogLine(' → timbang : $byteStr');
} }
// Try to decode as ASCII if printable // Try to decode as ASCII if printable
final asciiStr = packet.asciiString; final asciiStr = packet.asciiString;
if (asciiStr != null && asciiStr.isNotEmpty) { if (asciiStr != null && asciiStr.isNotEmpty) {
_addLogLine(" → ASCII: '$asciiStr'"); _addLogLine(" → ASCII: '$asciiStr'");
} }
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
backgroundColor: Colors.black, backgroundColor: Colors.black,
appBar: AppBar( appBar: AppBar(
title: const Text('SIAB Bluetooth CLI', style: TextStyle(color: Colors.green)), title: const Text('SIAB Bluetooth CLI', style: TextStyle(color: Colors.green)),
backgroundColor: Colors.grey[900], backgroundColor: Colors.grey[900],
iconTheme: const IconThemeData(color: Colors.green), iconTheme: const IconThemeData(color: Colors.green),
actions: [ actions: [
Consumer<BLEService>( Consumer<BLEService>(
builder: (context, ble, _) { builder: (context, ble, _) {
if (ble.isConnected) { if (ble.isConnected) {
return IconButton( return IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.green), icon: const Icon(Icons.delete_outline, color: Colors.green),
tooltip: 'Clear Log', tooltip: 'Clear Log',
onPressed: () { onPressed: () {
setState(() { setState(() {
_logLines.clear(); _logLines.clear();
_addHeader(); _addHeader();
}); });
ble.clearData(); ble.clearData();
}, },
); );
} }
return const SizedBox.shrink(); return const SizedBox.shrink();
}, },
), ),
IconButton( IconButton(
icon: Icon( icon: Icon(
_autoScroll ? Icons.vertical_align_bottom : Icons.vertical_align_center, _autoScroll ? Icons.vertical_align_bottom : Icons.vertical_align_center,
color: Colors.green, color: Colors.green,
), ),
tooltip: _autoScroll ? 'Disable Auto-scroll' : 'Enable Auto-scroll', tooltip: _autoScroll ? 'Disable Auto-scroll' : 'Enable Auto-scroll',
onPressed: () { onPressed: () {
setState(() { setState(() {
_autoScroll = !_autoScroll; _autoScroll = !_autoScroll;
}); });
}, },
), ),
], ],
), ),
body: Consumer<BLEService>( body: Consumer<BLEService>(
builder: (context, ble, _) { builder: (context, ble, _) {
// Process new data packets // Process new data packets
if (ble.dataPackets.isNotEmpty) { if (ble.dataPackets.isNotEmpty) {
final newPackets = ble.dataPackets final newPackets = ble.dataPackets
.where((p) => p.packetNumber > _lastProcessedPacket) .where((p) => p.packetNumber > _lastProcessedPacket)
.toList(); .toList();
for (final packet in newPackets) { for (final packet in newPackets) {
_onDataReceived(packet); _onDataReceived(packet);
_lastProcessedPacket = packet.packetNumber; _lastProcessedPacket = packet.packetNumber;
} }
} else { } else {
_lastProcessedPacket = 0; _lastProcessedPacket = 0;
} }
return Column( return Column(
children: [ children: [
// Connection status bar (terminal style) // Connection status bar (terminal style)
Container( Container(
width: double.infinity, width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
color: Colors.grey[900], color: Colors.grey[900],
child: Row( child: Row(
children: [ children: [
Icon( Icon(
ble.isConnected ? Icons.bluetooth_connected : Icons.bluetooth_disabled, ble.isConnected ? Icons.bluetooth_connected : Icons.bluetooth_disabled,
color: ble.isConnected ? Colors.green : Colors.red, color: ble.isConnected ? Colors.green : Colors.red,
size: 20, size: 20,
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
Text( Text(
ble.isConnected ble.isConnected
? 'Connected: ${ble.deviceName ?? ble.deviceAddress ?? "Unknown"}' ? 'Connected: ${ble.deviceName ?? ble.deviceAddress ?? "Unknown"}'
: 'Disconnected', : 'Disconnected',
style: const TextStyle( style: const TextStyle(
color: Colors.green, color: Colors.green,
fontFamily: 'monospace', fontFamily: 'monospace',
fontSize: 12, fontSize: 12,
), ),
), ),
const Spacer(), const Spacer(),
if (ble.isScanning || ble.isConnecting) if (ble.isScanning || ble.isConnecting)
const SizedBox( const SizedBox(
width: 16, width: 16,
height: 16, height: 16,
child: CircularProgressIndicator( child: CircularProgressIndicator(
strokeWidth: 2, strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Colors.green), valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
), ),
), ),
], ],
), ),
), ),
// Terminal output area // Terminal output area
Expanded( Expanded(
child: Container( child: Container(
color: Colors.black, color: Colors.black,
child: SingleChildScrollView( child: SingleChildScrollView(
controller: _scrollController, controller: _scrollController,
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: SelectableText( child: SelectableText(
_logLines.join('\n'), _logLines.join('\n'),
style: const TextStyle( style: const TextStyle(
color: Colors.green, color: Colors.green,
fontFamily: 'monospace', fontFamily: 'monospace',
fontSize: 12, fontSize: 12,
height: 1.4, height: 1.4,
), ),
), ),
), ),
), ),
), ),
// Bottom action bar // Bottom action bar
Container( Container(
width: double.infinity, width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
color: Colors.grey[900], color: Colors.grey[900],
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [ children: [
if (ble.isConnecting || ble.isScanning) if (ble.isConnecting || ble.isScanning)
const Text( const Text(
'Connecting...', 'Connecting...',
style: TextStyle(color: Colors.yellow, fontFamily: 'monospace'), style: TextStyle(color: Colors.yellow, fontFamily: 'monospace'),
) )
else if (ble.isConnected) else if (ble.isConnected)
ElevatedButton.icon( ElevatedButton.icon(
onPressed: () async { onPressed: () async {
_addLogLine('\n⏹ Disconnecting...'); _addLogLine('\n⏹ Disconnecting...');
await ble.disconnect(); await ble.disconnect();
ble.clearData(); ble.clearData();
_addLogLine('✅ Disconnected\n'); _addLogLine('✅ Disconnected\n');
}, },
icon: const Icon(Icons.bluetooth_disabled, size: 18), icon: const Icon(Icons.bluetooth_disabled, size: 18),
label: const Text('Disconnect'), label: const Text('Disconnect'),
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Colors.red[900], backgroundColor: Colors.red[900],
foregroundColor: Colors.white, foregroundColor: Colors.white,
), ),
) )
else else
ElevatedButton.icon( ElevatedButton.icon(
onPressed: () async { onPressed: () async {
_addLogLine('\n[1/3] Connecting to SIAB device...'); _addLogLine('\n[1/3] Connecting to SIAB device...');
final success = await ble.autoConnect(); final success = await ble.autoConnect();
if (success) { if (success) {
_addLogLine('✅ Connected successfully!'); _addLogLine('✅ Connected successfully!');
if (ble.deviceAddress != null) { if (ble.deviceAddress != null) {
_addLogLine(' Device address: ${ble.deviceAddress}'); _addLogLine(' Device address: ${ble.deviceAddress}');
} }
_addLogLine('\n[2/3] Enabling streaming data notifications...'); _addLogLine('\n[2/3] Enabling streaming data notifications...');
_addLogLine('✅ Notifications enabled!'); _addLogLine('✅ Notifications enabled!');
_addLogLine('\n[3/3] Receiving streaming data...'); _addLogLine('\n[3/3] Receiving streaming data...');
_addLogLine(_repeatChar('=', 70)); _addLogLine(_repeatChar('=', 70));
_addLogLine('Waiting for data packets...'); _addLogLine('Waiting for data packets...');
_addLogLine(''); _addLogLine('');
} else { } else {
_addLogLine('❌ Failed to connect!'); _addLogLine('❌ Failed to connect!');
_addLogLine('\nTroubleshooting:'); _addLogLine('\nTroubleshooting:');
_addLogLine(' • Make sure SIAB device is powered on'); _addLogLine(' • Make sure SIAB device is powered on');
_addLogLine(' • Check Bluetooth is enabled'); _addLogLine(' • Check Bluetooth is enabled');
_addLogLine(' • Verify device name is \'SIAB\''); _addLogLine(' • Verify device name is \'SIAB\'');
} }
}, },
icon: const Icon(Icons.bluetooth_searching, size: 18), icon: const Icon(Icons.bluetooth_searching, size: 18),
label: const Text('Connect'), label: const Text('Connect'),
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Colors.green[900], backgroundColor: Colors.green[900],
foregroundColor: Colors.white, foregroundColor: Colors.white,
), ),
), ),
], ],
), ),
), ),
], ],
); );
}, },
), ),
); );
} }
} }
File diff suppressed because it is too large. Load diff