TKK_E32230206/lib/models/sensor_model.dart

71 lines
2.1 KiB
Dart

/// Model untuk data sensor IoT (suhu, kelembapan, & debit air).
class SensorModel {
final double temperature;
final double humidity;
final double waterFlow;
final double waterVolume;
final bool relayOn;
final String mode;
final DateTime timestamp;
const SensorModel({
required this.temperature,
required this.humidity,
this.waterFlow = 0.0,
this.waterVolume = 0.0,
this.relayOn = false,
this.mode = 'auto',
required this.timestamp,
});
factory SensorModel.fromJson(Map<String, dynamic> json) {
return SensorModel(
temperature: (json['temperature'] as num?)?.toDouble() ?? 0.0,
humidity: (json['humidity'] as num?)?.toDouble() ?? 0.0,
waterFlow: (json['water_flow'] as num?)?.toDouble() ?? 0.0,
waterVolume: (json['water_volume'] as num?)?.toDouble() ?? 0.0,
relayOn: json['relay_state'] as bool? ?? false,
mode: json['mode'] as String? ?? 'auto',
timestamp: json['timestamp'] != null
? DateTime.parse(json['timestamp'] as String)
: (json['created_at'] != null
? DateTime.parse(json['created_at'] as String)
: DateTime.now()),
);
}
Map<String, dynamic> toJson() => {
'temperature': temperature,
'humidity': humidity,
'water_flow': waterFlow,
'water_volume': waterVolume,
'relay_state': relayOn,
'mode': mode,
'timestamp': timestamp.toIso8601String(),
};
SensorModel copyWith({
double? temperature,
double? humidity,
double? waterFlow,
double? waterVolume,
bool? relayOn,
String? mode,
DateTime? timestamp,
}) {
return SensorModel(
temperature: temperature ?? this.temperature,
humidity: humidity ?? this.humidity,
waterFlow: waterFlow ?? this.waterFlow,
waterVolume: waterVolume ?? this.waterVolume,
relayOn: relayOn ?? this.relayOn,
mode: mode ?? this.mode,
timestamp: timestamp ?? this.timestamp,
);
}
@override
String toString() =>
'SensorModel(temp: $temperature°C, hum: $humidity%, flow: $waterFlow L/min, vol: $waterVolume L, relay: $relayOn, mode: $mode, ts: $timestamp)';
}