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()
Exemplo n.º 2
0
def startTimer(name):
    isSend = True
    rt = RepeatedTimer(90, getPubKey, name)
    try:
        sleep(600)
    finally:
        rt.stop()
Exemplo n.º 3
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)
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()
Exemplo n.º 5
0
def startServer():
    try:
        print("I'm working...")
        rt = RepeatedTimer(15, shakhesBource)
        rt = RepeatedTimer(35, detectVolume)
        rt = RepeatedTimer(1000, car)
        rt = RepeatedTimer(800, currency)
        rt = RepeatedTimer(700, digital_currency)
        # rt = RepeatedTimer(500, timeVolume)

        try:
            sleep(14400)
        finally:
            rt.stop()
    except ZeroDivisionError:
        logging.exception("message")
Exemplo n.º 6
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))
Exemplo n.º 7
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)
Exemplo n.º 8
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!
Exemplo n.º 9
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)
Exemplo n.º 10
0
        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()
    finally:
        rt.stop()
Exemplo n.º 11
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()
Exemplo n.º 12
0
GPIO.setup(grohbotconfig.dht_ground_relay_pin, GPIO.OUT)
GPIO.output(grohbotconfig.dht_ground_relay_pin, GPIO.HIGH)

# pins not being used, still turning them off at startup
GPIO.setup(grohbotconfig.bottom_fan_pin, GPIO.OUT)
GPIO.output(grohbotconfig.bottom_fan_pin, GPIO.HIGH)
GPIO.setup(grohbotconfig.top_light_pin, GPIO.OUT)
GPIO.output(grohbotconfig.top_light_pin, GPIO.HIGH)
GPIO.setup(grohbotconfig.not_used_pin, GPIO.OUT)
GPIO.output(grohbotconfig.not_used_pin, GPIO.HIGH)

# Initial the dht device, with data pin connected to:
dhtDevice = adafruit_dht.DHT22(grohbotconfig.dht22_pin)

save_config_to_file(grohbotconfig)
save_device_states_to_file(devices)
save_temps_to_file(70, 30)

ftemp, humidity = get_temps_from_file()
devices = set_states_by_logic(ftemp, humidity, devices)
save_device_states_to_file(devices)

timer = RepeatedTimer(check_mode_seconds, tick_tock)

print_lcd_line_0("GROHBOT ACTIVE")

message = input("Press enter to quit\n")  # Run until someone presses enter
print("QUITTING")
GPIO.cleanup()  # Clean up
timer.stop()  # stop timer
Exemplo n.º 13
0
                            action="store_true",
                            help="Extra level of verbosity")
        cmd_args = parser.parse_args()
        manager = CollectorManager(ROOT, forget_state=cmd_args.drop)

        print(cmd_args)

        INTERVAL = 120

        def collect():
            if manager.is_old():
                manager.take_collected()
                print_if_verbose("new manager created")

        manager.collect()
        manager.save_state
        print_if_verbose("collected")

        timer = RepeatedTimer(INTERVAL, collect)
        collect()  # timer will call only after interval passes
        while running:
            pass
    except Exception as e:
        with open("data/collector_manager/last_error.txt", "w") as f:
            f.write(traceback.format_exc())
            f.close()
        raise e
    finally:
        print("Cleaning up")
        timer.stop()
Exemplo n.º 14
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"
Exemplo n.º 15
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
Exemplo n.º 16
0
    # 5) apply threshold to frame: depending on pixel value, an array of 1s and 0s is created
    _, threshold = cv2.threshold(blur, 230, 255, cv2.THRESH_BINARY)
    # only apply to masked area
    t = cv2.bitwise_and(threshold, threshold, mask=area_mask)

    # count white pixels within defined polygon/mask
    free = np.count_nonzero(t)
    # calculate capacity in %
    capacity = 1 - float(free) / all

    # update variables
    updateStats(capacity)

    # remove comment to visualize counting area
    #cv2.fillPoly(frame, [AREA_PTS], (255, 0, 0))

    # show masked frame
    cv2.imshow('counting area', t)
    # show original frame
    cv2.imshow('original', frame)

    # wait for "ESC" being pressed to leave infinite loop
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cv2.destroyAllWindows()
cap.stop()
rt.stop()
Exemplo n.º 17
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()