Exemple #1
0
def runrouter(targetaddr, boundaddr, latency = 0.32, jitter = 0.05, loss = 1.0, onsend = None, ondrop = None, onexcept = None):
	latency, jitter = latency/2, jitter/2	# Half time there, half time home.
	targetaddr, boundaddr = [(socket.gethostbyname(addr[0]), addr[1]) for addr in [targetaddr, boundaddr]]
	sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)	# UDP
	sock.bind(boundaddr)
	scheduler = EternalScheduler()
	while True:
		try:
			data, fromaddr = sock.recvfrom(4096)
		except Exception as e:
			if onexcept: onexcept(e)
			continue
		if uniform(0.0, 100.0) < loss:
			if ondrop: ondrop()
			continue
		else:
			if onsend: onsend()
		delay = uniform(0.0, jitter)
		if fromaddr == targetaddr:
			# Server to client.
			scheduler.enter(delay, sock.sendto, (data, lastclientaddr))
		else:
			# Client to server.
			lastclientaddr = fromaddr
			scheduler.enter(delay, sock.sendto, (data, targetaddr))
Exemple #2
0
def main() -> None:
    try:
        # Raises an HTTPError exception if moodle is not properly up
        get_moodlepage().raise_for_status()

        # Create a .env file if it doesn't exist
        if not file_exists(".env"):
            create_default_env_file()
            log_with_time("The '.env' file has been created")

        # Get our session set up
        user_credentials = get_env_netname_credentials()
        session = get_session(user_credentials)

        # Get the fetch_and_notify function running repeatedly
        log_with_time("Starting scheduler")
        scheduler = sched.scheduler()
        scheduler.enter(0, 1, fetch_and_notify, (session, scheduler))
        scheduler.run()
    except HTTPError as e:
        log_with_time(f"HTTPError occured (status code is 4xx or 5xx):\n{e}")
    except (ConnectionError, Timeout) as e:
        log_with_time(
            f"Moodle website appears to be down (ConnectionError or Timeout):\n{e}"
        )
    except Exception as e:
        log_with_time(f"Exception:\n{e}")

    log_with_time(
        f"Rescheduling the main method to run in {get_scheduler_delay()} seconds"
    )
    scheduler = sched.scheduler()
    scheduler.enter(get_scheduler_delay(), 1, main)
    scheduler.run()
Exemple #3
0
 def callback(scheduler=None):
     if scheduler is None:
         scheduler = sched.scheduler(time.time, time.sleep)
         scheduler.enter(0,1,callback,([scheduler]))
         scheduler.run()
     scheduler.enter(.1,1,callback,([scheduler]))
     if self.ser.inWaiting() > 0:
         a = self.ser.read()
         self.queue.put(a)
Exemple #4
0
def query_event(now, scheduler, search_sched, event_handler, priority=0):
    def run():
        response = search_sched.query.execute()
        for evt in response.events():
            event_handler(evt)
        now = datetime.now()
        query_event(now, scheduler, search_sched, event_handler, priority)

    delay = search_sched.after(now, inc=True) - now
    print('delay is', delay)
    scheduler.enter(delay.total_seconds(), priority, run, ())
    return run
                        '--enable_log',
                        type=int,
                        help='',
                        required=False)

    args = parser.parse_args()

    if args.thingplug_host != None: THINGPLUG_HOST = args.thingplug_host
    if args.thingplug_port != None: THINGPLUG_PORT = args.thingplug_port
    if args.app_eui != None: THINGPLUG_APPEUI = args.app_eui
    if args.period_time != None: PERIOD_TIME = args.period_time
    if args.enable_log != None: args.enable_log = 1

    thingplug = ThingPlug.ThingPlug(THINGPLUG_HOST, THINGPLUG_PORT)
    thingplug.login(args.user_id, args.user_pw)

    thingplug.setAppEui(args.app_eui)

    if PERIOD_TIME == 0:
        status, data, lt_time = thingplug.getLatestData(
            args.node_id, args.container)
        current_time = str(datetime.datetime.now())
        output_data = current_time + ',' + data + ',' + lt_time + '\r\n'
        print output_data,
    else:
        while True:
            scheduler = sched.scheduler(time.time, time.sleep)
            param = (thingplug, args.node_id, args.container, args.enable_log)
            scheduler.enter(PERIOD_TIME, 1, fun_getLatestData, param)
            scheduler.run()
Exemple #6
0
def cyclic_scan(scan_interval, scheduler):
    # 循环扫描
    run_cleaning_tasks()
    scheduler.enter(scan_interval, 0, cyclic_scan, (scan_interval, scheduler))
    scheduler.run()
def periodic(scheduler, interval, action, actionargs=()):
    scheduler.enter(interval, 1, periodic,
                    (scheduler, interval, action, actionargs))
    action(*actionargs)
Exemple #8
0
def housekeeper(scheduler, interval, action, actionargs=()):
    scheduler.enter(interval, 1, housekeeper,
                    (scheduler, interval, action, actionargs))
    action(*actionargs)
Exemple #9
0
 def schedule(self, scheduler):
     "Schedule my events in given scheduler, events are handled by my output handler"
     for event in self.events:
         scheduler.enter(event[1], 0, self.output_handler, argument=event)
Exemple #10
0
def fetch_and_notify(session: Session, scheduler: scheduler) -> None:
    log_with_time(f"Fetching everything")

    # Check if the user is properly logged in
    while not is_logged_in(session):
        print("Not logged in, getting a new session", flush=True)
        session = get_session(get_env_netname_credentials())

    # Fetch the course links
    course_links = get_course_links(session)
    print(f"Course links: {course_links}")

    # Go through each course's page
    for course_link in course_links:
        course_page_soup = BeautifulSoup(
            session.get(course_link, timeout=3).content, "lxml")
        course_name = course_page_soup.select_one(".page-context-header").text
        posts = course_page_soup.select("li[id^=module]")
        current_post_ids = {post.get("id") for post in posts}

        # Create course_file for this specific course if it does not exist
        course_filepath = f"./Pickles/{course_name}"
        if not file_exists(course_filepath) or not is_pickle_file(
                course_filepath):
            create_course_file(course_name)

        email_content = EmailContent(course_link, course_name, "")
        with open(course_filepath, "rb") as file:
            # Find the differences between the current course post state and the previous one
            previous_post_ids: set = pickle.load(file)
            added_post_ids = current_post_ids.difference(previous_post_ids)
            deleted_post_ids = previous_post_ids.difference(current_post_ids)

            num_additions = len(added_post_ids)
            num_deletions = len(deleted_post_ids)
            should_send_email = num_additions > 0 or num_deletions > 0

            # Send an email if there are either post additions or post deletions
            if should_send_email:
                # Build the email body
                if num_additions > 0:
                    email_content.content_body += "<h2>Added:</h2>\n"
                    email_content.content_body += "<hr>".join(
                        get_post_contents(course_page_soup, added_post_ids))
                if num_deletions > 0:
                    email_content.content_body += "<h2>Deleted:</h2>\n"
                    email_content.content_body += "<hr>".join(
                        get_post_contents(course_page_soup, deleted_post_ids))

                email_subject = f"[{course_name}] +{num_additions} -{num_deletions}"
                # Send the email
                Email(email_subject,
                      email_content).send(get_env_email_credentials(),
                                          get_env_email_recipients())
        # Update the current state in the course_file
        dump_post_ids(course_filepath, current_post_ids)

    scheduler.enter(get_scheduler_delay(), 1, fetch_and_notify,
                    (session, scheduler))

    log_with_time(f"Done fetching and rescheduling.\n\n")