Skip to content

Commit 45c15fd

Browse files
committed
CLeanup
1 parent 21abcc6 commit 45c15fd

7 files changed

Lines changed: 63 additions & 79 deletions

File tree

elevator_1_state.txt

Lines changed: 0 additions & 2 deletions
This file was deleted.

elevator_2_state.txt

Lines changed: 0 additions & 2 deletions
This file was deleted.

src/control.rs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -161,17 +161,13 @@ pub fn serve_call(elevator_system: &ElevatorSystem, floor: u8) {
161161

162162
println!("Call for floor {} removed", floor);
163163

164-
// Open door for 3 seconds.
165-
// elevator.door_light(true);
166-
// std::thread::sleep(Duration::from_secs(3));
167-
168164
// Open door and handle obstruction properly
169165
elevator.door_light(true);
170166

171167
// Check for obstruction before starting the wait
172168
if elevator.is_obstructed {
173169
println!("Door kept open due to active obstruction");
174-
// Release the elevator lock and return - let the main loop handle it
170+
// Release the elevator lock and return it to main loop
175171
return;
176172
}
177173

@@ -194,7 +190,7 @@ pub fn serve_call(elevator_system: &ElevatorSystem, floor: u8) {
194190

195191
if is_blocked {
196192
println!("Door operation interrupted by obstruction");
197-
return; // Exit early, let main loop handle it
193+
return; // Goes to main loop
198194
}
199195
}
200196

@@ -229,7 +225,7 @@ pub fn serve_call(elevator_system: &ElevatorSystem, floor: u8) {
229225
fault_handler::persist_elevator_state(
230226
&elevator_system.local_id,
231227
elevator.current_floor,
232-
elevator.current_direction, // Should be DIRN_STOP here
228+
elevator.current_direction,
233229
&elevator.call_buttons
234230
).unwrap_or_else(|e| eprintln!("Failed to persist state: {}", e));
235231
}

src/elevio/cost.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ pub fn calculate_cost(
1414
}
1515
let mut cost = 0;
1616

17-
// Give a MAJOR bonus if elevator is already at the call floor
17+
// Give a large bonus if elevator is already at the call floor
1818
if current_floor == call_floor {
19-
cost -= 100; // Large bonus for being at the requested floor
19+
cost -= 100;
2020
} else {
2121
// Original distance calculation only if not at the floor
2222
let floor_distance = if current_floor > call_floor {
@@ -55,14 +55,12 @@ pub fn calculate_cost(
5555
/// Message types for elevator network communication
5656
#[derive(Debug, Clone)]
5757
pub enum ElevatorMessage {
58-
/// Message for a new hall call
5958
HallCall {
6059
floor: u8,
6160
direction: u8,
6261
timestamp: u64
6362
},
6463

65-
/// Message containing an elevator's current state
6664
ElevatorState {
6765
id: String,
6866
floor: u8,
@@ -71,7 +69,6 @@ pub enum ElevatorMessage {
7169
is_obstructed: bool,
7270
},
7371

74-
/// Message indicating a call has been completed
7572
CompletedCall {
7673
floor: u8,
7774
direction: u8
@@ -149,7 +146,7 @@ impl ElevatorMessage {
149146
}
150147
}
151148

152-
// Check if obstruction info is included (for backward compatibility)
149+
// Check if obstruction info is included
153150
let is_obstructed = if parts.len() > 5 {
154151
parts[5].parse::<u8>().ok()? != 0
155152
} else {

src/elevio/fault_handler.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,12 @@
1-
// Implementation for src/elevio/fault_handler.rs
2-
// This module will handle fault detection and recovery
3-
41
use std::collections::HashMap;
52
use std::sync::{Arc, Mutex};
6-
use std::time::{Duration, Instant, SystemTime};
3+
use std::time::{Duration, Instant};
74
use std::thread;
85

96
use crate::elevio::system::ElevatorSystem;
107

118
// Constants for heartbeat timing
129
const HEARTBEAT_INTERVAL: Duration = Duration::from_millis(500);
13-
// const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(2);
1410
const ELEVATOR_TIMEOUT: Duration = Duration::from_secs(5); // Time to consider an elevator disconnected
1511

1612
// Structure to track elevator health
@@ -93,7 +89,7 @@ pub fn start_health_monitoring(
9389
) {
9490
thread::spawn(move || {
9591
loop {
96-
// Sleep for a bit before checking
92+
// Sleep before checking
9793
thread::sleep(HEARTBEAT_INTERVAL);
9894

9995
// Check for disconnected elevators

src/elevio/system.rs

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,15 @@ use crate::control::{
1818

1919
// Structure to hold shared state for all elevators in the system
2020
pub struct ElevatorSystem {
21-
// Local elevator state
2221
pub local_id: String,
2322
pub local_elevator: Arc<Mutex<Elevator>>,
2423

25-
// Global system state
26-
pub hall_calls: Arc<Mutex<HashMap<(u8, u8), (String, u64)>>>, // (floor, direction) -> (aigned_to,ss timestamp)
24+
pub hall_calls: Arc<Mutex<HashMap<(u8, u8), (String, u64)>>>,
2725
pub elevator_states: Arc<Mutex<HashMap<String, ElevatorState>>>,
2826

29-
// Network communication
27+
3028
pub network_manager: Arc<p2p_connect::NetworkManager>,
31-
pub peers: Arc<Mutex<Vec<String>>>, // Store peer addresses separately
29+
pub peers: Arc<Mutex<Vec<String>>>,
3230
}
3331

3432
// Structure to keep track of other elevator states
@@ -37,7 +35,7 @@ pub struct ElevatorState {
3735
pub floor: u8,
3836
pub direction: u8,
3937
pub call_buttons: Vec<Vec<u8>>,
40-
pub last_seen: u64, // Timestamp of last update
38+
pub last_seen: u64,
4139
pub is_obstructed: bool,
4240
pub obstruction_duration: u64,
4341
}
@@ -53,13 +51,26 @@ pub fn start_reconnection_service(elevator_system: Arc<ElevatorSystem>) {
5351
let elevator_id = elevator_system.local_id.parse::<usize>().unwrap_or(0);
5452
if i as usize != elevator_id - 1 {
5553
let peer_message_port = 8878 + i;
54+
55+
56+
// Comment out if using simulator setup:
57+
// ----- Simulator setup begin here: -----
5658
let peer_addr = format!("localhost:{}", peer_message_port);
57-
// let peer_addr = format!("10.24.139.104:{}", peer_message_port);
58-
// let peer_addr_2 = format!("10.100.23.35:{}", peer_message_port);
59+
elevator_system.establish_bidirectional_connection(&peer_addr);
60+
// ----- Simulator setup end here: -----
61+
62+
63+
// Uncomment and type correct IP if using physical setup:
64+
/*
65+
// ----- Physical machine begin here: -----
66+
let peer_addr = format!("10.24.139.104:{}", peer_message_port);
67+
let peer_addr_2 = format!("10.100.23.35:{}", peer_message_port);
5968
6069
// Try to establish bidirectional connection
6170
elevator_system.establish_bidirectional_connection(&peer_addr);
62-
// elevator_system.establish_bidirectional_connection(&peer_addr_2);
71+
elevator_system.establish_bidirectional_connection(&peer_addr_2);
72+
// ----- Physical machine end here -----
73+
*/
6374
}
6475
}
6576
}
@@ -73,7 +84,7 @@ pub fn message_listener(elevator_system: Arc<ElevatorSystem>, port: u16, fault_m
7384
println!("Message listener started on port {}", port);
7485

7586
// Create a channel for passing messages to the processor
76-
let (tx, rx) = cbc::unbounded::<(String, String)>(); // (message, from_addr)
87+
let (tx, rx) = cbc::unbounded::<(String, String)>();
7788

7889
// Accept connections and handle messages
7990
thread::spawn(move || {
@@ -182,7 +193,6 @@ impl ElevatorSystem {
182193
};
183194

184195
if stream.write_all(msg.to_string().as_bytes()).is_ok() {
185-
// println!("Successfully established connection with {}", peer_addr);
186196
return true;
187197
}
188198
},
@@ -207,7 +217,6 @@ impl ElevatorSystem {
207217
// Find the address for this elevator ID
208218
let peers = self.peers.lock().unwrap();
209219
for peer_addr in &*peers {
210-
// Here we're sending to all peers, but ideally would target just the requesting elevator
211220
p2p_connect::send(Arc::clone(&self.network_manager), peer_addr, &sync_msg.to_string());
212221
}
213222
}
@@ -240,7 +249,7 @@ impl ElevatorSystem {
240249
println!("DEBUG: Received hall call message for floor {}, direction {}",
241250
floor, direction_to_string(direction));
242251

243-
// ALWAYS turn on the hall call light first (unconditionally)
252+
// Always turn on the hall call light first
244253
{
245254
let elevator = self.local_elevator.lock().unwrap();
246255
elevator.call_button_light(floor, direction, true);
@@ -365,7 +374,7 @@ impl ElevatorSystem {
365374
}
366375
};
367376

368-
// ALWAYS turn off the hall call light, regardless of who it was assigned to
377+
// Always turn off the hall call light, regardless of who it was assigned to
369378
{
370379
let elevator = self.local_elevator.lock().unwrap();
371380
elevator.call_button_light(floor, direction, false);
@@ -394,21 +403,13 @@ impl ElevatorSystem {
394403
}
395404
}
396405

397-
398-
399-
// Assign a hall call to the best elevator
400-
// that properly handles ties in cost calculation
401-
402-
403-
404406
pub fn assign_hall_call(&self, floor: u8, direction: u8, timestamp: u64) {
405407
// Check if call is already assigned
406408
{
407409
let hall_calls = self.hall_calls.lock().unwrap();
408410
if let Some((assigned_id, existing_ts)) = hall_calls.get(&(floor, direction)) {
409-
// If already assigned to someone, and no "newer" timestamp, do nothing
411+
// If already assigned to someone, and no newer timestamp, do nothing
410412
if !assigned_id.is_empty() && *existing_ts == timestamp {
411-
// Don't print anything - reduces console spam
412413
return;
413414
}
414415
}
@@ -458,7 +459,7 @@ impl ElevatorSystem {
458459
return;
459460
}
460461

461-
// Sort by cost (ascending) and then by id (ascending) for consistent tie-breaking
462+
// Sort by cost and then id for tie-breaks.
462463
all_costs.sort_by(|a, b| {
463464
match a.0.cmp(&b.0) {
464465
std::cmp::Ordering::Equal => a.1.cmp(&b.1),
@@ -558,7 +559,7 @@ impl ElevatorSystem {
558559

559560
/// Process a message received from another elevator
560561
pub fn process_message(&self, message: ElevatorMessage, from_addr: Option<String>) {
561-
// If we got this message from a specific address, make sure it's in our peer list
562+
// Check if message comes from a peer
562563
if let Some(addr) = from_addr {
563564
self.add_peer(addr);
564565
}
@@ -573,7 +574,6 @@ impl ElevatorSystem {
573574
ElevatorMessage::CompletedCall { floor, direction } => {
574575
self.handle_completed_call_message(floor, direction);
575576
},
576-
/* */
577577
ElevatorMessage::SyncRequest { id } => {
578578
self.handle_sync_request(id);
579579
}
@@ -587,7 +587,7 @@ impl ElevatorSystem {
587587
Err(_) => 0,
588588
};
589589

590-
let timeout_duration = 5; // Match ELEVATOR_TIMEOUT in fault_handler.rs
590+
let timeout_duration = 5;
591591
let mut disconnected_ids = Vec::new();
592592

593593
// Identify disconnected elevators with more detailed logging
@@ -617,7 +617,6 @@ impl ElevatorSystem {
617617
}
618618
}
619619

620-
// Find and explicitly mark calls for reassignment
621620
self.process_calls_from_disconnected_elevators(&disconnected_ids);
622621
}
623622
}

0 commit comments

Comments
 (0)