class TrafficLightWindow:
    """ Graphical window that displays a traffic light and change button. """

    def __init__(self):
        root = Tk()      # Create the main window
        root.title("Traffic Light")  # Set title bar text
        # Create widget container
        frame = Frame(root)
        frame.pack()
        #  Create a graphical button and ensure it calls the do_button_press
        #  method when the user presses it
        button = Button(frame, text='Change', command=self.do_button_press)
        #  Create and add a drawing surface within the window
        canvas = Canvas(frame, width=200, height=300)
        # Make a traffic light object instance variable
        self.light = TrafficLight(50, 20, 100, canvas)
        #  Position button and canvas objects
        button.grid(row=0, column=0)
        canvas.grid(row=0, column=1)
        #  Start the GUI event loop
        root.mainloop()               

    def do_button_press(self):
        """  The window manager calls this function when the user
             presses the graphical button. """
        self.light.change()
    def __init__(self):
        self.CurrentState = 'Init'
        self.NextState = 'Init'
        self.TimerCounter = 0
        self.ExitDummyFlag = 1
        #algoritmo para determinar quien empieza aleatoriamente
        self.Light0 = TrafficLight('0', 11)
        self.Light1 = TrafficLight('2', 29)

        self.FORCE_STATE_id0 = 0
        self.FORCE_STATE_id2 = 0
        self.DUMMY_STATE = 0
        self.LastLine = ""
Beispiel #3
0
 def test_can_change_lane_when_alone(self):
     car1 = Car(20, 0, 0, 10, 0)
     lane1 = Lane()
     lane2 = Lane()
     lane1.add_car(car1)
     light = TrafficLight(100)
     self.assertTrue(control.can_change_lane(car1, lane1, lane2, [light]))
Beispiel #4
0
 def test_cant_change_lane_when_close_to_traffic_lights(self):
     car1 = Car(98, 0, 0, 10, 0)
     lane1 = Lane()
     lane2 = Lane()
     lane1.add_car(car1)
     light = TrafficLight(100)
     self.assertFalse(control.can_change_lane(car1, lane1, lane2, [light]))
Beispiel #5
0
 def test_car_cant_advance_due_to_traffic(self):
     light = TrafficLight(200)
     other_car = Car(200 + Car.length, 0, 0, 0, 0)
     self.lane.add_car(other_car)
     self.assertFalse(
         control.can_advance(self.car, self.lane, [self.lane], [light], 0))
     # Cleanup
     self.lane.remove_car(other_car)
Beispiel #6
0
 def test_get_next_car_before_next_traffic_light_when_car_on_light(self):
     light = TrafficLight(200)
     other_car = Car(220, 0, 0, 0, 0)
     self.lane.add_car(other_car)
     self.assertFalse(
         control.get_next_car_before_next_traffic_light(
             self.car, self.lane, [light]))
     self.lane.remove_car(other_car)
Beispiel #7
0
 def test_cant_change_lane_when_car_slightly_in_front(self):
     car1 = Car(20, 0, 0, 10, 0)
     car2 = Car(25, 0, 0, 10, 0)
     lane1 = Lane()
     lane2 = Lane()
     lane1.add_car(car1)
     lane2.add_car(car2)
     light = TrafficLight(100)
     self.assertFalse(control.can_change_lane(car1, lane1, lane2, [light]))
Beispiel #8
0
 def test_get_next_car_before_next_traffic_light_returns_none(self):
     light = TrafficLight(100)
     self.car.position = 20
     other_car = Car(120, 0, 0, 0, 0)
     self.lane.add_car(other_car)
     self.assertFalse(
         control.get_next_car_before_next_traffic_light(
             self.car, self.lane, [light]))
     self.lane.remove_car(other_car)
     self.car.position = 200
Beispiel #9
0
    def __init__(self):
        super(TrafficMap, self).__init__(46, 139, 87, 255)
        self.north_stop_line = None
        self.east_stop_line = None
        self.south_stop_line = None
        self.west_stop_line = None
        self.north_normal_button = Button("normal", "north", self)
        self.east_normal_button = Button("normal", "east", self)
        self.south_normal_button = Button("normal", "south", self)
        self.west_normal_button = Button("normal", "west", self)
        self.north_emergency_button = Button("emergency", "north", self)
        self.east_emergency_button = Button("emergency", "east", self)
        self.south_emergency_button = Button("emergency", "south", self)
        self.west_emergency_button = Button("emergency", "west", self)

        self.car_queue = []

        self.from_north_light = TrafficLight("north")
        self.from_east_light = TrafficLight("east")
        self.from_south_light = TrafficLight("south")
        self.from_west_light = TrafficLight("west")
        self.from_north_light.push_handlers(self)
        self.from_east_light.push_handlers(self)
        self.from_south_light.push_handlers(self)
        self.from_west_light.push_handlers(self)

        self.north_lane = Lane(self, 'north')
        self.south_lane = Lane(self, 'south')
        self.east_lane = Lane(self, 'east')
        self.west_lane = Lane(self, 'west')

        self.central_occupied = 0

        self.draw_road()
        self.draw_button()
        self.draw_light()
        self.running_lane = "horizontal"
        self.last_change_time = time.time()



        pyglet.clock.schedule_interval(self.schedule, 0.1)
        self.aging = False
Beispiel #10
0
 def test_shouldnt_change_lane_to_go_faster_when_nothing(self):
     car1 = Car(50, 0, 0, 10, 0)
     lane0 = Lane()
     lane1 = Lane()
     lane2 = Lane()
     lane1.add_car(car1)
     light = TrafficLight(100)
     self.assertFalse(
         control.should_change_lane_to_move_faster(car1, lane1,
                                                   [lane0, lane2], [light]))
Beispiel #11
0
 def test_can_change_lane_when_cars_around_but_far(self):
     car1 = Car(50, 0, 0, 10, 0)
     car2 = Car(20, 0, 0, 10, 0)
     car3 = Car(70, 0, 0, 10, 0)
     lane1 = Lane()
     lane2 = Lane()
     lane1.add_car(car1)
     lane2.add_car(car2)
     lane2.add_car(car3)
     light = TrafficLight(100)
     self.assertTrue(control.can_change_lane(car1, lane1, lane2, [light]))
Beispiel #12
0
 def test_advance(self):
     for i in range(1, 99):
         test_car = Car(i, 0, 0, 0, 0)
         lane = Lane()
         lanes = [lane]
         lane.add_car(test_car)
         lights = [TrafficLight(100)]
         for j in range(200):
             control.advance(test_car, lane, lanes, lights, 30, 0.1)
         self.assertTrue(test_car.position < 100,
                         'Car starting at %d fail' % i)
def main(args):
    """
    Expects command line input: python traffic-simulator.py config_file.txt my_ip
    """
    config_filename = str(args[1])
    my_ip = str(args[2])

    # First, parse the config file
    config_dict = util.parse_config(config_filename)

    # Instantiate this traffic light
    traffic_light = TrafficLight(config_dict, my_ip)

    dir_to_mac_dict = util.match_MAC_to_direction(traffic_light.router, config_dict)

    # Make seperate process to listen for packets
    packet_listener = multiprocessing.Process(target=packet_sniff, \
                    args=(dir_to_mac_dict, traffic_light.north_queue, \
                    traffic_light.east_queue, traffic_light.south_queue, \
                    traffic_light.west_queue))

    packet_listener.start()
    traffic_light.start()
Beispiel #14
0
 def test_should_change_lane_to_go_to_no_car_lane(self):
     car1 = Car(20, 0, 0, 10, 0)
     car2 = Car(30, 0, 0, 10, 0)
     car3 = Car(60, 0, 0, 10, 0)
     lane0 = Lane()
     lane1 = Lane()
     lane2 = Lane()
     lane1.add_car(car1)
     lane1.add_car(car3)
     lane0.add_car(car2)
     light = TrafficLight(100)
     self.assertEquals(
         control.should_change_lane_to_move_faster(car1, lane1,
                                                   [lane0, lane2], [light]),
         lane2)
Beispiel #15
0
 def test_shouldnt_change_lane_when_current_lane_is_fastest(self):
     car0 = Car(30, 0, 0, 10, 0)
     car1 = Car(20, 0, 0, 10, 0)
     car2 = Car(45, 0, 0, 10, 0)
     car3 = Car(50, 0, 0, 10, 0)
     lane0 = Lane()
     lane1 = Lane()
     lane2 = Lane()
     lane0.add_car(car0)
     lane1.add_car(car1)
     lane1.add_car(car3)
     lane2.add_car(car2)
     light = TrafficLight(100)
     self.assertFalse(
         control.should_change_lane_to_move_faster(car1, lane1,
                                                   [lane0, lane2], [light]))
Beispiel #16
0
 def test_advance_with_car_in_front(self):
     for i in range(1, 80):
         test_car_1 = Car(i, 0, 0, 0, 0)
         test_car_2 = Car(i + 19, 0, 0, 0, 0)
         lane = Lane()
         lanes = [lane]
         lane.add_car(test_car_1)
         lane.add_car(test_car_2)
         lights = [TrafficLight(100)]
         for j in range(200):
             control.advance(test_car_1, lane, lanes, lights, 30, 0.1)
             control.advance(test_car_2, lane, lanes, lights, 30, 0.1)
         self.assertTrue(
             test_car_1.position < 100,
             'First car at %d fail, pos(car1) = %f, pos(car2) = %f' %
             (i, test_car_1.position, test_car_2.position))
         self.assertTrue(test_car_2.position < 100,
                         'Second car at %d fails' % (i + 19))
         self.assertTrue(
             test_car_1.position <= control.rear(test_car_2,
                                                 test_car_1.speed),
             'First car ended up further than expected')
Beispiel #17
0
 def __init__(self):
     root = Tk()  # Create the main window
     root.title("Multiple Traffic Lights")  # Set title bar text
     self.lights = []
     # The outer frame holds the nine inner frames that each contain
     # a canvas and a button.
     outer_frame = Frame(root)
     outer_frame.pack()
     #  Create nine drawing surfaces within the window
     for i in range(1, 10):
         f = Frame(outer_frame, borderwidth=2, relief=GROOVE)
         f.grid(row=0, column=i)
         c = Canvas(f, width=20 * i, height=250)
         c.grid(row=0, column=0)
         self.lights.append(TrafficLight(5 * i, 10, 10 * i, c))
         #b = Button(f, text="Change", command=lambda x=i: lights[x - 1].change())
         b = Button(f,
                    text="Change",
                    command=partial(self.do_button_press, i - 1))
         b.grid(row=1, column=0)
     #  Start the GUI event loop
     root.mainloop()
 def __init__(self):
     root = Tk()  # Create the main window
     root.title("Multiple Traffic Lights")  # Set title bar text
     f = Frame(root)
     f.pack()
     #  Create a drawing surface within the window
     canvas = Canvas(f, width=800, height=600)
     # Make a list of random traffic light objects
     color_list = ["red", "yellow", "green"]
     self.light_list = []
     for i in range(50):
         self.light_list.append(
             TrafficLight(randrange(2, 700), randrange(2, 400),
                          randrange(5, 120), canvas, choice(color_list)))
     #  Create a graphical button and ensure it calls the do_button_press
     #  function when the user presses it
     button = Button(f, text='Change', command=self.do_button_press)
     #  Position button and canvas objects
     button.grid(row=0, column=0)
     canvas.grid(row=0, column=1)
     #  Start the GUI event loop
     root.mainloop()
	def __init__(self):
		CoupledDEVS.__init__(self, "system")
		self.light = self.addSubModel(TrafficLight())
		self.police = self.addSubModel(Policeman())
		self.connectPorts(self.police.out, self.light.interrupt)
Beispiel #20
0
def main(url):
    curr = None
    try:
        light = TrafficLight()

        print("{0}: Starting up. Blinking lights".format(time.time()))

        for i in range(5):
            light.switch(TrafficLight.Color.green)
            time.sleep(0.2)
            light.switch(TrafficLight.Color.orange)
            time.sleep(0.2)
            light.switch(TrafficLight.Color.red)
            time.sleep(0.2)

        light.dark()

        while True:
            health = get_ceph_health(url)
            if health is not False:
                if curr != health:
                    print("{0}: {1}".format(time.time(), health))
                    color = healthmap.get(health)
                    light.switch(color)

            curr = health

            time.sleep(1)

    except KeyboardInterrupt:
        pass
    except Exception as e:
        print(e)
    finally:
        light.dark()
Beispiel #21
0
from trafficlight import TrafficLight

PORT = 5003
SPEED_LIMIT = 60
STATE = None

app = TrafficLight(__name__, PORT, STATE, SPEED_LIMIT)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=PORT)
class TrafficLightManager:

    #constructor
    def __init__(self):
        self.CurrentState = 'Init'
        self.NextState = 'Init'
        self.TimerCounter = 0
        self.ExitDummyFlag = 1
        #algoritmo para determinar quien empieza aleatoriamente
        self.Light0 = TrafficLight('0', 11)
        self.Light1 = TrafficLight('2', 29)

        self.FORCE_STATE_id0 = 0
        self.FORCE_STATE_id2 = 0
        self.DUMMY_STATE = 0
        self.LastLine = ""

    def hardware_config(self):
        GPIO.setmode(GPIO.BOARD)

        GPIO.setup(FORCE_LED_PIN, GPIO.OUT)
        GPIO.setup(BUTTON_0_INT_PIN, GPIO.IN)
        GPIO.setup(BUTTON_2_INT_PIN, GPIO.IN)

        GPIO.add_event_detect(BUTTON_0_INT_PIN, GPIO.FALLING)
        GPIO.add_event_callback(BUTTON_0_INT_PIN, self.buttonEventHandler)

        GPIO.add_event_detect(BUTTON_2_INT_PIN, GPIO.FALLING)
        GPIO.add_event_callback(BUTTON_2_INT_PIN, self.buttonEventHandler)

    # send message
    def sendMessage(self, message):
        try:
            l_StrExcecutionCall = "mosquitto_pub -h " + Pi_HOST + " -t \"" + TOPIC + "\" -m \"" + message + "\""
            l_StrProcessOutput = subprocess.Popen(l_StrExcecutionCall,
                                                  stdout=subprocess.PIPE,
                                                  shell=True)
        except:
            #pass
            print("PASS")

    # update flags log
    def updateFlags(self, flag):
        try:
            f = open(logPath, 'a')
            f.write(str(flag) + "\n")
            f.close()
        except:
            #pass
            print("\n\nSEDN PASS\n\n")

    # read flags
    def readFlags(self):
        try:
            with open(logPath, 'r') as f:
                lines = f.readlines()
                flags = lines[-1]
                flags = flags.rstrip('\n')
            print("\nFLAGS: " + flags)

            if (self.LastLine != flags):
                self.LastLine = flags

                if (flags == "000"):
                    self.FORCE_STATE_id0 = 0
                    self.FORCE_STATE_id2 = 0
                    #print("Exit Force Light state\n" )
                    GPIO.output(FORCE_LED_PIN, GPIO.LOW)

                elif (flags == "010"):
                    print("\n--- Force Light 1 ---")
                    GPIO.output(FORCE_LED_PIN, GPIO.HIGH)
                    self.FORCE_STATE_id2 = 1

                    if (self.Light1.mStatus == 'STOP'):
                        self.Light0.toggleTrafficLight()
                        self.Light1.toggleTrafficLight()
                    print('...')

                elif (flags == "100"):
                    print("\n--- Force Light 0 ---")
                    GPIO.output(FORCE_LED_PIN, GPIO.HIGH)
                    self.FORCE_STATE_id0 = 1

                    if (self.Light0.mStatus == 'STOP'):
                        self.Light1.toggleTrafficLight()
                        self.Light0.toggleTrafficLight()
                    print('...')

                elif (flags == "001"):
                    self.NextState = 'Dummy'

                else:
                    pass
        except:
            #pass
            print("PASS")

    #generates the interrupt
    def buttonEventHandler(self, pin):
        flag = ""
        # Light 0
        if (pin == BUTTON_0_INT_PIN):
            if ((self.FORCE_STATE_id0 == 0) and (self.FORCE_STATE_id2 == 0)):
                print("\n--- Force Light 0 ---")
                GPIO.output(FORCE_LED_PIN, GPIO.HIGH)
                self.FORCE_STATE_id0 = 1

                self.Light0.mStatus = 'STOP'
                self.Light1.mStatus = 'GO'

                self.Light1.toggleTrafficLight()
                self.Light0.toggleTrafficLight()

                #if(self.Light0.mStatus == 'STOP'):
                #self.Light1.mStatus = 'GO'
                #self.Light1.toggleTrafficLight()
                #self.Light0.toggleTrafficLight()
                print('...')
                self.updateFlags("100")
                self.sendMessage("100")

            elif ((self.FORCE_STATE_id0 == 0) and (self.FORCE_STATE_id2 == 1)):
                print("Can't Force Light 0, Light 1 is already forced\n...")

            elif (self.FORCE_STATE_id0 == 1):
                print("Exit Force Light 0 state\n")
                self.FORCE_STATE_id0 = 0
                GPIO.output(FORCE_LED_PIN, GPIO.LOW)
                self.updateFlags("000")
                self.sendMessage("000")

        # Light 1
        else:
            if ((self.FORCE_STATE_id2 == 0) and (self.FORCE_STATE_id0 == 0)):
                print("\n--- Force Light 1 ---")
                GPIO.output(FORCE_LED_PIN, GPIO.HIGH)
                self.FORCE_STATE_id2 = 1

                self.Light0.mStatus = 'GO'
                self.Light1.mStatus = 'STOP'
                self.Light0.toggleTrafficLight()
                self.Light1.toggleTrafficLight()

                #if(self.Light1.mStatus == 'STOP'):
                #self.Light0.mStatus = 'GO'
                #self.Light0.toggleTrafficLight()
                #self.Light1.toggleTrafficLight()
                print('...')
                self.updateFlags("010")
                self.sendMessage("010")

            elif ((self.FORCE_STATE_id2 == 0) and (self.FORCE_STATE_id0 == 1)):
                print("Can't Force Light 1, Light 0 is already forced\n...")

            elif (self.FORCE_STATE_id2 == 1):
                print("Exit Force Light 1 state\n")
                self.FORCE_STATE_id2 = 0
                GPIO.output(FORCE_LED_PIN, GPIO.LOW)
                self.updateFlags("000")
                self.sendMessage("000")

        # Update Log
        #self.updateFlags(flag)

        # Send message
        #self.sendMessage(flag)

        ###
        time.sleep(1)

    def run(self):
        if ((self.CurrentState == 'Init') and (self.FORCE_STATE_id0 == 0)
                and (self.FORCE_STATE_id2 == 0)):
            print('\n--- State: Init ---')
            self.TimerCounter = TIMEX  #starts with a random timeout
            RandomLight = random.randrange(2)
            print('GO ', RandomLight, '\n')
            if RandomLight:
                self.Light1.setStatus('STOP')
                self.Light0.setStatus('GO')
            else:
                self.Light0.setStatus('STOP')
                self.Light1.setStatus('GO')

            self.NextState = 'Idle'
            print('--- State: Idle ...')
            self.readFlags()

        elif ((self.CurrentState == 'Idle') and (self.FORCE_STATE_id0 == 0)
              and (self.FORCE_STATE_id2 == 0)):
            #print('\n--- State: Idle ---')
            if (self.TimerCounter == 0):
                self.NextState = 'UpdateLights'
            else:
                self.NextState = 'Idle'
                time.sleep(1)
                self.TimerCounter = self.TimerCounter - 1
            self.readFlags()

        elif ((self.CurrentState == 'UpdateLights')
              and (self.FORCE_STATE_id0 == 0) and (self.FORCE_STATE_id2 == 0)):
            print("--- State: UpdateLights ...")
            image_file = ''
            if (self.Light0.mStatus == 'GO' and self.Light1.mStatus == 'STOP'):
                image_file = self.Light1.mID + "cars.jpg"
                subprocess.call("fswebcam -d /dev/video" + self.Light1.mID +
                                " -S0 " + image_file,
                                shell=True)

            elif (self.Light1.mStatus == 'GO'
                  and self.Light0.mStatus == 'STOP'):
                image_file = self.Light0.mID + "cars.jpg"
                subprocess.call("fswebcam -d /dev/video" + self.Light0.mID +
                                " -S0 " + image_file,
                                shell=True)
            #print(image_file)
            CarsWaiting = self.ImageRecognition(image_file)
            print('Cars waiting: ' + str(CarsWaiting), '\n')
            if (CarsWaiting > 0):
                self.TimerCounter = CarsWaiting * TIME_PER_CAR
                self.NextState = 'Toggle'
                self.updateFlags("000")
                self.sendMessage("000")
            elif (CarsWaiting == 0):  #Zero cars waiting
                self.TimerCounter = TIMEX
                self.NextState = 'Idle'
                self.updateFlags("000")
                self.sendMessage("000")
            else:
                self.NextState = 'Dummy'
            self.readFlags()

        elif ((self.CurrentState == 'Toggle') and (self.FORCE_STATE_id0 == 0)
              and (self.FORCE_STATE_id2 == 0)):
            print('--- State: Toggle ...')
            # call toggle function
            if (self.Light1.mStatus == 'STOP'):
                self.Light0.toggleTrafficLight()
                self.Light1.toggleTrafficLight()

            elif (self.Light0.mStatus == 'STOP'):
                self.Light1.toggleTrafficLight()
                self.Light0.toggleTrafficLight()

            self.NextState = 'Idle'
            print('--- State: Idle ...')
            self.readFlags()

        elif ((self.CurrentState == 'Dummy') and (self.FORCE_STATE_id0 == 0)
              and (self.FORCE_STATE_id2 == 0)):
            print('--- State: Dummy ...')
            if (self.Light0.mStatus == 'GO'):
                self.Light0.toggleTrafficLight()
                self.Light1.toggleTrafficLight()
            else:
                self.Light1.toggleTrafficLight()
                self.Light0.toggleTrafficLight()

            time.sleep(TIME_DUMMY)
            self.NextState = 'UpdateLights'

            # Update Log
            self.updateFlags("001")

            # Send message
            self.sendMessage("001")

            # Read Log
            self.readFlags()

        #elif(self.CurrentState == 'Reset'):
        #pass
        #self.readFlags()

        #FORCE state
        else:
            self.NextState = 'UpdateLights'
            self.readFlags()

        ##
        self.CurrentState = self.NextState

    def ImageRecognition(self, image_file):
        IMAGE_FILE = image_file
        try:
            # Connect to the Google Cloud-ML Service
            credentials = GoogleCredentials.from_stream(CREDENTIALS_FILE)
            service = googleapiclient.discovery.build('vision',
                                                      'v1',
                                                      credentials=credentials)

            # Read file and convert it to a base64 encoding
            with open(image_file, "rb") as f:
                image_data = f.read()
                encoded_image_data = b64encode(image_data).decode('UTF-8')

            # Create the request object for the Google Vision API
            batch_request = [{
                'image': {
                    'content': encoded_image_data
                },
                'features': [{
                    'type': 'OBJECT_LOCALIZATION'
                }]
            }]
            request = service.images().annotate(
                body={'requests': batch_request})

            # Send the request to Google
            response = request.execute()

        except:
            return -1

        # Check for errors
        if 'error' in response:
            return -1

        else:
            try:
                labels = response['responses'][0]['localizedObjectAnnotations']

                counter = 0
                for label in labels:
                    tag = label['name']
                    if (re.search('Car', tag)):
                        counter = counter + 1
                return counter
            except:
                return 0
Beispiel #23
0
    def __init__(self):

        self.display = Display()
        self.quit = False
        self.stopped = False
        self.mode = None

        # Time in seconds until screen turns off if no activity
        self.screentimeout = 30

        # Time in seconds until box turns off if no activity
        self.powertimeout = 600

        self.display.Update("Setting up\nbuttons...")

        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(26, GPIO.IN)
        GPIO.setup(24, GPIO.IN)

        self.__speakerpin = 21

        self.__button1 = 7
        self.__button2 = 11
        self.__button3 = 12
        self.__button4 = 13
        self.__button5 = 15
        self.__button6 = 16
        self.__button7 = 18
        self.__button8 = 19       

        self.__redpin = 22
        self.__yellowpin = 23
        self.__greenpin = 24

        self.__unallocatedpins = [26]

        self.GPIOpins = {"buttons": [self.__button1,
                                     self.__button2,
                                     self.__button3,
                                     self.__button4,
                                     self.__button5,
                                     self.__button6,
                                     self.__button7,
                                     self.__button8],
                         "speaker":  self.__speakerpin,
                         "leds":    [self.__redpin,
                                     self.__yellowpin,
                                     self.__greenpin],
                         "unused":   self.__unallocatedpins}
        for button in self.GPIOpins["buttons"]:
            GPIO.setup(button, GPIO.IN)

        for button in (self.GPIOpins["leds"] + [self.__speakerpin]):
            GPIO.setup(button, GPIO.OUT)

        self.speaker = Speaker(self.__speakerpin)

        self.display.Update("Initialising\nsystem...")

        pygame.init()
        pygame.display.set_mode((1,1))
        pygame.mixer.init(frequency=22050, channels=1, buffer=1024) 
        
        self.trafficlight = TrafficLight(self.__redpin,
                                         self.__yellowpin,
                                         self.__greenpin)
        #self.automute = True
        #self.startAutoMute()

        self.display.Update("Looking for\nplugins...")
        self.modes = self.__getModes()
        #train = self.__loadMode(self.modes[0])
        self.switchMode(1)

        self.override_thread = threading.Thread(target=self.__override_monitor)
        self.override_thread.start()

        self.powersave_thread = threading.Thread(target=self.__power_save)
        self.powersave_thread.start()
Beispiel #24
0
class TrafficMap(ColorLayer):
    def __init__(self):
        super(TrafficMap, self).__init__(46, 139, 87, 255)
        self.north_stop_line = None
        self.east_stop_line = None
        self.south_stop_line = None
        self.west_stop_line = None
        self.north_normal_button = Button("normal", "north", self)
        self.east_normal_button = Button("normal", "east", self)
        self.south_normal_button = Button("normal", "south", self)
        self.west_normal_button = Button("normal", "west", self)
        self.north_emergency_button = Button("emergency", "north", self)
        self.east_emergency_button = Button("emergency", "east", self)
        self.south_emergency_button = Button("emergency", "south", self)
        self.west_emergency_button = Button("emergency", "west", self)

        self.car_queue = []

        self.from_north_light = TrafficLight("north")
        self.from_east_light = TrafficLight("east")
        self.from_south_light = TrafficLight("south")
        self.from_west_light = TrafficLight("west")
        self.from_north_light.push_handlers(self)
        self.from_east_light.push_handlers(self)
        self.from_south_light.push_handlers(self)
        self.from_west_light.push_handlers(self)

        self.north_lane = Lane(self, 'north')
        self.south_lane = Lane(self, 'south')
        self.east_lane = Lane(self, 'east')
        self.west_lane = Lane(self, 'west')

        self.central_occupied = 0

        self.draw_road()
        self.draw_button()
        self.draw_light()
        self.running_lane = "horizontal"
        self.last_change_time = time.time()



        pyglet.clock.schedule_interval(self.schedule, 0.1)
        self.aging = False


    def draw_road(self):

        road_image_1 = image.create(200, 800, image.SolidColorImagePattern(color=(190, 190, 190, 255)))
        road_image_2 = image.create(800, 200, image.SolidColorImagePattern(color=(190, 190, 190, 255)))
        road_1 = Sprite(road_image_1, position=(400, 400))
        road_2 = Sprite(road_image_2, position=(400, 400))
        self.add(road_1)
        self.add(road_2)
        self.draw_line()

    def draw_line(self):
        line_1 = Line(start=(0, 400), end=(300, 400), color=(255, 215, 0, 255), stroke_width=5)
        self.add(line_1)
        line_2 = Line(start=(400, 800), end=(400, 500), color=(255, 215, 0, 255), stroke_width=5)
        self.add(line_2)
        line_3 = Line(start=(500, 400), end=(800, 400), color=(255, 215, 0, 255), stroke_width=5)
        self.add(line_3)
        line_4 = Line(start=(400, 300), end=(400, 0), color=(255, 215, 0, 255), stroke_width=5)
        self.add(line_4)
        self.north_stop_line = Line(start=(300, 500), end=(500, 500), color=(255, 255, 255, 255), stroke_width=5)
        self.add(self.north_stop_line)
        self.east_stop_line = Line(start=(500, 500), end=(500, 300), color=(255, 255, 255, 255), stroke_width=5)
        self.add(self.east_stop_line)
        self.south_stop_line = Line(start=(500, 300), end=(300, 300), color=(255, 255, 255, 255), stroke_width=5)
        self.add(self.south_stop_line)
        self.west_stop_line = Line(start=(300, 300), end=(300, 500), color=(255, 255, 255, 255), stroke_width=5)
        self.add(self.west_stop_line)

    def draw_button(self):

        self.add(self.north_normal_button)
        self.add(self.east_normal_button)
        self.add(self.south_normal_button)
        self.add(self.west_normal_button)
        self.add(self.north_emergency_button)
        self.add(self.east_emergency_button)
        self.add(self.south_emergency_button)
        self.add(self.west_emergency_button)


    def draw_light(self):

        self.add(self.from_north_light)
        self.add(self.from_south_light)
        self.add(self.from_east_light)
        self.add(self.from_west_light)

        self.from_west_light.switch_signal()
        self.from_east_light.switch_signal()


    def add_car(self, type, from_direction):
        car = None

        if from_direction is "north":
            car = Car(type, self.north_lane)
            self.north_lane.add_car(car)
            car.do(CustomizeMoveBy((0, -900), duration=4))

        elif from_direction is "south":
            car = Car(type, self.south_lane)
            self.south_lane.add_car(car)
            car.do(CustomizeMoveBy((0, 900), duration=4))
        elif from_direction is "east":
            car = Car(type, self.east_lane)
            self.east_lane.add_car(car)
            car.do(CustomizeMoveBy((-900, 0), duration=4))
        elif from_direction is "west":
            car = Car(type, self.west_lane)
            self.west_lane.add_car(car)

            car.do(CustomizeMoveBy((900, 0), duration=4))

        self.add(car)
        print car
        self.car_queue.append(car)


    def swtich_lights(self):
        self.last_change_time = time.time()
        self.from_north_light.switch_signal()
        self.from_west_light.switch_signal()
        self.from_east_light.switch_signal()
        self.from_south_light.switch_signal()


    def allow_vertical(self):
        self.running_lane = "vertical"
        self.last_change_time = time.time()
        self.from_north_light.set_green()
        self.from_south_light.set_green()
        self.from_east_light.set_red()
        self.from_west_light.set_red()


    def allow_horizontal(self):
        self.running_lane = "horizontal"
        self.last_change_time = time.time()
        self.from_west_light.set_green()
        self.from_east_light.set_green()
        self.from_north_light.set_red()
        self.from_south_light.set_red()

    def clear_central(self):

        self.from_west_light.set_red()
        self.from_east_light.set_red()
        self.from_north_light.set_red()
        self.from_south_light.set_red()

    def has_emergency_car(self):
        if not self.north_lane.has_emergency() and not self.south_lane.has_emergency() \
                and not self.west_lane.has_emergency() and not self.east_lane.has_emergency():
            return False
        else:
            return True

    def has_waiting_car(self):
        if self.north_lane.has_waiting_car() or self.south_lane.has_waiting_car() \
                or self.west_lane.has_waiting_car() or self.east_lane.has_waiting_car():
            return True
        else:
            return False

    def has_emergency_waiting(self):
        if not self.north_lane.has_emergency_waiting() and not self.south_lane.has_emergency_waiting() \
                and not self.west_lane.has_emergency_waiting() and not self.east_lane.has_emergency_waiting():
            return False
        else:
            return True

    def is_empty(self):
        if self.north_lane.normal_car_num + self.north_lane.emergency_car_num is 0 \
                and self.south_lane.normal_car_num + self.south_lane.emergency_car_num is 0 \
                and self.east_lane.normal_car_num + self.east_lane.emergency_car_num is 0 \
                and self.west_lane.normal_car_num + self.west_lane.emergency_car_num is 0:
            return True
        else:
            return False

    def schedule(self, dt):

        # print time.time() -self.last_change_time
        # print "aging",self.aging
        if time.time() - self.last_change_time > 4.0 and (self.aging or self.is_empty()):
            # if self.aging or self.is_empty():
                if not self.central_occupied:
                    if self.running_lane is "horizontal":
                        self.allow_vertical()
                    else:
                        self.allow_horizontal()
                else:
                    self.clear_central()
        else:
            if not self.has_waiting_car():
                self.aging = False
                if not self.has_emergency_car():
                    if self.north_lane.normal_car_num > self.west_lane.normal_car_num and self.north_lane.normal_car_num > self.east_lane.normal_car_num \
                            or self.south_lane.normal_car_num > self.west_lane.normal_car_num and self.south_lane.normal_car_num > self.east_lane.normal_car_num:
                        if not self.central_occupied:
                            if self.running_lane is "horizontal":
                                self.allow_vertical()
                                for car in self.car_queue:
                                    car.resume()
                    else:
                        if not self.central_occupied:
                            if self.running_lane is "vertical":
                                self.allow_horizontal()
                                for car in self.car_queue:
                                    car.resume()

                else:
                    if self.north_lane.emergency_car_num > self.west_lane.emergency_car_num and self.north_lane.emergency_car_num > self.east_lane.emergency_car_num \
                            or self.south_lane.emergency_car_num > self.west_lane.emergency_car_num and self.south_lane.emergency_car_num > self.east_lane.emergency_car_num:
                        if not self.central_occupied:
                            if self.running_lane is "horizontal":
                                self.allow_vertical()
                                for car in self.car_queue:
                                    car.resume()
                    else:
                        if not self.central_occupied:
                            if self.running_lane is "vertical":
                                self.allow_horizontal()
                                for car in self.car_queue:
                                    car.resume()
                        else:
                            self.clear_central()
            else:
                print "has waiting"
                self.aging = True
                if not self.has_emergency_waiting():

                    if self.north_lane.waiting_normal_car > self.west_lane.waiting_normal_car and self.north_lane.waiting_normal_car > self.east_lane.waiting_normal_car \
                            or self.south_lane.waiting_normal_car > self.west_lane.waiting_normal_car and self.south_lane.waiting_normal_car > self.east_lane.waiting_normal_car:
                        if not self.central_occupied:
                            if self.running_lane is "horizontal":
                                self.allow_vertical()
                                for car in self.car_queue:
                                    car.resume()
                    else:
                        if not self.central_occupied:
                            if self.running_lane is "vertical":
                                self.allow_horizontal()
                                for car in self.car_queue:
                                    car.resume()

                else:
                    if self.north_lane.waiting_emergency_car > self.west_lane.waiting_emergency_car and self.north_lane.waiting_emergency_car > self.east_lane.waiting_emergency_car \
                            or self.south_lane.waiting_emergency_car > self.west_lane.waiting_emergency_car and self.south_lane.waiting_emergency_car > self.east_lane.waiting_emergency_car:
                        if not self.central_occupied:
                            if self.running_lane is "horizontal":
                                self.allow_vertical()
                                for car in self.car_queue:
                                    car.resume()
                    else:
                        if not self.central_occupied:
                            if self.running_lane is "vertical":
                                self.allow_horizontal()
                                for car in self.car_queue:
                                    car.resume()
                        else:
                            self.clear_central()
Beispiel #25
0
 def test_cant_change_to_lane_with_opposite_direction(self):
     car = Car(20, 0, 0, 10, 0)
     lane1 = Lane()
     lane2 = Lane('SOUTH')
     light = TrafficLight(100)
     self.assertFalse(control.can_change_lane(car, lane1, lane2, [light]))
Beispiel #26
0
 def test_cant_advance_on_traffic_light(self):
     red_light = TrafficLight(200, initial_state='Red')
     self.assertFalse(
         control.can_advance(self.car, self.lane, [self.lane], [red_light],
                             0))
Beispiel #27
0
 def test_can_advance_on_green(self):
     light = TrafficLight(200)
     self.assertTrue(
         control.can_advance(self.car, self.lane, [self.lane], [light], 0))
Beispiel #28
0
 def test_appear_cars_between_two_lanes(self):
     lanes = [Lane(), Lane()]
     lights = [TrafficLight(100)]