Fase 3 ยท Minggu 10

Proyek: Smart Home Controller via BLE

Proyek lengkap: kontrol relay + monitoring sensor DHT11 via BLE dengan error handling.

Arsitektur Proyek

DHT11 Suhu + Hum LDR Cahaya Relay GPIO 26 LED GPIO 2 ESP32 BLE Server 3 Services 5 Characteristics Smart Home ๐ŸŒก๏ธ 27.5ยฐC Suhu ๐Ÿ’ง 65% Hum ๐Ÿ’ก LED โšก Relay BLE Connected โœ“ Features: โœ“ Suhu & kelembaban โœ“ Level cahaya โœ“ Toggle LED โœ“ Toggle relay โœ“ Connection status โœ“ Auto reconnect โœ“ Error handling

Proyek Smart Home: Sensor + Aktuator + BLE + Flutter Dashboard

Error Handling & Reconnect

Di dunia nyata, koneksi BLE bisa terputus. Kita harus menangani error dengan baik.

Pola Error Handling:

Dart// 1. Connection with timeout
Future<void> _connectWithRetry(BluetoothDevice device) async {
  int retries = 3;
  while (retries > 0) {
    try {
      await device.connect(timeout: const Duration(seconds: 10));
      setState(() => _connected = true);
      return;
    } catch (e) {
      retries--;
      if (retries == 0) {
        setState(() => _status = 'Connection failed after 3 retries');
      }
      await Future.delayed(const Duration(seconds: 2));
    }
  }
}

// 2. Listen for disconnection
device.connectionState.listen((state) {
  if (state == BluetoothConnectionState.disconnected) {
    setState(() {
      _connected = false;
      _status = 'Disconnected โ€” tap to reconnect';
    });
  }
});

// 3. Safe write with error handling
Future<void> _safeWrite(BluetoothCharacteristic char, String value) async {
  try {
    await char.write(utf8.encode(value), withoutResponse: false);
  } catch (e) {
    setState(() => _status = 'Write failed: $e');
  }
}
Connected lost! Disconnected auto Retrying... Reconnect! UI Connection States: Connected Disconnected Reconnecting Scanning

Connection state machine: connected โ†” disconnected (auto retry)

Rangkaian Hardware

ESP32 GPIO 4 โ†’ GPIO 34 โ†’ GPIO 2 โ†’ GPIO 26 โ†’ GND โ†’ 3V3 โ†’ DHT11 VCC|DATA|GND LDR + Resistor 10Kฮฉ LED + Resistor 220ฮฉ Relay 1-Channel ๐Ÿ’ก Lamp

Rangkaian lengkap: ESP32 + DHT11 + LDR + LED + Relay

KomponenPin ESP32Catatan
DHT11 DATAGPIO 4+ pull-up 10Kฮฉ ke 3V3
LDRGPIO 34Voltage divider dengan 10Kฮฉ
LEDGPIO 2Seri dengan resistor 220ฮฉ
Relay INGPIO 26VCC ke 5V (VIN)
DHT11 VCC3V3โ€”
Semua GNDGNDCommon ground

Checklist Minggu 10

๐Ÿ’ก Selesai Fase 3! Kamu sudah menguasai koneksi Bluetooth. Minggu depan kita mulai koneksi WiFi / Access Point โ€” jarak lebih jauh dan bisa multi-device! ๐ŸŽ‰