Created
December 28, 2020 21:45
-
-
Save chelseatroy/b3fe642679482116410fb6940474b0b6 to your computer and use it in GitHub Desktop.
Elevator Implementation with Threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import threading | |
class Elevator: | |
def __init__(self, control, timer=Timer(), eventlog=EventLog()): | |
self.control = control | |
self.timer = timer | |
self.eventlog = eventlog | |
#Python thinks it's a dict if you | |
#initialize an empty set | |
self.floors_to_visit = {1} | |
self.floors_to_visit.remove(1) | |
self.min_floor = 1 | |
self.max_floor = 1 | |
self.current_floor = 1 | |
self.action_log = [] | |
self.on= True | |
threading.Timer(self.timer.interval, self.keep_it_moving).start() | |
def go_to_floor(self, floor): | |
self.log(f"Stop requested for floor {floor}") | |
self.floors_to_visit.add(floor) | |
self.max_floor = max(self.floors_to_visit) | |
self.min_floor = min(self.floors_to_visit) | |
def keep_it_moving(self): | |
if self.floors_to_visit: | |
if len(self.floors_to_visit) == 1 and self.current_floor in self.floors_to_visit: | |
self.floors_to_visit.remove(self.current_floor) | |
self.open_doors() | |
time.sleep(self.timer.interval) | |
elif self.max_floor > self.current_floor: | |
self.up_1_floor() | |
else: | |
self.down_1_floor() | |
if self.on: | |
threading.Timer(self.timer.interval, self.keep_it_moving).start() | |
def up_1_floor(self): | |
self.control.hoist_motor("up") | |
self.current_floor += 1 | |
self.log(message=f"On floor {self.current_floor}") | |
self.handle_making_a_stop() | |
def down_1_floor(self): | |
self.control.hoist_motor("down") | |
self.current_floor -= 1 | |
self.log(f"On floor {self.current_floor}") | |
self.handle_making_a_stop() | |
def handle_making_a_stop(self): | |
if self.current_floor in self.floors_to_visit: | |
self.log(f"Stopping at floor {self.current_floor}") | |
self.stop() | |
self.open_doors() | |
self.floors_to_visit.remove(self.current_floor) | |
if self.floors_to_visit: | |
self.max_floor = max(self.floors_to_visit) | |
self.min_floor = min(self.floors_to_visit) | |
def stop(self): | |
self.control.stop_motor() | |
def open_doors(self): | |
self.log(f"Opening doors at floor {self.current_floor}") | |
self.control.open_door() | |
self.log(f"DOORS CLOSING") | |
self.control.close_door() | |
def log(self, message): | |
self.action_log.append(message) | |
self.eventlog.register(message) | |
print(message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment