684 lines
33 KiB
Dart
684 lines
33 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:provider/provider.dart';
|
|
import '../services/mqtt_service.dart';
|
|
import '../services/supabase_service.dart';
|
|
import 'package:supabase_flutter/supabase_flutter.dart';
|
|
import '../constants/app_colors.dart';
|
|
import '../services/recording_service.dart'; // Memori Abadi Timer Tetap Dipakai
|
|
import 'dart:io';
|
|
import 'dart:convert';
|
|
import 'package:archive/archive_io.dart';
|
|
import 'package:path_provider/path_provider.dart';
|
|
import 'package:share_plus/share_plus.dart';
|
|
import 'package:http/http.dart' as http;
|
|
|
|
class RecordingScreen extends StatefulWidget {
|
|
const RecordingScreen({super.key});
|
|
|
|
@override
|
|
State<RecordingScreen> createState() => _RecordingScreenState();
|
|
}
|
|
|
|
class _RecordingScreenState extends State<RecordingScreen> {
|
|
final TextEditingController _intervalController = TextEditingController();
|
|
List<Map<String, dynamic>> _gallery = [];
|
|
bool _isLoading = true;
|
|
bool _isSelectionMode = false;
|
|
final Set<int> _selectedIndices = {}; // Menyimpan index foto yang dicentang
|
|
|
|
final recordingService = RecordingService();
|
|
late final RealtimeChannel _channel;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_loadData();
|
|
|
|
_channel = Supabase.instance.client
|
|
.channel('realtime-foto')
|
|
.onPostgresChanges(
|
|
event: PostgresChangeEvent.insert,
|
|
schema: 'public',
|
|
table: 'foto_dataset',
|
|
callback: (payload) {
|
|
_loadData();
|
|
},
|
|
)
|
|
.subscribe();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_intervalController.dispose();
|
|
Supabase.instance.client.removeChannel(_channel);
|
|
super.dispose();
|
|
}
|
|
|
|
Future<void> _loadData() async {
|
|
setState(() => _isLoading = true);
|
|
try {
|
|
final interval = await SupabaseService().getIntervalSetting();
|
|
final images = await SupabaseService().getFotoDataset();
|
|
if (mounted) {
|
|
setState(() {
|
|
_intervalController.text = interval.toString();
|
|
_gallery = images.reversed.toList();
|
|
_isLoading = false;
|
|
});
|
|
}
|
|
} catch (e) {
|
|
debugPrint('Error loading recording data: $e');
|
|
if (mounted) setState(() => _isLoading = false);
|
|
}
|
|
}
|
|
|
|
Future<void> _controlRecording(bool start) async {
|
|
final mqtt = Provider.of<MqttService>(context, listen: false);
|
|
final intervalVal = int.tryParse(_intervalController.text) ?? 30;
|
|
|
|
if (intervalVal <= 0) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(
|
|
content: Text('Interval harus lebih dari 0 menit!'),
|
|
backgroundColor: AppColors.warning,
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (start) {
|
|
await SupabaseService().updateIntervalSetting(intervalVal);
|
|
mqtt.setIntervalFoto(intervalVal);
|
|
recordingService.setRecordingStatus(true);
|
|
} else {
|
|
mqtt.setIntervalFoto(0);
|
|
recordingService.setRecordingStatus(false);
|
|
}
|
|
|
|
if (mounted) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(
|
|
content: Text(
|
|
start
|
|
? 'Perekaman dimulai — interval $intervalVal menit'
|
|
: 'Perekaman dihentikan',
|
|
style: const TextStyle(
|
|
color: Colors.white, fontWeight: FontWeight.bold),
|
|
),
|
|
backgroundColor: start ? AppColors.success : AppColors.error,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
floatingActionButton: _selectedIndices.isNotEmpty
|
|
? FloatingActionButton.extended(
|
|
onPressed: () => _downloadDatasetZip(),
|
|
backgroundColor: AppColors.primary,
|
|
icon: const Icon(Icons.download, color: Colors.white),
|
|
label: Text(
|
|
'Download ZIP (${_selectedIndices.length})',
|
|
style: const TextStyle(
|
|
color: Colors.white, fontWeight: FontWeight.bold),
|
|
),
|
|
)
|
|
: null,
|
|
backgroundColor: AppColors.background,
|
|
body: SafeArea(
|
|
child: _isLoading
|
|
? const Center(
|
|
child: CircularProgressIndicator(color: AppColors.primary))
|
|
: Padding(
|
|
padding: const EdgeInsets.all(20.0),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
const Text(
|
|
'Perekaman',
|
|
style: TextStyle(
|
|
color: AppColors.textMain,
|
|
fontSize: 32,
|
|
fontWeight: FontWeight.bold),
|
|
),
|
|
const Text(
|
|
'Dataset Citra Kopi',
|
|
style: TextStyle(
|
|
color: AppColors.textSecondary, fontSize: 16),
|
|
),
|
|
const SizedBox(height: 20),
|
|
|
|
// LISTENABLE BUILDER: Membuat timer kebal pindah halaman
|
|
ListenableBuilder(
|
|
listenable: recordingService,
|
|
builder: (context, child) {
|
|
final isRecording = recordingService.isRecording;
|
|
|
|
return Container(
|
|
padding: const EdgeInsets.all(20),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.cardBg,
|
|
borderRadius: BorderRadius.circular(20),
|
|
border: Border.all(
|
|
color: AppColors.textSecondary
|
|
.withValues(alpha: 0.15)),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
const Text(
|
|
'Interval Waktu (menit)',
|
|
style: TextStyle(
|
|
color: AppColors.textMain,
|
|
fontWeight: FontWeight.bold),
|
|
),
|
|
const SizedBox(height: 10),
|
|
TextField(
|
|
controller: _intervalController,
|
|
keyboardType: TextInputType.number,
|
|
style:
|
|
const TextStyle(color: AppColors.textMain),
|
|
decoration: InputDecoration(
|
|
hintText: '30',
|
|
hintStyle: const TextStyle(
|
|
color: AppColors.textSecondary),
|
|
filled: true,
|
|
fillColor: AppColors.background,
|
|
border: OutlineInputBorder(
|
|
borderRadius: BorderRadius.circular(15),
|
|
borderSide: BorderSide(
|
|
color: AppColors.textSecondary
|
|
.withValues(alpha: 0.3)),
|
|
),
|
|
focusedBorder: OutlineInputBorder(
|
|
borderRadius: BorderRadius.circular(15),
|
|
borderSide: const BorderSide(
|
|
color: AppColors.primary),
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(height: 15),
|
|
if (isRecording)
|
|
Container(
|
|
padding: const EdgeInsets.all(10),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.success
|
|
.withValues(alpha: 0.15),
|
|
borderRadius: BorderRadius.circular(10),
|
|
border:
|
|
Border.all(color: AppColors.success),
|
|
),
|
|
child: const Row(
|
|
children: [
|
|
Icon(Icons.circle,
|
|
color: AppColors.success, size: 10),
|
|
SizedBox(width: 8),
|
|
Text('Perekaman berjalan...',
|
|
style: TextStyle(
|
|
color: AppColors.success,
|
|
fontSize: 12,
|
|
fontWeight: FontWeight.bold)),
|
|
],
|
|
),
|
|
),
|
|
const SizedBox(height: 10),
|
|
Row(
|
|
children: [
|
|
Expanded(
|
|
child: ElevatedButton.icon(
|
|
onPressed: isRecording
|
|
? null
|
|
: () => _controlRecording(true),
|
|
icon: const Icon(Icons.play_arrow,
|
|
color: Colors.white),
|
|
label: const Text('Mulai',
|
|
style:
|
|
TextStyle(color: Colors.white)),
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: AppColors.primary,
|
|
disabledBackgroundColor: AppColors
|
|
.primary
|
|
.withValues(alpha: 0.3),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius:
|
|
BorderRadius.circular(12)),
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(width: 10),
|
|
Expanded(
|
|
child: ElevatedButton.icon(
|
|
onPressed: !isRecording
|
|
? null
|
|
: () => _controlRecording(false),
|
|
icon: const Icon(Icons.stop,
|
|
color: Colors.white),
|
|
label: const Text('Berhenti',
|
|
style:
|
|
TextStyle(color: Colors.white)),
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: AppColors.error,
|
|
disabledBackgroundColor: AppColors.error
|
|
.withValues(alpha: 0.3),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius:
|
|
BorderRadius.circular(12)),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
);
|
|
},
|
|
),
|
|
const SizedBox(height: 20),
|
|
|
|
// KODE BARU (Sudah Termasuk Tombol Checklist & Select All):
|
|
Row(
|
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
|
children: [
|
|
Expanded(
|
|
child: Text(
|
|
'Galeri Dataset (${_gallery.length} foto)',
|
|
style: const TextStyle(
|
|
color: AppColors.textMain,
|
|
fontSize: 18,
|
|
fontWeight: FontWeight.bold),
|
|
),
|
|
),
|
|
Row(
|
|
children: [
|
|
if (_isSelectionMode) ...[
|
|
IconButton(
|
|
icon: const Icon(Icons.select_all,
|
|
color: AppColors.primary),
|
|
tooltip: 'Pilih Semua',
|
|
onPressed: () {
|
|
setState(() {
|
|
if (_selectedIndices.length ==
|
|
_gallery.length) {
|
|
_selectedIndices
|
|
.clear(); // Batal pilih semua
|
|
} else {
|
|
_selectedIndices.addAll(List.generate(
|
|
_gallery.length,
|
|
(i) => i)); // Pilih semua
|
|
}
|
|
});
|
|
},
|
|
),
|
|
IconButton(
|
|
icon: const Icon(Icons.close,
|
|
color: AppColors.error),
|
|
tooltip: 'Batal Mode Seleksi',
|
|
onPressed: () => setState(() {
|
|
_isSelectionMode = false;
|
|
_selectedIndices.clear();
|
|
}),
|
|
),
|
|
] else ...[
|
|
IconButton(
|
|
icon: const Icon(Icons.checklist,
|
|
color: AppColors.primary),
|
|
tooltip: 'Pilih Foto',
|
|
onPressed: () =>
|
|
setState(() => _isSelectionMode = true),
|
|
),
|
|
IconButton(
|
|
icon: const Icon(Icons.refresh,
|
|
color: AppColors.primary),
|
|
onPressed: _loadData,
|
|
),
|
|
],
|
|
],
|
|
)
|
|
],
|
|
),
|
|
const SizedBox(height: 10),
|
|
|
|
Expanded(
|
|
child: _gallery.isEmpty
|
|
? const Center(
|
|
child: Text('Belum ada data citra',
|
|
style: TextStyle(
|
|
color: AppColors.textSecondary)),
|
|
)
|
|
: GridView.builder(
|
|
gridDelegate:
|
|
const SliverGridDelegateWithFixedCrossAxisCount(
|
|
crossAxisCount: 2,
|
|
crossAxisSpacing: 10,
|
|
mainAxisSpacing: 10,
|
|
),
|
|
itemCount: _gallery.length,
|
|
itemBuilder: (context, index) {
|
|
final item = _gallery[index];
|
|
final nomorFoto = _gallery.length - index;
|
|
|
|
// PENYARING WAKTU: Ubah 'T' jadi Spasi agar kodingan lamamu aman
|
|
String rawTime = item['timestamp'] ??
|
|
item['created_at'] ??
|
|
'';
|
|
String cleanTime = rawTime.replaceAll('T', ' ');
|
|
|
|
final tanggal = cleanTime.contains(' ')
|
|
? cleanTime.split(' ')[0]
|
|
: cleanTime;
|
|
final jam = cleanTime.contains(' ')
|
|
? cleanTime.split(' ')[1]
|
|
: '';
|
|
final jamSingkat =
|
|
jam.length >= 5 ? jam.substring(0, 5) : jam;
|
|
|
|
return GestureDetector(
|
|
// --- FITUR BARU: Logika Tahan & Klik ---
|
|
onLongPress: () {
|
|
setState(() {
|
|
_isSelectionMode = true;
|
|
_selectedIndices.add(index);
|
|
});
|
|
},
|
|
onTap: () {
|
|
if (_isSelectionMode) {
|
|
setState(() {
|
|
if (_selectedIndices.contains(index)) {
|
|
_selectedIndices.remove(index);
|
|
} else {
|
|
_selectedIndices.add(index);
|
|
}
|
|
});
|
|
} else {
|
|
// KODE LAMAMU TETAP AMAN DI SINI (Navigasi ke Detail)
|
|
Navigator.pushNamed(
|
|
context,
|
|
'/image_result',
|
|
arguments: {
|
|
'id': item['id'].toString(),
|
|
'date': tanggal,
|
|
'time': jamSingkat,
|
|
'temp': (item['suhu'] == 0 ||
|
|
item['suhu'] == null)
|
|
? '-'
|
|
: '${item['suhu']} °C',
|
|
'humidity': (item['kelembapan'] ==
|
|
0 ||
|
|
item['kelembapan'] == null)
|
|
? '-'
|
|
: '${item['kelembapan']} %',
|
|
'light': (item['intensitas'] == 0 ||
|
|
item['intensitas'] == null)
|
|
? '-'
|
|
: '${item['intensitas']} Lux',
|
|
'location': 'Gudang Pengering',
|
|
'intake': item['kipas1'] ?? 'OFF',
|
|
'exhaust': item['kipas2'] ?? 'OFF',
|
|
'url_foto': item['url_foto'] ?? '',
|
|
},
|
|
);
|
|
}
|
|
},
|
|
child: Stack(
|
|
children: [
|
|
// KODE WADAH FOTO LAMAMU (Hanya ditambah opacity saat dicentang)
|
|
Opacity(
|
|
opacity:
|
|
_selectedIndices.contains(index)
|
|
? 0.6
|
|
: 1.0,
|
|
child: Container(
|
|
decoration: BoxDecoration(
|
|
color: AppColors.cardBg,
|
|
borderRadius:
|
|
BorderRadius.circular(15),
|
|
border: Border.all(
|
|
color: _selectedIndices
|
|
.contains(index)
|
|
? AppColors.primary
|
|
: AppColors.textSecondary
|
|
.withValues(alpha: 0.15),
|
|
width: _selectedIndices
|
|
.contains(index)
|
|
? 2.0
|
|
: 1.0,
|
|
),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment:
|
|
CrossAxisAlignment.stretch,
|
|
children: [
|
|
Expanded(
|
|
flex: 3,
|
|
child: ClipRRect(
|
|
borderRadius:
|
|
const BorderRadius
|
|
.vertical(
|
|
top: Radius.circular(
|
|
14)),
|
|
child: item['url_foto'] !=
|
|
null
|
|
? Image.network(
|
|
item['url_foto'],
|
|
fit: BoxFit.cover,
|
|
errorBuilder:
|
|
(_, __, ___) =>
|
|
const Center(
|
|
child: Icon(
|
|
Icons
|
|
.broken_image,
|
|
color: AppColors
|
|
.textSecondary,
|
|
size: 40),
|
|
),
|
|
)
|
|
: const Center(
|
|
child: Icon(
|
|
Icons.image,
|
|
color: AppColors
|
|
.textSecondary,
|
|
size: 40),
|
|
),
|
|
),
|
|
),
|
|
Container(
|
|
padding:
|
|
const EdgeInsets.symmetric(
|
|
horizontal: 8,
|
|
vertical: 6),
|
|
decoration: const BoxDecoration(
|
|
color: Colors.transparent,
|
|
borderRadius:
|
|
BorderRadius.vertical(
|
|
bottom:
|
|
Radius.circular(
|
|
15)),
|
|
),
|
|
child: Row(
|
|
mainAxisAlignment:
|
|
MainAxisAlignment
|
|
.spaceBetween,
|
|
children: [
|
|
Container(
|
|
padding: const EdgeInsets
|
|
.symmetric(
|
|
horizontal: 6,
|
|
vertical: 2),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.primary
|
|
.withValues(
|
|
alpha: 0.15),
|
|
borderRadius:
|
|
BorderRadius
|
|
.circular(6),
|
|
),
|
|
child: Text(
|
|
'#$nomorFoto',
|
|
style: const TextStyle(
|
|
color: AppColors
|
|
.primary,
|
|
fontSize: 10,
|
|
fontWeight:
|
|
FontWeight
|
|
.bold),
|
|
),
|
|
),
|
|
Column(
|
|
crossAxisAlignment:
|
|
CrossAxisAlignment
|
|
.end,
|
|
children: [
|
|
Text(tanggal,
|
|
style: const TextStyle(
|
|
color: AppColors
|
|
.textSecondary,
|
|
fontSize: 8)),
|
|
Text(jamSingkat,
|
|
style: const TextStyle(
|
|
color: AppColors
|
|
.textMain,
|
|
fontSize: 10,
|
|
fontWeight:
|
|
FontWeight
|
|
.bold)),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
// --- FITUR BARU: Ikon Centang ---
|
|
if (_isSelectionMode)
|
|
Positioned(
|
|
top: 8,
|
|
right: 8,
|
|
child: Icon(
|
|
_selectedIndices.contains(index)
|
|
? Icons.check_circle
|
|
: Icons.radio_button_unchecked,
|
|
color:
|
|
_selectedIndices.contains(index)
|
|
? AppColors.primary
|
|
: Colors.white,
|
|
shadows: const [
|
|
Shadow(
|
|
blurRadius: 2.0,
|
|
color: Colors.black45)
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
},
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
// =====================================================================
|
|
// --- FITUR BARU: Fungsi Membuat ZIP dan Ekspor ---
|
|
// =====================================================================
|
|
Future<void> _downloadDatasetZip() async {
|
|
showDialog(
|
|
context: context,
|
|
barrierDismissible: false,
|
|
builder: (_) => AlertDialog(
|
|
content: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
const CircularProgressIndicator(color: AppColors.primary),
|
|
const SizedBox(height: 20),
|
|
Text('Mengunduh & Membungkus ${_selectedIndices.length} Data...',
|
|
textAlign: TextAlign.center),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
|
|
try {
|
|
final archive = Archive();
|
|
// Membuat header (judul kolom) untuk file Excel/CSV
|
|
String csvContent =
|
|
"Nama_File,Tanggal,Jam,Suhu(C),Kelembapan(%),Intensitas_Cahaya(Lux),Kipas_1,Kipas_2\n";
|
|
|
|
for (int index in _selectedIndices) {
|
|
final item = _gallery[index];
|
|
|
|
// Membersihkan format waktu
|
|
String rawTime = item['timestamp'] ?? item['created_at'] ?? '';
|
|
String cleanTime = rawTime.replaceAll('T', ' ');
|
|
final tanggal =
|
|
cleanTime.contains(' ') ? cleanTime.split(' ')[0] : cleanTime;
|
|
final jam = cleanTime.contains(' ') ? cleanTime.split(' ')[1] : '';
|
|
final jamSingkat = jam.length >= 5 ? jam.substring(0, 5) : jam;
|
|
|
|
// Nama file gambar
|
|
String fileName =
|
|
'IMG_${tanggal}_${jamSingkat.replaceAll(':', '-')}.jpg';
|
|
|
|
// Unduh gambar dari Supabase
|
|
if (item['url_foto'] != null &&
|
|
item['url_foto'].toString().isNotEmpty) {
|
|
final response = await http.get(Uri.parse(item['url_foto']));
|
|
if (response.statusCode == 200) {
|
|
archive.addFile(ArchiveFile(
|
|
fileName, response.bodyBytes.length, response.bodyBytes));
|
|
}
|
|
}
|
|
|
|
// Tambah baris data ke Excel/CSV
|
|
csvContent +=
|
|
"$fileName,$tanggal,$jamSingkat,${item['suhu']},${item['kelembapan']},${item['intensitas']},${item['kipas1'] ?? 'OFF'},${item['kipas2'] ?? 'OFF'}\n";
|
|
}
|
|
|
|
// Masukkan file CSV ke dalam ZIP
|
|
final csvBytes = utf8.encode(csvContent);
|
|
archive.addFile(
|
|
ArchiveFile("Data_Sensor_Dataset.csv", csvBytes.length, csvBytes));
|
|
|
|
// Proses kompresi file ZIP
|
|
final zipBytes = ZipEncoder().encode(archive);
|
|
|
|
// Simpan sementara di memori HP
|
|
final tempDir = await getTemporaryDirectory();
|
|
final zipPath = '${tempDir.path}/Dataset_Kopi_IoT.zip';
|
|
final zipFile = File(zipPath);
|
|
await zipFile.writeAsBytes(zipBytes!);
|
|
|
|
if (mounted) Navigator.pop(context); // Tutup loading dialog
|
|
|
|
// Buka popup Share/Save untuk disimpan ke HP pengguna
|
|
await Share.shareXFiles(
|
|
[XFile(zipPath)],
|
|
text:
|
|
'Ini adalah Dataset Kopi berformat ZIP. Ekstrak untuk melihat foto dan tabel Excel.',
|
|
);
|
|
|
|
// Reset mode seleksi
|
|
setState(() {
|
|
_isSelectionMode = false;
|
|
_selectedIndices.clear();
|
|
});
|
|
} catch (e) {
|
|
if (mounted) {
|
|
Navigator.pop(context);
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(
|
|
content: Text('Gagal membuat ZIP: $e'),
|
|
backgroundColor: AppColors.error),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|