Skip to content

Commit 793c07e

Browse files
committed
Added new lesson codes
1 parent 3e3a751 commit 793c07e

File tree

10 files changed

+202
-72
lines changed

10 files changed

+202
-72
lines changed

drone-lab/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ version = "0.1.0"
44
edition = "2024"
55

66
[dependencies]
7+
rand = "0.9.1"

drone-lab/src/controller/flight_controller.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@ pub struct FlightController;
44
#[allow(dead_code)]
55
impl FlightController {
66
pub fn check_status<'a>(drone: &'a Drone<'a>) -> DroneStatus<'a> {
7+
// Harici bir REST Api'den bilgileri çektiğimizi düşünelim.
8+
// Örneğin http://localhost:4980/drone/api/states/{id} HTTP Get
79
if !drone.is_alive {
810
return DroneStatus::Offline;
911
}
1012
if drone.energy_level < 30.0 {
11-
return DroneStatus::LowBattery(drone.energy_level);
13+
return DroneStatus::LowBattery(BatteryRate(drone.energy_level));
1214
}
1315
if drone.location.x > 800.0 || drone.location.y > 800.0 || drone.location.z > 800.0 {
1416
return DroneStatus::OutOffRange(drone.location);
@@ -22,6 +24,9 @@ impl FlightController {
2224
pub enum DroneStatus<'a> {
2325
OutOffRange(Location<'a>),
2426
Offline,
25-
LowBattery(f32),
27+
LowBattery(BatteryRate),
2628
Fine,
2729
}
30+
31+
#[derive(Debug, PartialEq)]
32+
pub struct BatteryRate(pub f32);
Lines changed: 58 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
1+
//! # Simulation Module
2+
//! Dron simulasyon nesnelerini oluşturan, yöneten modül enstrümanlarını içerir
3+
//!
4+
//! ## Structs
5+
//! * `SimulationController`
6+
17
use crate::data::*;
28
use crate::model::*;
9+
use rand::Rng;
10+
use std::fs::File;
11+
use std::io::Write;
312

413
#[allow(dead_code)]
514
pub struct SimulationController<'a> {
@@ -11,19 +20,39 @@ impl SimulationController<'_> {
1120
pub fn new() -> Self {
1221
SimulationController { drones: Vec::new() }
1322
}
23+
24+
/// # Drone Yükleme Fonksiyonu
25+
///
26+
/// Sahaya parametre olarak verilen sayıda drone ekler.
27+
///
28+
/// ## Arguments
29+
/// * `drone_count: i32` türünden drone sayısını ifade eder
30+
///
31+
/// ## Returns
32+
/// * `bool:` İşlemin başarılı olup olmadığı bilgisidir
33+
///
34+
/// ## Examples
35+
/// ```rust
36+
/// use crate::controller::SimulationController;
37+
///
38+
/// let mut simulator = SimulationController::new();
39+
/// let load_result = simulator.load(10);
40+
/// ```
1441
pub fn load(&mut self, drone_count: i32) -> bool {
42+
let mut rng = rand::rng();
43+
1544
for i in 0..drone_count {
16-
let model = DRONE_MODELS[get_random_number(DRONE_MODELS.len())];
45+
let model = DRONE_MODELS[rng.random_range(0..DRONE_MODELS.len())];
1746
self.drones.push(Drone {
1847
id: i as u32,
1948
energy_level: 100.0,
2049
model,
2150
is_alive: true,
2251
location: Location {
23-
x: get_random_between(1, 100) as f32,
24-
y: get_random_between(1, 100) as f32,
25-
z: get_random_between(1, 100) as f32,
26-
caption: "",
52+
x: rng.random_range(0..100) as f32,
53+
y: rng.random_range(0..100) as f32,
54+
z: rng.random_range(0..100) as f32,
55+
caption: LOCATION_CAPTIONS[rng.random_range(0..LOCATION_CAPTIONS.len())],
2756
},
2857
})
2958
}
@@ -33,6 +62,29 @@ impl SimulationController<'_> {
3362
self.drones.len()
3463
}
3564
pub fn get_random(&self) -> Drone {
36-
self.drones[0]
65+
let mut rng = rand::rng();
66+
self.drones[rng.random_range(0..self.drones.len())]
67+
}
68+
69+
pub fn save(&self, path: &str) -> std::io::Result<u32> {
70+
let mut content = String::new();
71+
for drone in &self.drones {
72+
content.push_str(format!("{}\n", &drone.to_string()).as_str());
73+
}
74+
75+
let mut f = File::create(path)?;
76+
// let mut f = OpenOptions::new().append(true).write(true).open(path)?;
77+
f.write_all(content.as_bytes())?;
78+
Ok(content.len() as u32)
79+
}
80+
81+
pub fn load_from(path: &str) -> std::io::Result<()> {
82+
//todo@buraksenyurt Aşağıdaki maddeler tamamlanmalı
83+
84+
// Dosya gerçekten var mı kontrolü?
85+
// Dosya içeriği dolu mu?
86+
// Dosya satırları gerçekten Drone verisi mi içeriyor mu? (Satır bazında yapılabilir)
87+
// Dosya satırlarını Drone türünden nesneler çevirip self üstünde vektöre eklemek lazım
88+
Ok(())
3789
}
3890
}

drone-lab/src/data/generator.rs

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
1-
use std::time::{SystemTime, UNIX_EPOCH};
2-
3-
pub fn get_random_number(max: usize) -> usize {
4-
let duration = SystemTime::now()
5-
.duration_since(UNIX_EPOCH)
6-
.expect("Error at duration calculation");
7-
8-
let nanos = duration.subsec_nanos() as usize;
9-
10-
if max == 0 { 0 } else { nanos % max }
11-
}
12-
13-
pub fn get_random_between(min: usize, max: usize) -> usize {
14-
if min > max {
15-
panic!("Min must be less than or equal to Max");
16-
}
17-
18-
let duration = SystemTime::now()
19-
.duration_since(UNIX_EPOCH)
20-
.expect("Error at duration calculation");
21-
22-
let nanos = duration.subsec_nanos() as usize;
23-
let range = max - min + 1;
24-
25-
min + (nanos % range)
26-
}
1+
// use std::time::{SystemTime, UNIX_EPOCH};
2+
//
3+
// pub fn get_random_number(max: usize) -> usize {
4+
// let duration = SystemTime::now()
5+
// .duration_since(UNIX_EPOCH)
6+
// .expect("Error at duration calculation");
7+
//
8+
// let nanos = duration.subsec_nanos() as usize;
9+
//
10+
// if max == 0 { 0 } else { nanos % max }
11+
// }
12+
//
13+
// pub fn get_random_between(min: usize, max: usize) -> usize {
14+
// if min > max {
15+
// panic!("Min must be less than or equal to Max");
16+
// }
17+
//
18+
// let duration = SystemTime::now()
19+
// .duration_since(UNIX_EPOCH)
20+
// .expect("Error at duration calculation");
21+
//
22+
// let nanos = duration.subsec_nanos() as usize;
23+
// let range = max - min + 1;
24+
//
25+
// min + (nanos % range)
26+
// }

drone-lab/src/data/mod.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@ pub const DRONE_MODELS: [&str; 10] = [
1111
"Acrobat-K",
1212
];
1313

14+
pub const LOCATION_CAPTIONS: [&str; 4] = [
15+
"Kat 1 - Kuzey Batı Kanadı",
16+
"Zemin Kat - Merkez",
17+
"Kat 3 - Doğu Kanadı",
18+
"Çatı Katı - Helikopter Pisti Merkez",
19+
];
20+
1421
mod generator;
1522

16-
pub use generator::*;
23+
// pub use generator::*;

drone-lab/src/main.rs

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,44 @@
1-
use data::{DRONE_MODELS, get_random_between, get_random_number};
1+
use crate::controller::SimulationController;
22

33
mod controller;
44
mod data;
55
mod model;
66
mod tests;
77

88
fn main() {
9-
//todo@buraksenyurt Derste yapılacaklar
9+
// todo@buraksenyurt Derste yapılacaklar
10+
// Aynı davranışları uygulayan farklı veri yapılarını kullanabilen generic bir Simulation modeli oluşturmayı deneyelim
1011

11-
// Başlangıçta sahaya belli sayıda rastgele ama makul koordinatlara çıkacak drone'lar yerleştirelim
12-
// Belirli periyotlarda sahadaki drone konumlarını terminale loglayalım
13-
// Terminal loglarını fiziki dosyaya kaydedelim
14-
// Programın bir sonraki açılışında son konumları dosyadan okuyalım
12+
let mut simulator = SimulationController::new();
1513

16-
for _ in 0..10 {
17-
let max_value = DRONE_MODELS.len();
18-
println!("{}", DRONE_MODELS[get_random_number(max_value)]);
14+
let load_result = simulator.load(10);
15+
if load_result {
16+
for _ in 0..3 {
17+
let drone = simulator.get_random();
18+
println!("{}", drone);
19+
}
1920
}
2021

21-
for _ in 0..10 {
22-
let number = get_random_between(10, 100);
23-
println!("{number}");
22+
match simulator.save("Drones.dat") {
23+
Ok(length) => {
24+
println!(
25+
"Veriler dosyaya aktarıldı. Toplam içerik boyutu {} karakter",
26+
length
27+
);
28+
}
29+
Err(e) => eprintln!("{}", e),
2430
}
31+
32+
// Terminal loglarını fiziki dosyaya kaydedelim
33+
// Programın bir sonraki açılışında son konumları dosyadan okuyalım
34+
35+
// for _ in 0..10 {
36+
// let max_value = DRONE_MODELS.len();
37+
// println!("{}", DRONE_MODELS[get_random_number(max_value)]);
38+
// }
39+
//
40+
// for _ in 0..10 {
41+
// let number = get_random_between(10, 100);
42+
// println!("{number}");
43+
// }
2544
}

drone-lab/src/model/drone.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::model::location::Location;
2+
use std::fmt::Display;
23

34
#[derive(Debug, Copy, Clone)]
45
#[allow(dead_code)]
@@ -9,3 +10,39 @@ pub struct Drone<'a> {
910
pub location: Location<'a>,
1011
pub is_alive: bool,
1112
}
13+
14+
impl Display for Drone<'_> {
15+
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
16+
write!(
17+
f,
18+
"{} ({}%),{},{}",
19+
self.model,
20+
self.energy_level,
21+
self.location,
22+
// self.location.x,
23+
// self.location.y,
24+
// self.location.z,
25+
match self.is_alive {
26+
true => "alive",
27+
false => "dead",
28+
}
29+
)
30+
}
31+
}
32+
33+
// #[allow(dead_code)]
34+
// pub trait Update {
35+
// fn update(&mut self) {
36+
// println!("Default behavior")
37+
// }
38+
// }
39+
//
40+
// pub struct Player {}
41+
// impl Update for Player {
42+
// //fn update(&mut self) {}
43+
// }
44+
// pub struct Orc {}
45+
// impl Update for Orc {
46+
// fn update(&mut self) {}
47+
// }
48+
// fn update_all(objects: Vec<&dyn Update>) {}

drone-lab/src/model/location.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
1+
use std::fmt::{Display, Formatter};
2+
13
#[derive(Debug, Copy, Clone, PartialEq)]
24
pub struct Location<'a> {
35
pub caption: &'a str, // 2nci Kat Güney Kanadı
46
pub x: f32,
57
pub y: f32,
68
pub z: f32,
79
}
10+
11+
impl Display for Location<'_> {
12+
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
13+
write!(f, "({}:{}:{})-{}", self.x, self.y, self.z, self.caption)
14+
}
15+
}

drone-lab/src/tests/flight_controller_tests.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ mod tests {
1818
},
1919
is_alive: false,
2020
};
21+
// Mocking kullanılabilir
2122
let actual = FlightController::check_status(&discovery_drone);
2223
assert_eq!(actual, DroneStatus::Offline);
2324
}
@@ -38,7 +39,7 @@ mod tests {
3839
is_alive: true,
3940
};
4041
let actual = FlightController::check_status(&discovery_drone);
41-
assert_eq!(actual, DroneStatus::LowBattery(energy_level));
42+
assert_eq!(actual, DroneStatus::LowBattery(BatteryRate(energy_level)));
4243
}
4344

4445
#[test]
Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
1-
#[cfg(test)]
2-
mod test {
3-
use crate::data::{DRONE_MODELS, get_random_between, get_random_number};
4-
5-
#[test]
6-
fn random_drone_model_test() {
7-
let max_value = DRONE_MODELS.len();
8-
let random_number = get_random_number(max_value);
9-
let model = DRONE_MODELS[random_number];
10-
assert!(
11-
DRONE_MODELS
12-
.iter()
13-
.any(|m| m.to_string() == model.to_string())
14-
);
15-
}
16-
17-
#[test]
18-
fn random_number_between_range_test() {
19-
let min_value = 10;
20-
let max_value = 50;
21-
let actual = get_random_between(min_value, max_value);
22-
assert!(actual >= min_value && actual <= max_value);
23-
}
24-
}
1+
// #[cfg(test)]
2+
// mod test {
3+
// use crate::data::{DRONE_MODELS, get_random_between, get_random_number};
4+
//
5+
// #[test]
6+
// fn random_drone_model_test() {
7+
// let max_value = DRONE_MODELS.len();
8+
// let random_number = get_random_number(max_value);
9+
// let model = DRONE_MODELS[random_number];
10+
// assert!(
11+
// DRONE_MODELS
12+
// .iter()
13+
// .any(|m| m.to_string() == model.to_string())
14+
// );
15+
// }
16+
//
17+
// #[test]
18+
// fn random_number_between_range_test() {
19+
// let min_value = 10;
20+
// let max_value = 50;
21+
// let actual = get_random_between(min_value, max_value);
22+
// assert!(actual >= min_value && actual <= max_value);
23+
// }
24+
// }

0 commit comments

Comments
 (0)