TKK_E32222428/lib/screens/control_settings_screen.dart

303 lines
11 KiB
Dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/mqtt_service.dart';
import '../services/supabase_service.dart';
class ControlSettingsScreen extends StatefulWidget {
const ControlSettingsScreen({super.key});
@override
State<ControlSettingsScreen> createState() => _ControlSettingsScreenState();
}
class _ControlSettingsScreenState extends State<ControlSettingsScreen> {
int _operatingMode = 0; // 0 = otomatis, 1 = manual
final TextEditingController _tempMinController = TextEditingController();
final TextEditingController _tempMaxController = TextEditingController();
final TextEditingController _humMinController = TextEditingController();
final TextEditingController _humMaxController = TextEditingController();
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadSettings();
}
@override
void dispose() {
_tempMinController.dispose();
_tempMaxController.dispose();
_humMinController.dispose();
_humMaxController.dispose();
super.dispose();
}
Future<void> _loadSettings() async {
try {
final prefs = await SharedPreferences.getInstance();
final data = await SupabaseService().getBatasSensor();
if (data != null && mounted) {
setState(() {
_tempMinController.text = data['suhu_min'].toString();
_tempMaxController.text = data['suhu_max'].toString();
_humMinController.text = data['rh_min'].toString();
_humMaxController.text = data['rh_max'].toString();
_operatingMode = prefs.getInt('op_mode') ?? 1;
_isLoading = false;
});
}
} catch (e) {
debugPrint('Error loading settings: $e');
if (mounted) setState(() => _isLoading = false);
}
}
Future<void> _saveSettings() async {
if (_tempMinController.text.isEmpty ||
_tempMaxController.text.isEmpty ||
_humMinController.text.isEmpty ||
_humMaxController.text.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Semua kolom batas harus diisi!'),
backgroundColor: Colors.orange,
),
);
return;
}
final suhuMin = double.tryParse(_tempMinController.text) ?? 30;
final suhuMax = double.tryParse(_tempMaxController.text) ?? 45;
final rhMin = double.tryParse(_humMinController.text) ?? 60;
final rhMax = double.tryParse(_humMaxController.text) ?? 70;
// Validasi logika
if (suhuMin >= suhuMax) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Suhu min harus lebih kecil dari suhu max!'),
backgroundColor: Colors.orange,
),
);
return;
}
if (rhMin >= rhMax) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('RH min harus lebih kecil dari RH max!'),
backgroundColor: Colors.orange,
),
);
return;
}
final mqtt = Provider.of<MqttService>(context, listen: false);
final prefs = await SharedPreferences.getInstance();
setState(() => _isLoading = true);
try {
// Simpan mode ke local storage
await prefs.setInt('op_mode', _operatingMode);
// Kirim batas sensor ke ESP32 via MQTT → Flow 5 simpan ke Supabase
mqtt.setBatasSensor(suhuMin, suhuMax, rhMin, rhMax);
// Kirim mode ke ESP32
mqtt.gantiMode(_operatingMode == 0 ? "otomatis" : "manual");
// Update Supabase langsung juga sebagai backup
await SupabaseService().updateBatasSensor(suhuMin, suhuMax, rhMin, rhMax);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('✅ Pengaturan Tersimpan & Terkirim ke ESP32'),
backgroundColor: Colors.green,
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('❌ Gagal: $e'),
backgroundColor: Colors.red,
),
);
}
} finally {
if (mounted) setState(() => _isLoading = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child: _isLoading
? const Center(
child: CircularProgressIndicator(color: Colors.green))
: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Pengaturan',
style: TextStyle(
color: Colors.white,
fontSize: 32,
fontWeight: FontWeight.bold),
),
const Text(
'Batas Sensor & Mode Operasi',
style: TextStyle(color: Colors.grey, fontSize: 16),
),
const SizedBox(height: 30),
// ── Batas Suhu ──
Row(
children: [
Expanded(child: _buildInputCard(
'Suhu Min (°C)', '30', _tempMinController)),
const SizedBox(width: 10),
Expanded(child: _buildInputCard(
'Suhu Max (°C)', '45', _tempMaxController)),
],
),
const SizedBox(height: 15),
// ── Batas RH ──
Row(
children: [
Expanded(child: _buildInputCard(
'RH Min (%)', '60', _humMinController)),
const SizedBox(width: 10),
Expanded(child: _buildInputCard(
'RH Max (%)', '70', _humMaxController)),
],
),
const SizedBox(height: 20),
// ── Mode Operasi ──
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: const Color(0xFF1A1A1A),
borderRadius: BorderRadius.circular(20),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Mode Operasi',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 16)),
const SizedBox(height: 10),
RadioListTile<int>(
value: 0,
groupValue: _operatingMode,
onChanged: (val) =>
setState(() => _operatingMode = val!),
title: const Text('Mode Otomatis',
style: TextStyle(color: Colors.white)),
activeColor: Colors.green,
subtitle: const Text(
'Kipas bekerja otomatis berdasarkan sensor',
style: TextStyle(
color: Colors.grey, fontSize: 10),
),
),
RadioListTile<int>(
value: 1,
groupValue: _operatingMode,
onChanged: (val) =>
setState(() => _operatingMode = val!),
title: const Text('Mode Manual',
style: TextStyle(color: Colors.white)),
activeColor: Colors.green,
subtitle: const Text(
'Kontrol penuh kipas melalui dashboard HP',
style: TextStyle(
color: Colors.grey, fontSize: 10),
),
),
],
),
),
const SizedBox(height: 20),
// ── Tombol Simpan ──
SizedBox(
width: double.infinity,
height: 55,
child: ElevatedButton(
onPressed: _saveSettings,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
),
child: const Text(
'Simpan & Kirim ke ESP32',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white),
),
),
),
const SizedBox(height: 100),
],
),
),
),
),
);
}
Widget _buildInputCard(
String title, String hint, TextEditingController controller) {
return Container(
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
color: const Color(0xFF1A1A1A),
borderRadius: BorderRadius.circular(20),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.bold)),
const SizedBox(height: 10),
TextField(
controller: controller,
keyboardType: TextInputType.number,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
hintText: hint,
hintStyle: const TextStyle(color: Colors.grey),
filled: true,
fillColor: Colors.black,
isDense: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(color: Colors.grey),
),
),
),
],
),
);
}
}