TKK_E32230206/lib/services/api_control_service.dart

128 lines
3.6 KiB
Dart

import 'package:dio/dio.dart';
import '../core/api_config.dart';
class ApiControlService {
final Dio _dio;
final String deviceId;
ApiControlService(this.deviceId, [Dio? dio]) : _dio = dio ?? Dio();
// ── Mode Operasi ─────────────────────────────────────────────
Future<String> getMode() async {
try {
final res = await _dio.get('${ApiConfig.baseUrl}/mode/$deviceId');
if (res.statusCode == 200 && res.data != null) {
return res.data['current_mode'] ?? 'auto';
}
return 'auto';
} catch (e) {
return 'auto';
}
}
Future<void> setMode(String mode) async {
try {
await _dio.post(
'${ApiConfig.baseUrl}/mode/$deviceId',
data: {'mode': mode},
);
} catch (e) {
throw Exception('Gagal mengubah mode: $e');
}
}
Future<Map<String, dynamic>> getThreshold() async {
try {
final res = await _dio.get('${ApiConfig.baseUrl}/threshold/$deviceId');
if (res.statusCode == 200 && res.data != null) {
return res.data;
}
throw Exception('Gagal memuat threshold');
} catch (e) {
throw Exception('Error: $e');
}
}
Future<void> updateThreshold(double tempMax, double humMax) async {
try {
await _dio.post(
'${ApiConfig.baseUrl}/threshold/$deviceId',
data: {
'temp_max': tempMax,
'hum_max': humMax,
},
);
} catch (e) {
throw Exception('Gagal update threshold: $e');
}
}
// ── Manual Control (Pompa) ───────────────────────────────────
Future<void> siramManual(int durationSeconds) async {
try {
await _dio.post(
'${ApiConfig.baseUrl}/schedule/$deviceId/now',
data: {'duration_s': durationSeconds},
);
} catch (e) {
throw Exception('Gagal menyalakan pompa: $e');
}
}
Future<void> stopPump() async {
try {
await _dio.post('${ApiConfig.baseUrl}/schedule/$deviceId/stop');
} catch (e) {
throw Exception('Gagal mematikan pompa: $e');
}
}
// ── Schedules (Jadwal) ───────────────────────────────────────
Future<List<dynamic>> getSchedules() async {
try {
final res = await _dio.get('${ApiConfig.baseUrl}/schedule/$deviceId');
if (res.statusCode == 200 && res.data != null) {
return res.data as List<dynamic>;
}
return [];
} catch (e) {
throw Exception('Gagal memuat jadwal: $e');
}
}
Future<Map<String, dynamic>> addSchedule(String cron, int durationSeconds, String label) async {
try {
final res = await _dio.post(
'${ApiConfig.baseUrl}/schedule/$deviceId',
data: {
'cron': cron,
'duration_s': durationSeconds,
'label': label,
},
);
if (res.statusCode == 200 || res.statusCode == 201) {
return res.data;
}
throw Exception('Gagal menambah jadwal');
} catch (e) {
throw Exception('Error tambah jadwal: $e');
}
}
Future<void> deleteSchedule(String id) async {
try {
await _dio.delete('${ApiConfig.baseUrl}/schedule/$id');
} catch (e) {
throw Exception('Gagal menghapus jadwal: $e');
}
}
Future<void> toggleSchedule(String id) async {
try {
await _dio.patch('${ApiConfig.baseUrl}/schedule/$id/toggle');
} catch (e) {
throw Exception('Gagal toggle jadwal: $e');
}
}
}