TKK_E32220332/lib/screens/recording_screen.dart

392 lines
18 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';
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 _isRecording = false;
late final RealtimeChannel _channel;
@override
void initState() {
super.initState();
_loadData();
// 🔥 REALTIME LISTENER SUPABASE (AUTO REFRESH GALERI)
_channel = Supabase.instance.client
.channel('realtime-foto')
.onPostgresChanges(
event: PostgresChangeEvent.insert,
schema: 'public',
table: 'foto_dataset',
callback: (payload) {
_loadData(); // reload gallery otomatis saat foto baru masuk
},
)
.subscribe();
}
@override
void dispose() {
_intervalController.dispose();
// 🔥 MATIKAN REALTIME LISTENER
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;
_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: Colors.orange,
),
);
return;
}
if (start) {
// Simpan interval ke Supabase
await SupabaseService().updateIntervalSetting(intervalVal);
// Kirim interval ke ESP32 via MQTT
mqtt.setIntervalFoto(intervalVal);
setState(() => _isRecording = true);
} else {
// Kirim stop ke ESP32 Dev via MQTT
mqtt.setIntervalFoto(0);
setState(() => _isRecording = false);
}
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(start
? '📸 Perekaman dimulai — interval ${intervalVal} menit'
: '⏹ Perekaman dihentikan'),
backgroundColor: start ? Colors.green : Colors.red,
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child: _isLoading
? const Center(
child: CircularProgressIndicator(color: Colors.green))
: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// ── Header ──
const Text(
'Perekaman',
style: TextStyle(
color: Colors.white,
fontSize: 32,
fontWeight: FontWeight.bold),
),
const Text(
'Dataset Citra Kopi',
style: TextStyle(color: Colors.grey, fontSize: 16),
),
const SizedBox(height: 20),
// ── Panel Kontrol ──
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: const Color(0xFF1A1A1A),
borderRadius: BorderRadius.circular(20),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Interval Waktu (menit)',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),
),
const SizedBox(height: 10),
TextField(
controller: _intervalController,
keyboardType: TextInputType.number,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
hintText: '30',
hintStyle:
const TextStyle(color: Colors.grey),
filled: true,
fillColor: Colors.black,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide:
const BorderSide(color: Colors.grey),
),
),
),
const SizedBox(height: 15),
// Status perekaman
if (_isRecording)
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.green.withOpacity(0.1),
borderRadius: BorderRadius.circular(10),
border: Border.all(color: Colors.green),
),
child: const Row(
children: [
Icon(Icons.circle,
color: Colors.green, size: 10),
SizedBox(width: 8),
Text('Perekaman berjalan...',
style: TextStyle(
color: Colors.green,
fontSize: 12)),
],
),
),
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: Colors.green,
disabledBackgroundColor:
Colors.green.withOpacity(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: Colors.redAccent,
disabledBackgroundColor:
Colors.redAccent.withOpacity(0.3),
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(12),
),
),
),
),
],
),
],
),
),
const SizedBox(height: 20),
// ── Header Galeri ──
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Galeri Citra Dataset (${_gallery.length} foto)',
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold),
),
IconButton(
icon: const Icon(Icons.refresh,
color: Colors.green),
onPressed: _loadData,
),
],
),
const SizedBox(height: 10),
// ── Grid Galeri ──
Expanded(
child: _gallery.isEmpty
? const Center(
child: Text(
'Belum ada data citra',
style: TextStyle(color: Colors.grey),
),
)
: GridView.builder(
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemCount: _gallery.length,
itemBuilder: (context, index) {
final item = _gallery[index];
final nomorFoto = index + 1;
final timestamp = item['timestamp'] ?? '';
final tanggal = timestamp.contains(' ') ? timestamp.split(' ')[0] : timestamp;
final jam = timestamp.contains(' ') ? timestamp.split(' ')[1] : '';
final jamSingkat = jam.length >= 5 ? jam.substring(0, 5) : jam;
return GestureDetector(
onTap: () => Navigator.pushNamed(
context,
'/image_result',
arguments: {
'id': item['id'].toString(),
'date': tanggal,
'time': jam,
'temp': '${item['suhu']} °C',
'humidity': '${item['kelembapan']} %',
'light': '${item['intensitas']} Lux',
'location': 'Gudang Pengering',
'intake': item['kipas1'] ?? 'OFF',
'exhaust': item['kipas2'] ?? 'OFF',
'url_foto': item['url_foto'] ?? '',
},
),
child: Container(
decoration: BoxDecoration(
color: const Color(0xFF1A1A1A),
borderRadius: BorderRadius.circular(15),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Foto 75% tinggi card
Expanded(
flex: 3,
child: ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(15)),
child: item['url_foto'] != null
? Image.network(
item['url_foto'],
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => const Center(
child: Icon(Icons.broken_image, color: Colors.grey, size: 40),
),
loadingBuilder: (_, child, progress) {
if (progress == null) return child;
return const Center(
child: CircularProgressIndicator(color: Colors.green, strokeWidth: 2),
);
},
)
: const Center(
child: Icon(Icons.image, color: Colors.grey, size: 40),
),
),
),
// Caption bawah foto
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
decoration: const BoxDecoration(
color: Color(0xFF1A1A1A),
borderRadius: BorderRadius.vertical(bottom: Radius.circular(15)),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// Badge nomor foto
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.green.withOpacity(0.2),
borderRadius: BorderRadius.circular(6),
border: Border.all(color: Colors.green.withOpacity(0.5)),
),
child: Text(
'#$nomorFoto',
style: const TextStyle(
color: Colors.green, fontSize: 10, fontWeight: FontWeight.bold),
),
),
// Tanggal dan jam
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(tanggal,
style: const TextStyle(color: Colors.grey, fontSize: 8)),
Text(jamSingkat,
style: const TextStyle(
color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold)),
],
),
],
),
),
],
),
),
);
},
),
),
],
),
),
),
);
}
}