TKK_E32220332/lib/screens/recording_screen.dart

338 lines
14 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);
// Trigger foto pertama langsung
mqtt.triggerFoto();
setState(() => _isRecording = true);
} else {
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: [
const Text(
'Galeri Citra Dataset',
style: 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];
return GestureDetector(
onTap: () => Navigator.pushNamed(
context,
'/image_result',
arguments: {
'id': item['id'].toString(),
'date': item['timestamp']
?.split(' ')[0] ??
'',
'time': item['timestamp']
?.split(' ')[1] ??
'',
'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),
image: item['url_foto'] != null
? DecorationImage(
image: NetworkImage(
item['url_foto']),
fit: BoxFit.cover,
)
: null,
),
child: item['url_foto'] == null
? const Center(
child: Icon(Icons.image,
color: Colors.grey,
size: 50),
)
: null,
),
);
},
),
),
],
),
),
),
);
}
}