class Elevator_tracker(object):
    def __init__(self, building, TRACKER_INTERVAL=1):
        self.building = building
        self.elevators = building.get_elevators()
        self.elevator_count = len(self.elevators)
        self.TRACKER_INTERVAL = TRACKER_INTERVAL
        self.visited_floors = [
            x[:] for x in [[] * self.elevator_count] * self.elevator_count
        ]
        self.tracker_timer = RepeatedTimer(self.TRACKER_INTERVAL,
                                           self.get_elevators_floors)

    def start_tracking(self):
        self.tracker_timer.start()

    def end_tracking(self):
        self.tracker_timer.stop()
        return self.visited_floors

    def get_tracker_status(self):
        if self.tracker_timer.isRunning():
            return "Running"
        else:
            return "Terminaed"

    def get_elevators_floors(self):
        for i in range(0, self.elevator_count):
            self.visited_floors[i].append(
                self.elevators[i].get_current_floor())

    def save_result(self):
        print(self.visited_floors)
        with open('visited_floors.csv', 'a') as fp:
            a = csv.writer(fp, delimiter=',', lineterminator="\n")
            a.writerows(self.result)

    def plot_track(self):
        #plt.hold(True)
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        x_axis = numpy.arange(
            0,
            len(self.visited_floors[0]) * self.TRACKER_INTERVAL,
            self.TRACKER_INTERVAL)
        labels = []
        lines = []
        for i in range(0, self.elevator_count):
            lines += plt.plot(x_axis,
                              self.visited_floors[i],
                              label='Elevator ' + str(i))
            #plt.plot(x_axis, self.visited_floors[i])

        # Plot decorations
        major_ticks = numpy.arange(0, self.building.get_floor_count(), 1)
        ax.set_yticks(major_ticks)
        labels = [l.get_label() for l in lines]
        plt.legend(lines, labels)
        plt.xlabel('Time [s]')
        plt.ylabel('Floor')
        plt.show()
示例#2
0
def startTimer(name):
    isSend = True
    rt = RepeatedTimer(90, getPubKey, name)
    try:
        sleep(600)
    finally:
        rt.stop()
示例#3
0
 def __init__(self):
     self.item_dict = {}
     self.ingredientsCrawled = 0
     self.productsCrawled = 0
     print("starting...")
     self.rt = RepeatedTimer(
         1, self.update_stats)  # it auto-starts, no need of rt.start()
 def __init__(self, building, name, current_floor):
     self.name = name
     self.current_floor = current_floor
     self.building = building
     self.destination_floor = []
     self.active_calls = []
     self.SPEED = 1 # s / floor
     self.TIME_AT_FLOOR = 5 # s / floor
     Elevator.elevator_count += 1
     self.run_timer = RepeatedTimer(self.SPEED, self.execute_call())
 def __init__(self, building, TRACKER_INTERVAL=1):
     self.building = building
     self.elevators = building.get_elevators()
     self.elevator_count = len(self.elevators)
     self.TRACKER_INTERVAL = TRACKER_INTERVAL
     self.visited_floors = [
         x[:] for x in [[] * self.elevator_count] * self.elevator_count
     ]
     self.tracker_timer = RepeatedTimer(self.TRACKER_INTERVAL,
                                        self.get_elevators_floors)
示例#6
0
 def __init__(self, sound, sequence=[0], bpm=120):
     self._sound = sound
     if len(sequence) > 0:
         self._sequence = sequence
     else:
         raise SequencerException("please provide a sequence as a list with length > 0.")
     self._repetitions = 0
     self._sequence_index = 0
     self._repetitions_played = 0
     self._bpm = bpm
     self._interval = self.bpm_to_interval(self.bpm)
     self._timer = RepeatedTimer(self._interval, self.execute_sequence_index)
class Elevator_tracker(object):
    def __init__(self, building, TRACKER_INTERVAL = 1):
        self.building = building
        self.elevators = building.get_elevators()
        self.elevator_count = len(self.elevators)
        self.TRACKER_INTERVAL = TRACKER_INTERVAL
        self.visited_floors = [x[:] for x in [[]*self.elevator_count]*self.elevator_count]
        self.tracker_timer = RepeatedTimer(self.TRACKER_INTERVAL, self.get_elevators_floors)

    def start_tracking(self):    
        self.tracker_timer.start()
        
    def end_tracking(self):
        self.tracker_timer.stop()
        return self.visited_floors
        
    def get_tracker_status(self):
        if self.tracker_timer.isRunning():
            return "Running"
        else: 
            return "Terminaed"
        
    def get_elevators_floors(self):
        for i in range(0, self.elevator_count):
            self.visited_floors[i].append(self.elevators[i].get_current_floor())
        
    def save_result(self):      
        print (self.visited_floors)
        with open('visited_floors.csv', 'a') as fp:
            a = csv.writer(fp, delimiter=',', lineterminator="\n")
            a.writerows(self.result)
            
    def plot_track(self):
        #plt.hold(True)
        fig = plt.figure() 
        ax = fig.add_subplot(1,1,1)   
        x_axis = numpy.arange(0, len(self.visited_floors[0])*self.TRACKER_INTERVAL, self.TRACKER_INTERVAL)
        labels = []
        lines = [] 
        for i in range(0, self.elevator_count):
            lines += plt.plot(x_axis, self.visited_floors[i], label='Elevator '+ str(i))
            #plt.plot(x_axis, self.visited_floors[i])
        
        # Plot decorations        
        major_ticks = numpy.arange(0, self.building.get_floor_count(), 1)                                              
        ax.set_yticks(major_ticks)
        labels = [l.get_label() for l in lines]
        plt.legend(lines, labels)
        plt.xlabel('Time [s]')
        plt.ylabel('Floor')
        plt.show()
 def __init__(self, building, TRACKER_INTERVAL = 1):
     self.building = building
     self.elevators = building.get_elevators()
     self.elevator_count = len(self.elevators)
     self.TRACKER_INTERVAL = TRACKER_INTERVAL
     self.visited_floors = [x[:] for x in [[]*self.elevator_count]*self.elevator_count]
     self.tracker_timer = RepeatedTimer(self.TRACKER_INTERVAL, self.get_elevators_floors)
示例#9
0
def main():
    temperature_sensor.setup()

    RepeatedTimer(10, measure)

    while True:
        signal.pause()
示例#10
0
class EwgScraperPipeline(object):
    def __init__(self):
        self.item_dict = {}
        self.ingredientsCrawled = 0
        self.productsCrawled = 0
        print("starting...")
        self.rt = RepeatedTimer(
            1, self.update_stats)  # it auto-starts, no need of rt.start()

    @classmethod
    def from_crawler(cls, crawler):
        pipeline = cls()
        crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
        return pipeline

    def spider_closed(self, spider):
        self.rt.stop()
        with open('%s_ingredients.json' % spider.name, 'w') as f:
            json.dump([entry for entry in self.item_dict.values()], f)
        print("FINAL: Ingredients: {}\tProducts: {}".format(
            self.ingredientsCrawled, self.productsCrawled))

    def process_item(self, item, spider):
        # Add ingredient or product to collected data
        # NOTE: Does nothing if input item is not a product or ingredient
        if item:
            is_ingredient = 'ingredient_id' in item.keys()
            item_key = 'ingredient_id' if is_ingredient else 'product_id'
            if 'product_id' in item.keys() or is_ingredient:
                input_dict = dict(item)
                input_key = input_dict[item_key]
                if input_key in self.item_dict:
                    # If item already exists make sure the new input is not another placeholder
                    # NOTE: A place holder item contains only the item id
                    if len(input_dict) > 1:
                        self.item_dict[input_key].update(input_dict)
                else:
                    self.item_dict[input_key] = input_dict
                if is_ingredient:
                    self.ingredientsCrawled = self.ingredientsCrawled + 1
                else:
                    self.productsCrawled = self.productsCrawled + 1

    def update_stats(self):
        print("Ingredients: {}\tProducts: {}".format(self.ingredientsCrawled,
                                                     self.productsCrawled))
示例#11
0
def main():
    client = InfluxDBClient(influx_host_ip, influx_host_port, influx_db)
    client.switch_database(influx_db)

    measurements_timer = RepeatedTimer(10, measurements, client)

    while (True):
        signal.pause()
示例#12
0
def main():
    influx_client.switch_database(influx_db)

    RepeatedTimer(30, control)

    while True:
        signal.pause()

    mqtt_client.disconnect()
示例#13
0
def main():
    timestamp = datetime.datetime.fromtimestamp(
        time.time()).strftime('%d.%m.%Y %H:%M')
    lcd.message("Initializing ...", 1)
    lcd.message(timestamp, 2)

    RepeatedTimer(30, display)

    while True:
        signal.pause()
示例#14
0
    def recv_connect(self):
        print "JointPosition channel connected"

        def sendPositions():
            self.broadcast_event('positionUpdate',
                                 motionController.getJointAngles(JointNames))

        global jointTimer
        if jointTimer == None:
            print "Starting joint timer"
            jointTimer = RepeatedTimer(1, sendPositions)
示例#15
0
    def recv_connect(self):
        self.subscribed = True
        self.framerate = 2
        print "Camera channel connected"

        def sendImage():
            frame = imageHandler.getLatestFrame()
            self.broadcast_event("image", frame.encode('base64'))

        global cameraTimer
        if cameraTimer == None:
            print "Starting camera timer"
            cameraTimer = RepeatedTimer(1.0 / self.framerate, sendImage)
示例#16
0
def main():
    camera_timer = RepeatedTimer(60, take_image)

    while (True):
        if get_sunrise() < datetime.now() < get_sunset():
            camera_timer.start()
        else:
            camera_timer.stop()

        time.sleep(60)
示例#17
0
文件: bot_el.py 项目: LiliyaSm/bot_el
    def run(self):
        rt = RepeatedTimer(
            1800, self.change_glade)  # it auto-starts, no need of rt.start()
        if self._flag:
            print(time.localtime())
            buttons = [(645, 430), (840, 425), (1060, 460), (1272, 453)]
            for i in range(4):
                mouse.left_click(1860, 1035)
                mouse.left_click(buttons[i][0], buttons[i][1])
                time.sleep(4)
                check_feeding()
                check_missions()

            print("checking glade")
            print("sleep")
            time.sleep(300)

            self._flag = False
示例#18
0
def saveEmailPreferences():
	global email
	global preferenceList
	global emailJobs

	headers = {'Content-Type': 'text/html'}
	_send = request.form['emailCheck']
	_numPosts = request.form['numPosts']
	_freq = request.form['emailFreq']
	_email = userEmail
	
	if _numPosts and _freq:
		cursor.callproc('sp_updateUserAccount', (_email, _send, _freq, _numPosts))
		data = cursor.fetchall()
		if len(data) is 1:
			conn.commit()
		emailJobs[_email]['send'] = _send
		emailJobs[_email]['freq'] = _freq
		emailJobs[_email]['numPosts'] = _numPosts
		print "freq: "+str(_freq)
		print type(_freq)
		if emailJobs[_email]['timer'] is not None:
   	             emailJobs[_email]['timer'].stop()
		if _send == u'1':
			
			freqCount = 0
                	#pd = getPostsForEmail(_email, _numPosts)
                	sendEmail("*****@*****.**", _email, int(_numPosts))
                	if _freq == u'1':
                       		freqCount = 604800
                	elif _freq == u'2':
                       		freqCount = 302400
               		elif _freq == u'3':
                       		freqCount = 201600
               		else:
                       		freqCount = 3600#86400
			#newpd = getPostsForEmail(_email, _numPosts)
               		rt = RepeatedTimer(freqCount, sendEmail, "*****@*****.**", _email, _numPosts)
			emailJobs[_email]['timer'] = rt
		else:
			emailJobs[_email]['timer'] = None
		return make_response("Email prefs added", 200, headers)
	else:
		return make_response("Couldn't save email prefs", 200, headers)
示例#19
0
def emails():
	global emailJobs	

	headers = {'Content-Type': 'text/html'}
	cursor.callproc('sp_getAllEmailData')
	data = cursor.fetchall()
	if len(data) > 0:
		conn.commit()
	for user in data:
		newDict = {}
		newDict['send'] = user[1]
		newDict['numPosts'] = user[2]
		newDict['freq'] = user[3]
#Create timer
		if user[1] == 1:  
			freqCount = 0
			f = user[3]
			userEmail = user[0]
			num = user[2]
			#pd = getPostsForEmail(user[0], user[2])
			sendEmail("*****@*****.**", user[0], user[2])
			if f == 1:
               			freqCount = 604800
       			elif f == 2:
				freqCount = 302400
			elif f == 3:
				freqCount = 201600
			else: #every day
				freqCount = 3600#86400
			#newpd = getPostsForEmail(user[0], user[2])
       			rt = RepeatedTimer(freqCount, sendEmail, "*****@*****.**", userEmail, num)
	# sent in user email and numposts for call to getPostsForEmail
			newDict['timer'] = rt
		else:
			newDict['timer'] = None
		emailJobs[user[0]] = newDict
	return None
def main():
	try:
		if len(sys.argv) == 2:
			read_config(sys.argv[1])
		else:
			read_config("./config.ini")
		init()
		camera.vflip = config.getboolean('capture', 'vertical_flip')
		camera.hflip = config.getboolean('capture', 'horizontal_flip')
		try:
			camera.resolution = (int( config.get('capture', 'width') ), int( config.get('capture', 'height') ))
			print "Using resolution %sx%s" % (int( config.get('capture', 'width') ), int( config.get('capture', 'height') ))
		except:
			camera.resolution = (2592, 1944)
			print "Using default resolution (%dx%d)" % default_resolution
#		time.sleep(2)
		camera.start_preview()
		print "Using interval %ds" % interval
		rt = RepeatedTimer(interval, capture)
		while (True):
			time.sleep(60)
	finally:
		camera.stop_preview()
		camera.close()
示例#21
0
    def ARPCLI(self):
        if self.thread is None:
            if self.PiIP == "" or self.PiIP is None:
                print("IP of the Pi-hole was not set, please run Discovery first.")
                return
            print("You are about to initiate ARP poisoning with settings: ")
            print("   NetworkInterface: " + self.conf.getNetworkInterface())
            setting = '{}'.format(self.conf.getARPtarget())
            if len(setting) == 2:
                print("   ARPtargets: " + self.conf.getDNSsetting())
            else:
                print("   ARPtargets: " + setting)

            print("   ARPdelay:  {} sec".format(self.conf.getARPdelay()))

            inp = input("Do you want to continue? (Y/n): ")

            if inp.lower().strip() == "y" or inp.lower().strip() == "yes" or len(inp.strip()) == 0:

                # ARP poisoning, initial call

                # If target is all hosts on DNS server's subnet
                if len(setting) == 2:
                    print("Performing poisoning on " + self.conf.getDNSsetting())
                    if self.arp.poison_all(self.conf.getDNSsetting(), self.PiIP, self.arp.get_dns_mac(self.PiIP)):
                        self.ARPresult = True

                # Otherwise
                else:
                    print("Performing poisoning on " + self.conf.getARPtarget())
                    if self.arp.poison_all(self.conf.getARPtarget(), self.PiIP, self.arp.get_dns_mac(self.PiIP)):
                        self.ARPresult = True

                if self.ARPresult:
                    print("Pi-hole was successfully poisoned")
                    # ARP poisoning, threading
                    self.thread = RepeatedTimer(self.conf.getARPdelay(), self.ARPPoisoning, setting)
                    self.thread.start()

                    self.mainText = "Enter the number of the method you want to use:\n\
                            1. Pi-hole discovery\n\
                            2. Stop ARP Poisoning\n\
                            3. DNS Poisoning\n\
                            4. Exit\n"
                    return
                else:
                    print("Poisoning was not successful. Please try again.")
                    return
            elif inp.lower().strip() == "n" or inp.lower().strip() == "no":
                return
            else:
                print("Invalid answer, please answer Y or N\n")
                self.ARPCLI()
                return

        # ARP Poisoning already running
        else:
            inp = input("You are about to stop the ARP poisoning, are you sure? (Y/N)")
            if inp.lower().strip() == "y" or inp.lower().strip() == "yes" or len(inp.strip()) == 0:
                # Stop thread and restore ARP tables
                self.thread.stop()
                self.arp.restore_all(self.conf.getARPtarget(), self.PiIP, self.arp.get_dns_mac(self.PiIP))
                self.thread = None
                print("ARP poisoning successfully stopped.")
                self.mainText = "Enter the number of the method you want to use:\n\
                        1. Pi-hole discovery\n\
                        2. ARP Poisoning\n\
                        3. DNS Poisoning\n\
                        4. Exit\n"
                return
            elif inp.lower().strip() == "n" or inp.lower().strip() == "no":
                print("Cancelling...")
                return
            else:
                print("Invalid answer, please answer Y or N\n")
                self.ARPCLI()
                return
示例#22
0
class CLI:

    conf = Configuration()
    disc = Discovery(conf.getNumberOfHosts(), conf.getSimilarResponses(), conf.getNumberOfHosts())
    dns = None
    arp = Arp()
    PiIP = ""
    ARPresult = False
    thread = None

    mainText = "Enter the number of the method you want to use:\n\
        1. Pi-hole discovery\n\
        2. ARP Poisoning\n\
        3. DNS Poisoning\n\
        4. Exit\n"




    def mainCLI(self):
        while True:
            inp = input(self.mainText)
            if inp.lower().strip() == "1":  # Discovery
                self.discoveryCLI()
            elif inp.lower().strip() == "2":  # ARP Poisoning
                self.ARPCLI()
            elif inp.lower().strip() == "3":  # DNS Poisoning
                self.DNSCLI()
            elif inp.lower().strip() == "4":  # Exit
                print("Quitting...")
                if self.thread is not None:
                    print("   Stopping ARP poisoning")
                    self.thread.stop()
                sys.exit()
            else:  # Error
                print("Please only enter a number 1-4\n")


    # =========================== Discovery ==============================

    def discoveryCLI(self):
        print("You are about to search for the Pi-hole with settings: ")
        print("   DnsQueryTimeout:  {} ms".format(self.conf.getDNSQueryTimeout()))
        print("   SimilarResp:      {}%".format(self.conf.getSimilarResponses()))
        print("   NumberOfHosts:    {}".format(self.conf.getNumberOfHosts()))
        print("   DNSServer:        {}".format(self.conf.getDNSsetting()))
        print("   HostsURL          {}".format(self.conf.getHostsURL()))
        inp = input("Do you want to continue? (Y/n): ")

        if inp.lower().strip() == "y" or inp.lower().strip() == "yes" or len(inp.strip()) == 0:
            print("\n")
            self.PiIP = self.disc.getPi(self.conf.getDNSQueryTimeout(), self.conf.getDNSsetting())
            if not self.PiIP == None:
                print("Pi-hole was found at " + self.PiIP + "\nYou can continue with ARP Poisoning")
            else:
                print("No Pi-hole was found")
            return
        elif inp.lower().strip() == "n" or inp.lower().strip() == "no":
            return
        else:
            print("Invalid answer, please answer Y or N\n")
            self.discoveryCLI()
            return


    # ================================= ARP ====================================

    # For multi-threading
    def ARPPoisoning(self, setting):
        if len(setting) == 2:
            self.arp.poison_all(self.conf.getDNSsetting(), self.PiIP, self.arp.get_dns_mac(self.PiIP))
        else:
            self.arp.poison_all(self.conf.getARPtarget(), self.PiIP, self.arp.get_dns_mac(self.PiIP))


    def ARPCLI(self):
        if self.thread is None:
            if self.PiIP == "" or self.PiIP is None:
                print("IP of the Pi-hole was not set, please run Discovery first.")
                return
            print("You are about to initiate ARP poisoning with settings: ")
            print("   NetworkInterface: " + self.conf.getNetworkInterface())
            setting = '{}'.format(self.conf.getARPtarget())
            if len(setting) == 2:
                print("   ARPtargets: " + self.conf.getDNSsetting())
            else:
                print("   ARPtargets: " + setting)

            print("   ARPdelay:  {} sec".format(self.conf.getARPdelay()))

            inp = input("Do you want to continue? (Y/n): ")

            if inp.lower().strip() == "y" or inp.lower().strip() == "yes" or len(inp.strip()) == 0:

                # ARP poisoning, initial call

                # If target is all hosts on DNS server's subnet
                if len(setting) == 2:
                    print("Performing poisoning on " + self.conf.getDNSsetting())
                    if self.arp.poison_all(self.conf.getDNSsetting(), self.PiIP, self.arp.get_dns_mac(self.PiIP)):
                        self.ARPresult = True

                # Otherwise
                else:
                    print("Performing poisoning on " + self.conf.getARPtarget())
                    if self.arp.poison_all(self.conf.getARPtarget(), self.PiIP, self.arp.get_dns_mac(self.PiIP)):
                        self.ARPresult = True

                if self.ARPresult:
                    print("Pi-hole was successfully poisoned")
                    # ARP poisoning, threading
                    self.thread = RepeatedTimer(self.conf.getARPdelay(), self.ARPPoisoning, setting)
                    self.thread.start()

                    self.mainText = "Enter the number of the method you want to use:\n\
                            1. Pi-hole discovery\n\
                            2. Stop ARP Poisoning\n\
                            3. DNS Poisoning\n\
                            4. Exit\n"
                    return
                else:
                    print("Poisoning was not successful. Please try again.")
                    return
            elif inp.lower().strip() == "n" or inp.lower().strip() == "no":
                return
            else:
                print("Invalid answer, please answer Y or N\n")
                self.ARPCLI()
                return

        # ARP Poisoning already running
        else:
            inp = input("You are about to stop the ARP poisoning, are you sure? (Y/N)")
            if inp.lower().strip() == "y" or inp.lower().strip() == "yes" or len(inp.strip()) == 0:
                # Stop thread and restore ARP tables
                self.thread.stop()
                self.arp.restore_all(self.conf.getARPtarget(), self.PiIP, self.arp.get_dns_mac(self.PiIP))
                self.thread = None
                print("ARP poisoning successfully stopped.")
                self.mainText = "Enter the number of the method you want to use:\n\
                        1. Pi-hole discovery\n\
                        2. ARP Poisoning\n\
                        3. DNS Poisoning\n\
                        4. Exit\n"
                return
            elif inp.lower().strip() == "n" or inp.lower().strip() == "no":
                print("Cancelling...")
                return
            else:
                print("Invalid answer, please answer Y or N\n")
                self.ARPCLI()
                return

    # ================================= DNS ===================================

    def DNSCLI(self):
        if not self.ARPresult:
            print("ARP Poisoning was not completed successfully, please do this first.")
            return
        print("You are about to replace DNS responses of the Pi-hole with settings: ")
        print("   PoisonType:      {}".format(self.conf.getPoisonType()))
        print("   ReplaceIP:       {}".format(self.conf.getReplaceIP()))
        print("   SpoofingTimeout: {}".format(self.conf.getSpoofingTimeout()))
        inp = input("Do you want to continue? (Y/n): ")

        if inp.lower().strip() == "y" or inp.lower().strip() == "yes" or len(inp.strip()) == 0:
            # Ask if we should run in verbose mode
            verbose = input("Do you want to run in verbose mode? (Y/n): ")
            if verbose.lower().strip() == "y" or verbose.lower().strip() == "yes" or len(verbose.strip()) == 0:
                self.dns = Dns(self.PiIP, self.conf.getReplaceIP(), self.conf.getPoisonType(), self.conf.getNetworkInterface(), True)
            else:
                self.dns = Dns(self.PiIP, self.conf.getReplaceIP(), self.conf.getPoisonType(), self.conf.getNetworkInterface(), False)
            print("\n")
            # Start spoofing
            self.dns.poison()
        elif inp.lower().strip() == "n" or inp.lower().strip() == "no":
            return
        else:
            print("Invalid answer, please answer Y or N\n")
            self.DNSCLI()
            return
示例#23
0
    def start(self, starting_num_cars, inflow, amount_of_inflow, time_end,
              fig):

        #Starting number of cars

        self.initialize_cars(starting_num_cars)

        #Inflows over time
        filharmonia_list = [0]
        idziego_list = [0]
        poczta_list = [0]
        slowackiego_list = [0]
        bagatela_list = [0]

        making_file_statistic()
        thread = threading.Thread(target=run_stats)

        # initialize
        pygame.init()

        # create screen
        screen = pygame.display.set_mode(resolution)

        # running condition and title
        running = True
        pygame.display.set_caption("Cracow Road Simulation")

        # time delay
        clockobject = pygame.time.Clock()
        tick = 10

        # background color
        screen.fill(self.colors["black"])

        # draw road
        self.initialize_points(screen)

        # pause and velocity message
        text = [
            'To Pause press P To Continue press C', 'Average V: ',
            'Average V_max: ', 'Percentage difference: ', 'Iteration: ',
            'km/h', 'Number of Cars: ', 'Time: ', 'Inflow: ',
            'Number of Inflow: ', 'Starting number of cars: '
        ]
        message(screen, (self.resolution[0] // 2, self.resolution[1] // 2),
                self.colors, text[0])
        message(screen, (100, 50), self.colors, text[1])
        message(screen, (450, 50), self.colors, text[5])
        message(screen, (145, 100), self.colors, text[2])
        message(screen, (450, 100), self.colors, text[5])
        message(screen, (200, 700), self.colors, text[3])
        message(screen, (90, 800), self.colors, text[4])
        message(screen, (140, 750), self.colors, text[6])
        message(screen, (50, 850), self.colors, text[7])
        message(screen,
                (self.resolution[0] // 2 - 200, self.resolution[1] // 2 - 100),
                self.colors, text[8] + str(inflow))
        message(screen,
                (self.resolution[0] // 2 + 200, self.resolution[1] // 2 - 100),
                self.colors, text[9] + str(inflow_number))
        message(screen,
                (self.resolution[0] // 2, self.resolution[1] // 2 - 200),
                self.colors, text[10] + str(starting_num_cars))

        # thread for counting time - to handle traffic lights
        rt = RepeatedTimer(1.00, start_traffic_lights, points, screen)

        try:
            #thread.start()
            tab = [0, 0]

            # start timer
            start_time = dt.datetime.today().timestamp()

            # Main Loop
            time.sleep(1)
            while running:
                clockobject.tick(tick)
                time_diff = dt.datetime.today().timestamp() - start_time

                tab[1] = tab[0]
                tab[0] = int(time_diff)
                if tab[0] - tab[1] == 1 and tab[0] % inflow == 0:
                    self.generate_car_on_each_intersection(amount_of_inflow)
                    filharmonia_list.append(outflows['filharmonia'])
                    idziego_list.append(outflows['idziego'])
                    poczta_list.append(outflows['poczta'])
                    slowackiego_list.append(outflows['slowackiego'])
                    bagatela_list.append(outflows['bagatela'])

                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        running = False
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_p:
                            pause(clockobject)
                        elif event.key == pygame.K_RIGHT:
                            tick = max(tick + 5, 3)
                        elif event.key == pygame.K_LEFT:
                            tick = max(tick - 5, 3)

                for car in self.cars:
                    car.move(screen, points)

                self.check_if_reached_end()
                #self.random_initialize(70)

                add_stats(self.cars, self.iteration, time_diff)
                self.iteration += 1
                show_statistics(screen, self.colors)

                pygame.display.update()

                if (time_diff > time_end):
                    running = False

        finally:
            rt.stop()

            #ploting
            plot_numcars_v(inflow, amount_of_inflow, fig, starting_num_cars)
            plot_t_numcars(inflow, amount_of_inflow, fig, starting_num_cars)
            plot_t_v(inflow, amount_of_inflow, fig, starting_num_cars)
            plot_inflow(filharmonia_list, idziego_list, poczta_list,
                        slowackiego_list, bagatela_list, inflow,
                        amount_of_inflow, fig, starting_num_cars)
            outflow = [
                filharmonia_list, idziego_list, poczta_list, slowackiego_list,
                bagatela_list
            ]
            final_data_append(fig, starting_num_cars, outflow)
示例#24
0
        client = pymongo.MongoClient("localhost", 27017)
        db = client['ohmni']
        collection = db.instagramData

        for post in json:
            post['_datetime'] = datetime.datetime.utcnow()
            id = collection.insert(post, continue_on_error=True)
            print(str(id))
        client.close()
    except pymongo.errors.DuplicateKeyError:
        pass

if __name__ == '__main__':

    getData()
    rt = RepeatedTimer(30, getData)
    try:
        while True:
            sys.stdout.write('\r')
            sys.stdout.write('|')
            sys.stdout.write('\r')
            sys.stdout.flush()
            sys.stdout.write('/')
            sys.stdout.write('\r')
            sys.stdout.flush()
            sys.stdout.write('-')
            sys.stdout.write('\r')
            sys.stdout.flush()
            sys.stdout.write('\\')
            sys.stdout.write('\r')
            sys.stdout.flush()
示例#25
0
def scheduleTask(currencies, window):
    rt = RepeatedTimer(3, tikBTC, currencies)
    return rt
示例#26
0

from ScenarioParser import ScenarioParser
from UdpAgent import UdpSender
from RepeatedTimer import RepeatedTimer

from time import sleep
#import time

if __name__ == '__main__':
	sp = ScenarioParser("scenario.yaml")
	scenario = sp.get_scenario()

	udpSender = UdpSender((scenario["ip"],scenario["port"]))

	if (scenario["direction"] == "out"):
		rt = RepeatedTimer(1, udpSender.send, scenario["data"])

	try:
	    sleep(5) # your long-running job goes here...
	finally:
	    rt.stop() # better in a try/finally block to make sure the program ends!
示例#27
0
    # Setup Cyton Biosensing board
    loop = 0
    while True:
        cytonBrd = setupCytonDongle()
        loop += 1
        if cytonBrd != 0:
            break
        if loop > 10:
            os.system('reboot now')

    # Sleep to allow mote to warm up
    time.sleep(0.5)

    print "Set timer to send data repeatedly...",
    mote_timer = RepeatedTimer(60, send_packet_over_lora, mote)
    print "Done"

    loop = 0
    while True:
        loop += 1
        isConnected = cytonBrd.start_stream()
        if isConnected == 1:
            break
        if loop > 10:
            os.system('reboot now')

    while True:
        cytonBrd.read_line()

        if cytonBrd.is_window_full():
示例#28
0
class Sequencer:
    def __init__(self, sound, sequence=[0], bpm=120):
        self._sound = sound
        if len(sequence) > 0:
            self._sequence = sequence
        else:
            raise SequencerException("please provide a sequence as a list with length > 0.")
        self._repetitions = 0
        self._sequence_index = 0
        self._repetitions_played = 0
        self._bpm = bpm
        self._interval = self.bpm_to_interval(self.bpm)
        self._timer = RepeatedTimer(self._interval, self.execute_sequence_index)

    @property
    def sound(self):
        return self._sound

    @sound.setter
    def sound(self, sound):
        self._sound = sound

    @property
    def sequence(self):
        return self._sequence

    @sequence.setter
    def sequence(self, sequence):
        if len(sequence) > 0:
            self._sequence = sequence
        else:
            raise SequencerException("please provide a sequence as a list with length > 0.")

    @property
    def bpm(self):
        return self._bpm

    @bpm.setter
    def bpm(self,bpm):
        self._bpm = bpm

    def bpm_to_interval(self, bpm):
        # translates to 1/16th notes
        return 15/bpm

    def play(self,repetitions):
        self._repetitions = repetitions
        self._timer.start()
        print(self._sound.path, "started")

    def stop(self):
        self._timer.stop()

    def execute_sequence_index(self):
        if(self.sequence[self._sequence_index] == 1):
            self._sound.play()
            print(self._sound.path,1)
        else:
            print(self._sound.path,0)

        self._sequence_index += 1
        if self._sequence_index >= len(self._sequence):
            self._sequence_index = 0
            self._repetitions_played += 1
            if(self._repetitions_played == self._repetitions and self._repetitions != 0):
                print(self._sound.path, "sequence ended")
                self.stop()
                self._sound.wait_done()
示例#29
0
import os, sys
import json
from sets import Set
from time import sleep
from CVEClassCveDetails import CVEClassCveDetails
from RepeatedTimer import RepeatedTimer

print "Starting the security bot..."

cveClass = CVEClassCveDetails()
cveClassRt = RepeatedTimer(300, cveClass.cveUpdate)  # Update every 5 minutes
cvePostRt = RepeatedTimer(1680,
                          cveClass.dequeueMessage)  # Post every 28 minutes

try:
    while True:
        sleep(60)
except Exception as e:
    e.msg()
finally:
    cveClassRt.stop()
    cvePostRt.stop()
示例#30
0
def main():
    global window
    sg.theme('DarkAmber')  # Add a touch of color

    rowsCurrencies = ['BTCBUSD', 'ADABUSD']

    # All the stuff inside your window.
    layout = [
        *[[sg.Text('', size=(22, 1), key=curr + '_output')]
          for curr in rowsCurrencies], [sg.InputText(size=(22, 1))],
        [sg.Button('add', key='add'),
         sg.Button('exit')]
    ]

    # Create the Window
    window = sg.Window('cryptoWidgetX',
                       layout,
                       no_titlebar=True,
                       grab_anywhere=True,
                       keep_on_top=True,
                       background_color='white',
                       alpha_channel=.6,
                       margins=(0, 0),
                       finalize=True)

    # number of buttons to add
    rows_number = 0

    tikBTC(rowsCurrencies.copy())

    rt = scheduleTask(rowsCurrencies.copy(), window)

    # Event Loop to process "events" and get the "values" of the inputs
    while True:
        event, values = window.read()
        if event == sg.WIN_CLOSED or event == 'exit':  # if user closes window or clicks cancel
            rt.stop()
            break
        if event == 'add':

            rt.stop()

            rowsCurrencies.append(values[0])

            rows_number += 1

            layout = [
                *[[sg.Text('', size=(22, 1), key=curr + '_output')]
                  for curr in rowsCurrencies],
                [sg.Button('add', key='add'),
                 sg.Button('exit')]
            ]

            window1 = sg.Window('cryptoWidgetX',
                                layout,
                                location=window.CurrentLocation(),
                                no_titlebar=True,
                                grab_anywhere=True,
                                keep_on_top=True,
                                background_color='white',
                                alpha_channel=.6,
                                margins=(0, 0),
                                finalize=True)

            rt = RepeatedTimer(3, tikBTC, rowsCurrencies)

            window.Close()
            window = window1
    window.close()
示例#31
0
 def on_subscribe(self, client, userdata, mid, granted_qos):
     """
     sets update timer/interval for map
     """
     self.rep_timer = RepeatedTimer(1000, self.show_map)
    global min
    global avg

    print "logged@{}, min={}, avg={}".format(time.time(), min, avg)
    logToFile(min, avg)
    resetValues()


# function to log mouse coords to console
def printMouseCoords(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDBLCLK:
        print "Mouse at ({},{})".format(x, y)


# repeated timer for logging each x seconds
rt = RepeatedTimer(logInterval, collect)

# prepare windows for opencv and mouse listener
cv2.namedWindow('original')
cv2.setMouseCallback('original', printMouseCoords)

# infinite loop
while 1:
    # 1) read the next frame
    frame = cap.read()

    # 2) convert current frame to gray and improve contrast with CLAHE (Contrast Limited Adaptive Histogram Equalization)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    cl1 = clahe.apply(gray)
示例#33
0
class Elevator(object):
    'An elevator'
    elevator_count = 0
    def __init__(self, building, name, current_floor):
        self.name = name
        self.current_floor = current_floor
        self.building = building
        self.destination_floor = []
        self.active_calls = []
        self.SPEED = 1 # s / floor
        self.TIME_AT_FLOOR = 5 # s / floor
        Elevator.elevator_count += 1
        self.run_timer = RepeatedTimer(self.SPEED, self.execute_call())
             
    def start_elevator(self):
        self.run_timer.start()
        
    def get_name(self):
        return self.name
        
    def get_current_floor(self):
        return self.current_floor
        
    def get_destination_floor(self):
        return self.destination_floor

    def get_direction(self):
        if not self.destination_floor:# or len(self.destination_floor) == 0:
            return 0
        else:
            return numpy.sign(self.destination_floor[0] - self.current_floor)       
    
    def get_speed(self):
        return self.SPEED
        
    def get_time_to_floor(self, floor):
        distance_to_destination = abs(floor - self.get_current_floor())  
        time_to_destination = self.get_speed()*distance_to_destination
        return time_to_destination
    
    def set_current_floor(self, floor):
        self.current_floor = floor
      
    def set_destination_floor(self, floor, on_the_way = False):
        if self.current_floor != floor:
            if on_the_way:
                self.destination_floor = [floor] + self.destination_floor
            else:
                self.destination_floor.append(floor)
               
    def execute_call(self):
        ''' checks if there is a call to execute. if yes, run elevator '''
        print('execute_call()')
        if self.active_calls:
            print("I got a call, Elevator " + str(self.name) + " will start!")
            self.run_timer.stop()
            self.run_elevator()
    
    def run_elevator(self):
        curret_call = self.active_calls[0]
        while self.current_floor != self.destination_floor[0]:
            new_floor = self.current_floor + self.get_direction() 
            self.set_current_floor(new_floor)
            sleep(self.SPEED)
        
        self.stop_at_floor(curret_call)

    def stop_at_floor(self, call):
        floor = call.get_floor()
        print ("Elevator " + str(self.name) + " now at floor " + str(floor) + ".")
        sleep(self.TIME_AT_FLOOR)
        self.destination_floor = [x for x in  self.destination_floor if x != floor]
        call.get_selected_floor()
        self.run_timer.start()

    def recieve_call(self, call):
        print ("Elevator " + str(self.name) + "has recieved a call.")
        self.active_calls.append(call)
        self.set_destination_floor(call.get_floor(), call.get_on_the_way())

    def stop_elevator(self):
        print ("Elevator to stop: " + str(self.name))
        if self.get_elevator_status() == "Running":
            self.run_timer.stop()
    
    def get_elevator_status(self):
        if self.run_timer.isRunning():
            return "Running"
        else: 
            return "Terminated"
示例#34
0
        print("Detectou")
        face_appearance_[0] = face_appearance_[0] + 1
        if face_appearance_[0] >= 10:
            application.stop()
            face_appearance_[0] = 0
            print("CRIOU IMAGEM")
            cv2.imwrite('face_img.jpg', frame)
            # Read the binary file to send data to API
            body = ""
            filename = 'face_img.jpg'
            f = open(filename, "rb")
            body = f.read()
            f.close()
            application.start()
    else:
        face_appearance_[0] = 0


# load serialized model from disk
# net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
net = cv2.dnn.readNetFromCaffe("deploy.prototxt.txt",
    "res10_300x300_ssd_iter_140000.caffemodel")

# initialize the video stream
# change src=0 to the camera source input
vs = VideoStream(src=0).start()
time.sleep(1.0)

# Calls detect_face every time_sec_ seconds
application = RepeatedTimer(time_sec_, detect_face, vs)
示例#35
0
def main():
    #Read config.ini file
    config_object = ConfigParser()
    init_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             'config.ini')
    config_object.read(init_file)

    # The file in which the data will be written into
    output_file_name = config_object.get("SETTINGS", "output_file_name")
    # Number of different scenarios to run
    num_of_iter = int(config_object.get("SETTINGS", "num_of_iter"))
    # Simulation time factor which is set in the settings.json file of AirSim
    sim_time_factor = int(config_object.get("SETTINGS", "sim_time_factor"))
    # The malicious behaviour type
    anomaly_type = config_object.get("SETTINGS", "anomaly_type")
    # If True, after getting the data it will get tested and updated by 'test.py' script
    active_data_test = config_object.get("SETTINGS", "active_data_test")

    # Time until next_action() and has_ended() is called again
    update_cycle_time = 0.1 / sim_time_factor

    # headers for csv file
    data_keys = [
        'drone', 'update_step', 'iter', 'script_time', 'sim_time', 'latitude',
        'longitude', 'altitude', 'angular_acceleration_x',
        'angular_acceleration_y', 'angular_acceleration_z',
        'angular_velocity_x', 'angular_velocity_y', 'angular_velocity_z',
        'linear_acceleration_x', 'linear_acceleration_y',
        'linear_acceleration_z', 'linear_velocity_x', 'linear_velocity_y',
        'linear_velocity_z', 'orientation_x', 'orientation_y', 'orientation_z',
        'position_x', 'position_y', 'position_z', 'collision', 'label'
    ]

    data = {data: [] for data in data_keys}

    drones = ["Drone1", "Drone2", "Drone3", "Drone4", "Drone5"]

    # Connect to the regular client
    client = airsim.MultirotorClient()
    client.confirmConnection()

    # Connect to the Monitor's client which is used by the monitor function
    client_monitor = airsim.MultirotorClient()
    client_monitor.confirmConnection()

    [client_monitor.enableApiControl(True, drone) for drone in drones]
    [client_monitor.armDisarm(True, drone) for drone in drones]

    # Dictionary of values that describe the current iteration state
    # It is used by the monitor function
    values = {
        "i": 0,
        "update_step": 0,
        "start": 0,
        "is_anomaly": False,
        "malicious": None,
        "collision": None
    }

    # Start the scenarios - each iteration is a new scenario
    for i in range(num_of_iter):

        [client.enableApiControl(True, drone) for drone in drones]
        [client.armDisarm(True, drone) for drone in drones]

        print(f'Iteration: {i}')
        values["i"] = i

        # On the first iteration, the drones need to take off first
        if i == 0:
            [client.takeoffAsync(vehicle_name=drone) for drone in drones]
            time.sleep(6)

        # Randomly choose a malicious drone
        malicious = random.sample(drones, 1)[0]
        values["malicious"] = malicious
        # After time_till_anoamly passes, the malicious drone starts acting maliciously
        time_till_anomaly = np.random.uniform(10, 15) / sim_time_factor

        print(f'starting new scenario with malicious: {malicious}')

        # Drones' initial positions which are also set in the settings.json file of AirSim
        initial_positions = ([[2, 0, -2], [4, 0, -2], [6, 0, -2], [8, 0, -2],
                              [10, 0, -2]])

        # Optional : use trace line to see the routes of the drones
        [client.simSetTraceLine([0.0], 20.0, drone) for drone in drones]

        # Creating the avoidance scenario class
        scenario = Simple(client, drones, initial_positions, malicious,
                          anomaly_type, sim_time_factor)

        # Get the beginning time for later measures
        start = time.perf_counter()
        values["start"] = start

        values["update_step"] = 0

        time_from_beginning = 0

        # When has_ended is True, the scenario will end
        has_ended = False
        # When is_anomaly is True, the malicious behaviour will start
        is_anomaly = False
        values["is_anomaly"] = False

        time.sleep(0.5)

        # Create the RepeatedTimer class with the monitor function, which monitors the scenario data
        # By creating the object, the function starts running and repeats itself every 0.05 seconds
        rt = RepeatedTimer(0.05, monitor, data, drones, client_monitor, values)

        while not has_ended:
            record_time = time.perf_counter()
            # Call the next action of the drones, which gets them to recalculate their movement
            scenario.next_action()
            # Check if the scenario has ended
            has_ended = scenario.has_ended()
            # Check if a collision has occured
            values["collision"] = scenario.get_collision()

            # If enough time has passed, the anomaly begins
            if time_from_beginning > time_till_anomaly and anomaly_type != "none" and not is_anomaly:
                print("starts anomaly")
                is_anomaly = True
                values["is_anomaly"] = True
                # Optional - set the malicious drone's path to have another color
                client.simSetTraceLine([1.0], 20.0, malicious)

            # If the anomaly has started, call the malicious behavior function
            if is_anomaly:
                scenario.next_action_anomaly()

            # calculating the time that passed since the beginning of the scenario
            current = time.perf_counter()
            time_from_beginning = current - start

            values["update_step"] += 1

            # If not enough time has passed until the next action should happen, sleep
            try:
                time.sleep(update_cycle_time - (current - record_time))
            except:
                print("passing")

        # When the scenario ends, the RepeatedTimer stops recording and the client resets
        rt.stop()
        client.reset()

    # Disconnect from the client
    [client.armDisarm(False, drone) for drone in drones]
    [client.enableApiControl(False, drone) for drone in drones]

    print('finished mission')

    # Write the data to the output file
    data_df = pd.DataFrame.from_dict(data)
    data_df.to_csv(output_file_name, index=False)

    if active_data_test == "True":
        test_data(output_file_name)