Пример #1
0
def notify():

    #------------------------
    # Setup watchdog patterns
    #------------------------
    #patterns = "*"
    patterns = ["*full.jpg"]

    ignore_patterns = ""
    ignore_directories = False
    case_sensitive = False 
    #path = "c://self//UniWatch2//static//images"
    path = watchConfig.config['fileWatch']['pathToImagesUnifi']
    go_recursively = True 
    #------------------------
    # Setup watchdog handlers
    #------------------------

    event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)

    event_handler.on_created = on_file_created
    #event_handler.on_modified = on_file_created

    #observer = Observer()
    observer = PollingObserver()
    observer.schedule(event_handler, path, recursive=go_recursively)
    #observer.schedule(event_handler, path, recursive=False)
    observer.start()
 def __init__(self, sql, args, q, staging_dir):
   PatternMatchingEventHandler.__init__(self)
   self.sql         = sql
   self.subs_table  = args['subs_table']
   self.team_table  = args['team_table']
   self.queue       = q
   self.staging_dir = staging_dir
Пример #3
0
    def start(self, root):
        self.root = root
        patterns = ["*.edd"]
        ignore_patterns = ""
        ignore_directories = False
        case_sensitive = True
        my_event_handler = PatternMatchingEventHandler(patterns,
                                                       ignore_patterns,
                                                       ignore_directories,
                                                       case_sensitive)
        my_event_handler.on_created = self.on_created
        my_event_handler.on_modified = self.on_modified
        go_recursively = False

        path = config.app_dir

        # edmc may be slow starting, stored/current may already  be there, process

        stored = join(path, "stored.edd")
        if os.path.exists(stored):
            print("Stored exists, processing")
            self.readfile(stored)

        current = join(path, "current.edd")
        if os.path.exists(current):
            print("Current exists, processing")
            self.readfile(current)

        my_observer = Observer()
        my_observer.schedule(my_event_handler, path, recursive=go_recursively)
        my_observer.start()
Пример #4
0
    def __init__(self, container, host_dir, container_dir):
        """
        Initialize a new instance of ContainerNotifier

        Args:
            container: Container
            host_dir (str): Host directory
            container_dir (str): Container directory
        """
        self.container = container
        self.host_dir = host_dir
        self.container_dir = container_dir

        event_handler = PatternMatchingEventHandler(ignore_directories=True)
        handler = self.__change_handler
        event_handler.on_created = handler
        event_handler.on_moved = handler
        event_handler.on_modified = handler

        self.ignore_file_pattern = '(\.idea|\.git|node_modules|___jb_old___|___jb_tmp___)'
        if self.ignore_file_pattern:
            self.ignore_file_pattern_compiled = re.compile(
                self.ignore_file_pattern)
        else:
            self.ignore_file_pattern_compiled = None
        self.observer = Observer()
        self.observer.schedule(event_handler, host_dir, recursive=True)
        self.observer.start()
Пример #5
0
 def test_ignore_directories(self):
   handler1 = PatternMatchingEventHandler(g_allowed_patterns,
                                          g_ignore_patterns, True)
   handler2 = PatternMatchingEventHandler(g_allowed_patterns,
                                          g_ignore_patterns, False)
   self.assertTrue(handler1.ignore_directories)
   self.assertFalse(handler2.ignore_directories)
 def __init__(self, watch_file, controller_function, args=[], loop=None):
     PatternMatchingEventHandler.__init__(self, patterns=[watch_file])
     self.controller_function = controller_function
     self.args = args
     self.loop = asyncio.SelectorEventLoop() if loop is None else loop
     self.async_task = None
     self.watch_file = watch_file
Пример #7
0
	def __init__(self, gcodeManager, printer):
		PatternMatchingEventHandler.__init__(self)

		self._logger = logging.getLogger(__name__)

		self._gcodeManager = gcodeManager
		self._printer = printer
 def __init__(self, watch_file, controller_function, args=[], loop=None):
     PatternMatchingEventHandler.__init__(self, patterns=[watch_file])
     self.controller_function = controller_function
     self.args = args
     self.loop = asyncio.SelectorEventLoop() if loop is None else loop
     self.async_task = None
     self.watch_file = watch_file
Пример #9
0
 def start_detect(self):
     patterns = "*"
     ignore_patterns = ""
     ignore_directories = False
     case_sensitive = True
     my_event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)
     my_event_handler.on_created = self.on_created
     self.detect_changes(my_event_handler)
Пример #10
0
 def __init__(self, path='.', patterns='*', logfunc=print):
     '''
     Instantiate the watchdog object
     '''
     PatternMatchingEventHandler.__init__(self, patterns)
     Observer.__init__(self)
     self.schedule(self, path=path, recursive=False)
     self.log = logfunc
Пример #11
0
 def __init__(self, bot, config, *args, **kwargs):
     """
     :type bot: cloudbot.bot.CloudBot
     :type config: Config
     """
     self.bot = bot
     self.config = config
     PatternMatchingEventHandler.__init__(self, *args, **kwargs)
Пример #12
0
 def __init__(self, bot, config, *args, **kwargs):
     """
     :type bot: ralybot.bot.Ralybot
     :type config: Config
     """
     self.bot = bot
     self.config = config
     PatternMatchingEventHandler.__init__(self, *args, **kwargs)
Пример #13
0
 def __init__(self,
              pattern,
              work,
              delete_after_work=config.delete_after_work):
     PatternMatchingEventHandler.__init__(self,
                                          patterns=[pattern],
                                          ignore_directories=True)
     self.work = work
     self.delete_after_work = delete_after_work
Пример #14
0
def observe_trig_file():
    print_limit(" - Enabling Trigger Events Config File Observation -", 2)
    path = homedir + "/Pigrow/config/"
    trig_events_handler = PatternMatchingEventHandler("*.txt", "", True, False)
    trig_events_handler.on_created = trig_change
    trig_events_handler.on_modified = trig_change
    trig_events_ob = Observer()
    trig_events_ob.schedule(trig_events_handler, path, recursive=True)
    trig_events_ob.start()
Пример #15
0
 def __init__(self, notifier, config_dir, service_dir, config_filename):
     self.notifier = notifier
     self.config_dir = config_dir
     self.service_dir = service_dir
     self.config_filename = config_filename
     PatternMatchingEventHandler.__init__(
         self,
         patterns=["*{}*".format(self.config_filename)],
         ignore_directories=True)
Пример #16
0
def test_handler():
    handler1 = PatternMatchingEventHandler(g_allowed_patterns,
                                           g_ignore_patterns, True)
    handler2 = PatternMatchingEventHandler(g_allowed_patterns,
                                           g_ignore_patterns, False)
    assert handler1.patterns == g_allowed_patterns
    assert handler1.ignore_patterns == g_ignore_patterns
    assert handler1.ignore_directories
    assert not handler2.ignore_directories
Пример #17
0
 def __init__(self, parent, watch_dir, emitter=None, *args, **kwargs):
     super(Event_Handler, self).__init__(*args, **kwargs)
     PatternMatchingEventHandler.__init__(self, *args, **kwargs)
     self._emitter = emitter
     self.parent = parent
     self.watch_dir = watch_dir
     self.last_item = None
     self._emitEvents = ['created', 'renamed', 'modified', 'moved']
     self._removeEvents = ['deleted', 'moved']
Пример #18
0
def Watch_func():

    import time
    from watchdog.observers import Observer
    from watchdog.events import PatternMatchingEventHandler
    import subprocess
    import ctypes  # An included library with Python install.   


    stim = [5, 6, 7, 8]

    patterns = "*"
    ignore_patterns = ""
    ignore_directories = False
    case_sensitive = True
    my_event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)

    def on_modified(event):
        print(f"{event.src_path} has been modified")

        filename = 'C:/Users/Adam/Documents/MENG_yr3/IRP_papers/pytest.csv'
        f = open(filename)

        excel_val = (f.read(1))
        if excel_val.isdigit():
            reg_val = int(excel_val)
            print(type(reg_val), reg_val)

            if reg_val == stim[0]:
                ctypes.windll.user32.MessageBoxW(0, "Input frequency is 5", "title test", 1)
            elif reg_val == stim[1]:
                ctypes.windll.user32.MessageBoxW(0, "input frequency is 6", "title test", 1)
            elif  reg_val == stim[2]:
                ctypes.windll.user32.MessageBoxW(0, "input frequency is 7", "title test", 1)
            elif reg_val == stim[3]:
                ctypes.windll.user32.MessageBoxW(0, "Input frequency is 8", "title test", 1)
    
    


    my_event_handler.on_modified = on_modified


    path = "/Users/Adam/Documents/MENG_yr3/IRP_papers"

    go_recursively = True
    my_observer = Observer()
    my_observer.schedule(my_event_handler, path, recursive=go_recursively)

    my_observer.start()
    try:
        while True:
            time.sleep(1)

    except KeyboardInterrupt:
        my_observer.stop()
        my_observer.join()
Пример #19
0
    def __init__(self, pat, src, dest, rls, ig):
        PatternMatchingEventHandler.__init__(self)
        patterns = pat
        self.source = src
        self.destination = dest
        self.rules = rls
        self.ignore = ig

        print "Watching for:", patterns, "\nOutput to:", self.destination, "\nIgnoring:", self.ignore
Пример #20
0
 def test___init__(self):
     handler1 = PatternMatchingEventHandler(g_allowed_patterns,
                                            g_ignore_patterns, True)
     handler2 = PatternMatchingEventHandler(g_allowed_patterns,
                                            g_ignore_patterns, False)
     assert_equal(handler1.patterns, g_allowed_patterns)
     assert_equal(handler1.ignore_patterns, g_ignore_patterns)
     assert_true(handler1.ignore_directories)
     assert_false(handler2.ignore_directories)
Пример #21
0
def start_params_monitor():
    load_values_from_file()
    event_handler = PatternMatchingEventHandler(patterns=["*.properties", "*.profile"],
                                                ignore_patterns=[],
                                                ignore_directories=True)
    event_handler.on_any_event = on_any_event
    observer = Observer()
    observer.schedule(event_handler, '.', recursive=False)
    observer.start()
Пример #22
0
 def __init__(self, *args):
     PatternMatchingEventHandler.__init__(self, *args)
     self._vertical_position = 0
     self._horizontal_position = 0
     self._faceTracker = FaceTracker()
     #self._curvefilter = filters.BGRPortraCurveFilter()
     self._center = (320, 240)
     self._threshold = 60
     self._ws = create_connection("ws://localhost/robot")
 def __init__(self,
              path='.',
              patterns=['*.txt', '*.pdf'],
              logfunc=print):  #patterns='*'
     PatternMatchingEventHandler.__init__(self, patterns)
     Observer.__init__(self)
     self.schedule(self, path=path, recursive=False
                   )  #recursive = false means dont go through subfolders
     self.log = logfunc
     self.my_ftp = '.'
Пример #24
0
    def __init__(self, parent_frame, status_frame, src_loc, dest_loc):
        PatternMatchingEventHandler.__init__(self)
        self.parent_frame = parent_frame
        self.statusFrame = status_frame
        self.dest_loc = dest_loc
        patterns = ["*"]
        self.backup_in_progress = False

        # First sync files that may have been modified while we were not running
        self.trigger_event(src_loc)
Пример #25
0
    def __init__(self, inputf, outputf):
        PatternMatchingEventHandler.__init__(self)

        self.output = outputf
        self.finished = os.path.join(inputf, 'finished')

        if not os.path.exists(self.output):
            os.makedirs(self.output)
        if not os.path.exists(self.finished):
            os.makedirs(self.finished)
Пример #26
0
    def run(self):
        my_event_handler = PatternMatchingEventHandler(self.patterns,
                                                       self.ignore_patterns,
                                                       self.ignore_directories,
                                                       self.case_sensitive)

        my_event_handler.on_created = self.on_created
        my_observer = Observer()
        my_observer.schedule(my_event_handler, self.rootPath, recursive=True)
        my_observer.start()
Пример #27
0
    def __init__(self, inputf, outputf):
        PatternMatchingEventHandler.__init__(self)

        self.output = outputf
        self.finished = os.path.join(inputf, 'finished')

        if not os.path.exists(self.output):
            os.makedirs(self.output)
        if not os.path.exists(self.finished):
            os.makedirs(self.finished)
Пример #28
0
def observe_config_file():
    print(" - Enabling Config File Observation")
    path = homedir + "/Pigrow/config/"
    print(path)
    conf_events_handler = PatternMatchingEventHandler("*.txt", "", True, False)
    conf_events_handler.on_created = config_change
    conf_events_handler.on_modified = config_change
    conf_events_ob = Observer()
    conf_events_ob.schedule(conf_events_handler, path, recursive=True)
    conf_events_ob.start()
Пример #29
0
 def __init__(self, filename, core, key):
     PatternMatchingEventHandler.__init__(self,
                                          patterns=["*" + filename],
                                          ignore_patterns=None,
                                          ignore_directories=True,
                                          case_sensitive=False)
     self.core = core
     self.key = key
     self.observer = None
     self.value = None
Пример #30
0
def launch(roots, watch, debounce):
    debounce = datetime.timedelta(milliseconds=debounce)

    collections = collect_mappings(map(find_collections, roots))
    log.msg("collections found", collections=collections)

    def install_all():
        log.msg("init", dir_count=len(collections))
        for c in collections.items():
            install(*c)

    if watch:

        to_process = {}

        def handle_change(event):
            event_path = event.src_path
            path = next((path for path in collections.keys()
                         if event_path.startswith(path)))

            log.msg("change event",
                    trigger=event.src_path,
                    collection_path=path)
            to_process[path] = datetime.datetime.now()

        handler = PatternMatchingEventHandler(patterns="*",
                                              ignore_patterns="",
                                              ignore_directories=False,
                                              case_sensitive=True)
        handler.on_any_event = handle_change

        my_observer = Observer()
        for d in collections.keys():
            my_observer.schedule(handler, path=d, recursive=True)

        my_observer.start()
        log.msg("observation", op="start", dir_count=len(collections))
        try:
            while True:
                time.sleep(1)
                now = datetime.datetime.now()
                to_remove = []
                for k, v in to_process.copy().items():
                    if now > v + debounce:
                        install(k, collections[k])
                        to_remove.append(k)
                for k in to_remove:
                    del to_process[k]

        except KeyboardInterrupt:
            log.msg("observation", op="stop")
            my_observer.stop()
            my_observer.join()
    else:
        install_all()
Пример #31
0
def work():
    # event_handler = EventHandler()
    # main_start = True
    patterns = "*"
    ignore_patterns = ""
    ignore_directories = False
    case_sensitive = True
    event_handler = PatternMatchingEventHandler(patterns, ignore_patterns,
                                                ignore_directories,
                                                case_sensitive)

    event_handler.on_created = event.on_created
    # event_handler.on_deleted = event.on_deleted
    # event_handler.on_modified = event.on_modified
    event_handler.on_moved = event.on_moved
    observer = Observer()
    observer.schedule(event_handler, config._path, recursive=True)
    observer.start()

    # print("path",path)
    # for root, dirs, files in os.walk(path):
    copypaths = []
    for dir in os.listdir(config._path):
        # print("dir", dir)
        # abspath = os.path.abspath(dir)
        # print("abspath", abspath)
        subdir = config._path + "/" + dir
        subfiles = os.listdir(config._path + "/" + dir)
        if len(subfiles) > 0:
            copypaths.append(subdir)

    # print(copypaths)
    if len(copypaths) > 0:
        for copypath in copypaths:
            # print("copy:", copypath)
            # shutil.copytree(copypath, f"{copypath}-Copy")
            shutil.move(copypath, f"{copypath}-Copy")
        # if os.path.isfile(path):
        #     copypath.append(path)
# os.path.isfile(path)
# print(os.path.isfile(path + '\\' + dir))

# shutil.copytree(dir, f"{dir}-Copy")

#         for file in files:
#             # print(file)
#             Path(os.path.join(root, file)).touch()
# main_start = False

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
    def __init__(self, directories, **kwargs):
        FileWatcher.__init__(self, directories, **kwargs)

        watched_extensions = get_watched_extensions()

        # pattern matching files with extension
        patterns = ["*{}".format(ext) for ext in watched_extensions]
        logging.info("Stating fs watching on {} with pattern:{}".format(
            self.module_dir, patterns))

        PatternMatchingEventHandler.__init__(self, patterns=patterns)
Пример #33
0
def statCheckSetup():
    event_handler = PatternMatchingEventHandler("*", "", True, True)

    event_handler.on_created = importStat
    event_handler.on_modified = importStat

    path = f"{MINECRAFT_DIRECTORY}/world/stats"
    observer = Observer()
    observer.schedule(event_handler, path)

    observer.start()
Пример #34
0
 def __init__(
     self,
     path=PATH,
     patterns="*",
     ignore_patterns=[".DS_Store"],
     logfunc=logging.info,
 ):
     PatternMatchingEventHandler.__init__(self, patterns)
     Observer.__init__(self)
     self.schedule(self, path=path, recursive=True)
     self.log = logfunc
Пример #35
0
 def __init__(self, logger_fname, callback_func):
     '''
     :param logger_fname: name of the file to watch  
     :param callback_func: function to call when the file is moved. The function should 
             accept the moved file path as the first parameter
     '''
     self.logger_fname = logger_fname
     self.callback_func = callback_func
     PatternMatchingEventHandler.__init__(self,
                                          "*" + logger_fname,
                                          ignore_directories=True)
Пример #36
0
def run(application_path: 'the path to the application to run',
        reloader: 'reload the application on changes' = False,
        workers: 'the number of asynchronous tasks to run' = 1,
        debug: 'enable debug mode' = False):
    """Import and run an application."""
    import_path, app = _import_application(application_path)

    if reloader:
        # If the reloader is requested, create threads for running the
        # application and watching the file system for changes
        print('Running {!r} with reloader...'.format(app))

        # Find the root of the application and watch for changes
        watchdir = os.path.abspath(import_module(import_path).__file__)
        for _ in import_path.split('.'):
            watchdir = os.path.dirname(watchdir)

        # Create observer and runner threads
        observer = Observer()
        loop = asyncio.new_event_loop()
        runner = Thread(
            target=app.run_forever,
            kwargs={'num_workers': workers, 'loop': loop},
        )

        # This function is called by watchdog event handler when changes
        # are detected by the observers
        def restart_process(event):
            """Restart the process in-place."""
            os.execv(sys.executable, [sys.executable] + sys.argv[:])

        # Create the handler and watch the files
        handler = PatternMatchingEventHandler(
            patterns=['*.py', '*.ini'],
            ignore_directories=True,
        )
        handler.on_any_event = restart_process
        observer.schedule(handler, watchdir, recursive=True)

        # Start running everything
        runner.start()
        observer.start()

    else:
        # If the reloader is not needed, avoid the overhead
        print('Running {!r} forever...'.format(app))
        app.run_forever(num_workers=workers)
Пример #37
0
    def __init__(self, exit, magic_script_pattern, loop=None, **kwargs):
        self._exit = exit

        script_location = os.path.join(input_directory, magic_script_pattern)

        patterns = kwargs['patterns'] if 'patterns' in kwargs else []
        patterns.append(script_location)
        kwargs['patterns'] = patterns

        logging.info('Patterns: %s' % str(kwargs['patterns']))

        AIOEventHandler.__init__(self, loop)
        PatternMatchingEventHandler.__init__(self, **kwargs)

        if os.path.exists(script_location):
            self._loop.call_soon_threadsafe(
                asyncio.async,
                self.handle_exists(script_location, os.path.isdir(script_location))
            )
Пример #38
0
    def server(self, args):
        server = Process(target=self._server)
        server.start()

        event_handler = PatternMatchingEventHandler(ignore_patterns=self.WATCH_EXCLUDE)
        event_handler.on_modified = lambda event : self._build()
        observer = Observer()
        observer.schedule(event_handler, self.BASE_DIR, recursive=True)
        observer.start()

        try:
            while True:
                time.sleep(1)
        except (KeyboardInterrupt, SystemExit):
            server.terminate()
            observer.stop()

        observer.join()

        self.logger.info("Clossing")
    def __init__(self, exit, target, interpreter, archive, passthrough, rmtree, loop=None, **kwargs):
        self._exit = exit

        self._archive = archive
        self._target = target
        self._passthrough = passthrough
        self._rmtree = rmtree
        self._interpreter = interpreter

        patterns = kwargs["patterns"] if "patterns" in kwargs else []
        patterns.append("input")
        kwargs["patterns"] = patterns

        logging.info("Patterns: %s" % str(kwargs["patterns"]))

        AIOEventHandler.__init__(self, loop)
        PatternMatchingEventHandler.__init__(self, **kwargs)

        if os.path.exists(input_directory):
            asyncio.async(self.execute(input_directory))
Пример #40
0
    def __init__(self, file_to_watch, dest_path):
        PatternMatchingEventHandler.__init__(self)

        self.file_to_watch = file_to_watch
        self.dest_path = dest_path

        if os.path.isdir(self.file_to_watch):
            self.file_to_watch = None

        self.default_template_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
            "template.html")

        self.ssh_client = create_ssh_client(*get_configs())
        self.scp = SCPClient(self.ssh_client.get_transport())

        if self.file_to_watch != None:
            self.fire(self.file_to_watch)
        else:
            mds = [filename for filename in os.listdir(".") if filename.endswith(".md")]
            for md in mds:
                self.fire(md)

        print "Initialization completed. Listening for changes..."
Пример #41
0
 def __init__(self):
     PatternMatchingEventHandler.__init__(self,
         patterns=['*.ui'],
         ignore_directories=True, 
         case_sensitive=False)
     self.command = 'pyside-uic'
Пример #42
0
 def on_moved(self, event):
     PatternMatchingEventHandler.on_moved(self, event)
     logging.info("Moved file from %s to %s", event.src_path,
              event.dest_path)
Пример #43
0
def run(application_path: 'the path to the application to run',
        reloader: 'reload the application on changes' = False,
        workers: 'the number of asynchronous tasks to run' = 1,
        debug: 'enable debug mode' = False,
        **kwargs):
    """Import and run an application."""
    if kwargs['quiet']:
        # If quiet mode has been enabled, set the number of verbose
        # flags to -1 so that the level above warning will be used.
        verbosity = -1
    else:
        # argparse gives None not 0.
        verbosity = kwargs['verbose'] or 0

    # Set the log level based on the number of verbose flags. Do this
    # before the app is imported so any log calls made will respect the
    # specified level.
    log_level = logging.WARNING - (verbosity * 10)
    logging.basicConfig(level=log_level)

    import_path, app = _import_application(application_path)

    # Now that we have an application, set it's log level, too.
    app.logger.setLevel(log_level)

    if reloader or debug:
        # If the reloader is requested (or debug is enabled), create
        # threads for running the application and watching the file
        # system for changes.
        app.logger.info('Running {!r} with reloader...'.format(app))

        # Find the root of the application and watch for changes
        watchdir = os.path.abspath(import_module(import_path).__file__)
        for _ in import_path.split('.'):
            watchdir = os.path.dirname(watchdir)

        # Create observer and runner threads
        observer = Observer()
        loop = _new_event_loop()
        runner = Thread(
            target=app.run_forever,
            kwargs={'num_workers': workers, 'loop': loop, 'debug': debug},
        )

        # This function is called by watchdog event handler when changes
        # are detected by the observers
        def restart_process(event):
            """Restart the process in-place."""
            os.execv(sys.executable, [sys.executable] + sys.argv[:])

        # Create the handler and watch the files
        handler = PatternMatchingEventHandler(
            patterns=['*.py', '*.ini'],
            ignore_directories=True,
        )
        handler.on_any_event = restart_process
        observer.schedule(handler, watchdir, recursive=True)

        # Start running everything
        runner.start()
        observer.start()

    else:
        # If the reloader is not needed, avoid the overhead
        app.logger.info('Running {!r} forever...'.format(app))
        app.run_forever(num_workers=workers, debug=debug)
Пример #44
0
def main():
    global signal_event
    global ra_str
    global dec_str

    parser = argparse.ArgumentParser(description='Watches a folder for .jpg files and runs them through the astrometry.net solver.')

    parser.add_argument('--watch-folder', required=True, help="folder to watch for new jpg files (will be created if it does not exist)")
    parser.add_argument('--output-folder', required=True, help="folder to output solved information to (will be created if it does not exist)")

    args = parser.parse_args()

    watch_folder = args.watch_folder
    output_folder = args.output_folder

    mkdir_p(watch_folder)
    mkdir_p(output_folder)

    # AF_INET means IPv4.
    # SOCK_STREAM means a TCP connection.
    # SOCK_DGRAM would mean an UDP "connection".
    listening_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    listening_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # The parameter is (host, port).
    # The host, when empty or when 0.0.0.0, means to accept connections for
    # all IP addresses of current machine. Otherwise, the socket will bind
    # itself only to one IP.
    # The port must greater than 1023 if you plan running this script as a
    # normal user. Ports below 1024 require root privileges.
    listening_socket.bind( ("", 10001) )

    # The parameter defines how many new connections can wait in queue.
    # Note that this is NOT the number of open connections (which has no limit).
    # Read listen(2) man page for more information.
    listening_socket.listen(5)
    listening_socket.setblocking(0)
    listening_socket.settimeout(0.5)

    def on_created(event):
        global ra_str
        global dec_str
        logger.info('Found new file: {0}'.format(event.src_path))

        # Sometimes we get the notification before the file is done being written. Wait half a second before processing.
        e = Event()
        e.wait(0.5)
        e = None

        result = solve(event.src_path, output_folder)

        if result is not None:
            ra_str = result[0]
            dec_str = result[1]


    event_handler = PatternMatchingEventHandler(patterns=["*.jpg"])

    event_handler.on_created = on_created

    observer = Observer()
    observer.schedule(event_handler, watch_folder, recursive=True)
    observer.start()

    wait_time = 0.1

    while not signal_event.wait(wait_time):

        conn = None

        try:
            conn, addr = listening_socket.accept()
        except socket.timeout as ex:
            pass
        except socket.error as ex:
            if ex.errno == errno.EINTR:
                # CTRL-C was pressed. Ignore the error.
                pass
            else:
                logger.error(ex)
                raise

        if conn is not None:
            conn.setblocking(0)
            conn.settimeout(0.5)

            logger.info('Connected...')

            ra_str = None
            dec_str = None

            while not signal_event.wait(wait_time):

                if ra_str is not None and dec_str is not None:

                    ra_str = ra_str[0:ra_str.rfind('.')]
                    dec_str = dec_str[0:dec_str.rfind('.')]
                    dec_str = dec_str.replace('+', '')

                    ra = functions.hourStr_2_rad(ra_str)
                    dec = functions.degStr_2_rad(dec_str)

                    result = functions.rad_2_stellarium_protocol(ra, dec)

                    t = time.time() * 1000000

                    # 2 bytes integer - Length of message (24)
                    # 2 bytes integer - 0
                    # 8 bytes integer - microseconds since epoch
                    # 4 bytes unsigned integer - RA
                    # 4 bytes signed integer - DEC
                    # 4 bytes status - 0 == OK

                    packet = (24, 0, t, result[0], result[1], 0)

                    reply = struct.pack('<hhqIii', 24, 0, t, result[0], result[1], 0)
                    #print reply

                    for i in range(10):
                        conn.send(reply)

                    ra_str = None
                    dec_str = None

                data = None

                try:
                    # recv can throw socket.timeout
                    data = conn.recv(20)
                except socket.timeout as ex:
                    pass
                except socket.error as ex:
                    if ex.errno == errno.EINTR:
                        # CTRL-C was pressed. Ignore the error.
                        pass
                    else:
                        logger.error(ex)
                        raise

                if data is not None:
                    # 2 bytes integer - Length of message
                    # 2 bytes integer - 0
                    # 8 bytes integer - current time in microseconds since epoch
                    # 4 bytes unsigned integer - RA
                    # 4 bytes signed integer - DEC

                    data = struct.unpack("<hhqIi", data)

                    #print data
                    recieved_coords = functions.eCoords2str(data[3], data[4], data[2])

                    logger.info('Received slew command to (RA, DEC) = ({0}, {1})'.format(recieved_coords[0], recieved_coords[1]))

            logger.warning('Disconnected...')
Пример #45
0
 def __init__(self, *args, **kwargs):
     self.freezer = kwargs.pop('freezer')
     self.throttle_seconds = kwargs.pop('throttle_seconds')
     PatternMatchingEventHandler.__init__(self, *args, **kwargs)
     self.last_event_time = 0
Пример #46
0
 def __init__(self, script):
     PatternMatchingEventHandler.__init__(self)
     self.script = script
Пример #47
0
 def on_created(self, event):
     PatternMatchingEventHandler.on_created(self, event)
     logging.info("Created file: %s",  event.src_path)
     make_py(event.src_path)
 def __init__(self):
     PatternMatchingEventHandler.__init__(self)
     self.count = 0
     print("In constructor")
Пример #49
0
 def on_deleted(self, event):
     PatternMatchingEventHandler.on_deleted(self, event)
     logging.info("Deleted file: %s", event.src_path)
Пример #50
0
 def __init__(self):
     PatternMatchingEventHandler.__init__(self, ignore_patterns=['*\.git*'])
Пример #51
0
 def __init__(self, proxy_func):
     self._proxy_func = proxy_func
     PatternMatchingEventHandler.__init__(self)
Пример #52
0
 def on_modified(self, event):
     PatternMatchingEventHandler.on_modified(self, event)
     
     logging.info("Modified %s", event.src_path)
     make_py(event.src_path)
Пример #53
0
 def __init__(self, ignore_patterns):
     PatternMatchingEventHandler.__init__(self, ignore_patterns=ignore_patterns)
 def __init__(self, random_player):
     PatternMatchingEventHandler.__init__(self)
     self.random_player = random_player
Пример #55
0
 def dispatch(self, event):
     if event.src_path is None:
         event._src_path = "/dev/null"
     PatternMatchingEventHandler.dispatch(self, event)
Пример #56
0
	def __init__(self, gcode_manager):
		PatternMatchingEventHandler.__init__(self)
		self._gcode_manager = gcode_manager
Пример #57
0
	def __init__(self):
		PatternMatchingEventHandler.__init__(self)
Пример #58
0
 def __init__(self):
     PatternMatchingEventHandler.__init__(self, patterns=["*.py"])
Пример #59
0
 def __init__(self):
     PatternMatchingEventHandler.__init__(self, patterns=["*.txt"])
     self.file_processor = FileProcessor()
Пример #60
0
 def __init__(self, kwdb, path):
     PatternMatchingEventHandler.__init__(self)
     self.kwdb = kwdb
     self.path = path