Proyek lengkap: kontrol relay + monitoring sensor DHT11 via BLE dengan error handling.
Proyek Smart Home: Sensor + Aktuator + BLE + Flutter Dashboard
Di dunia nyata, koneksi BLE bisa terputus. Kita harus menangani error dengan baik.
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');
}
}
Connection state machine: connected โ disconnected (auto retry)
Rangkaian lengkap: ESP32 + DHT11 + LDR + LED + Relay
| Komponen | Pin ESP32 | Catatan |
|---|---|---|
| DHT11 DATA | GPIO 4 | + pull-up 10Kฮฉ ke 3V3 |
| LDR | GPIO 34 | Voltage divider dengan 10Kฮฉ |
| LED | GPIO 2 | Seri dengan resistor 220ฮฉ |
| Relay IN | GPIO 26 | VCC ke 5V (VIN) |
| DHT11 VCC | 3V3 | โ |
| Semua GND | GND | Common ground |