示例#1
0
 def create_sync(self):
     """
     creates a sync object.
     """
     if self.certificate_file is None:
         self.sync = Sync(self.server_address, self.username, self.password)
     else:
         self.sync = Sync(self.server_address, self.username, self.password,
                          self.certificate_file.name)
示例#2
0
    def onLogin(self, host, username, passwd, ssl):
        """
        Slot. Triggers a log in request to the server.
        
        :param host: Indicates the hostname of the FTP server
        :param username: Username to log in into the FTP server
        :param passwd: Password to log in into the FTP server
        :param ssl: Indicates whether the FTP needs SSL support
        """

        self.sync = Sync(host, ssl)
        self.syncStarted.connect(self.sync.initQueue)
        self.sync.server.downloadProgress.connect(self.onDownloadProgress)
        self.sync.server.uploadProgress.connect(self.onUploadProgress)
        self.sync.server.fileEvent.connect(self.onFileEvent)
        self.sync.server.badFilenameFound.connect(self.badNameWarning)
        self.sync.server.loginCompleted.connect(self.onLoginCompleted)
        self.sync.server.fileEventCompleted.connect(self.onFileEventCompleted)
        self.sync.server.ioError.connect(self.onIOError)
        # Added by Si
        self.sync.server.textStatus.connect(self.setStatus)

        self.sync.statusChanged.connect(self.setStatus)
        self.loginRequested.connect(self.sync.server.onLogin)

        self.syncThread = QThread()
        self.sync.moveToThread(self.syncThread)
        self.syncThread.start()

        QApplication.instance().lastWindowClosed.connect(self.syncThread.quit)
        self.loginRequested.emit(username, passwd)
示例#3
0
 def __init__(self, config=None):
     if config is None:
         config = get_config_from_file("config.ini")
     self.config = config
     # Seed the trust stores
     Sync(self.config).seed()
     self.cert_processor = CertProcessor(config)
示例#4
0
	def run(self):
		sync = Sync(show_progress=self._isManual, run_silent=self._runSilent, library=self._library, api=globals.traktapi)
		sync.sync()
		
		if utilities.getSettingAsBool('tagging_enable') and utilities.getSettingAsBool('tagging_tag_after_sync'):
			q = queue.SqliteQueue()
			q.append({'action': 'updatetags'})
示例#5
0
def main():
    """Main
    """
    start = time()

    parser = ArgumentParser(description='Sync', prog='python __main__.py')
    add = parser.add_argument

    add('--clean', action='store_true', help='delete all .gz files')
    add('--console-debug', nargs='?', default='INFO', help='console debug level',
        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'])
    add('--download', action='store_true', help='download JSON files')
    add('--host', nargs='?', default='/', help='host, ex: /seriv/')
    add('--no-debug', nargs='?', default=0, const=1, type=int, help="remove debug code from the javascript")
    add('--no-process', nargs='?', default=0, const=1, type=int, help="don't process the images")
    add('--zip', action='store_true', help='create .gz files')

    args = parser.parse_args()
    args_dict = vars(args)

    if args.download:
        download_json()
    else:
        sync = Sync(**args_dict)
        sync.synchronise()

    end = time()
    print(f'\nELAPSED: {end-start:.3f} seconds')
示例#6
0
文件: asynk.py 项目: jdodds/ASynK
    def op_sync (self):
        conf  = self.get_config()
        pname = self._load_profile()

        sync = Sync(conf, pname, self.get_db(), dr=self.is_dry_run())
        if self.is_dry_run():
            sync.prep_lists(self.get_sync_dir())
        else:
            try:
                startt = conf.get_curr_time()
                result = sync.sync(self.get_sync_dir())
                if result:
                    conf.set_last_sync_start(pname, val=startt)
                    conf.set_last_sync_stop(pname)
                    logging.info('Updating item inventory...')
                    sync.save_item_lists()
                    logging.info('Updating item inventory...done')
                else:
                    logging.info('timestamps not reset for profile %s due to '
                                 'errors (previously identified).', pname)
            except Exception, e:
                logging.critical('Exception (%s) while syncing profile %s', 
                                 str(e), pname)
                logging.critical(traceback.format_exc())
                return False
示例#7
0
def _get_sync_object():
    """ get sync object """
    try:
        sync = Sync()
        sync.bucket = args.bucket
        return sync
    except NoCredentialsError as ex:
        log.debug('Error to connect to Amazon. Can not found the credentials.')
        log.debug(repr(ex))
        log.debug('Exit')
        exit(1)
示例#8
0
文件: watch.py 项目: moonbot/filesync
 def run(self):
     """
     Thread: Run
     """
     s = Sync(self.src, self.dst, **self.kwargs)
     s.diff()
     self.loadInitContents(s)
     s.progressfnc = self.progress
     while True:
         s.diff()
         s.difftrim(create=self.getInitContents())
         s.run()
         time.sleep(self.freq)
示例#9
0
def main():
    global sync
    print(sys.argv)
    url = "index.html"
    if len(sys.argv) > 1:
        url = sys.argv[1]
    print("main thread id:", threading.get_ident())

    data_dir = appdirs.user_data_dir(APPNAME)
    if not os.path.exists(data_dir):
        os.mkdir(data_dir)

    setting = read_setting_db()
    if not setting:
        setting = {
            "workspace": os.path.join(Path.home(), "gitCloud"),
            "interval": config.SYNC_INTERVAL
        }
    print("setting:", setting)
    excludesFile = os.path.join(appdirs.user_data_dir(APPNAME), ".gitignore")
    createExcludesFile(excludesFile)
    print("excludesFile:", excludesFile)

    workspace = setting["workspace"]
    if not os.path.exists(workspace):
        os.mkdir(workspace)

    if os.path.isabs(config.GIT):
        path = os.path.dirname(config.GIT)
        env_path = os.getenv("PATH")
        if env_path:
            env_path = env_path + ":" + path
        else:
            env_path = path
        set_env_path(env_path)

    api = Api(setting)
    repos = [repo.copy() for repo in api.repos]
    sync = Sync(repos, event_q, setting["interval"], excludesFile)

    window = webview.create_window('gitCloud',
                                   url,
                                   width=400,
                                   height=680,
                                   js_api=api)
    api.window = window

    api.start()
    sync.start(sync_q, workspace)

    webview.start(debug=config.DEBUG)
示例#10
0
    def syncElement(self,
                    path,
                    filename,
                    extension,
                    imdbid,
                    istvshow,
                    oldelement=None):
        printl(
            str(path) + " " + str(filename) + " " + str(extension) + " " +
            str(imdbid) + " " + str(istvshow), self)

        element = None

        if oldelement is None:
            element = MediaInfo(path, filename, extension)
            element.parse()
            element.ImdbId = imdbid
        else:
            element = oldelement  #.copy()

        if istvshow:
            element.setMediaType(MediaInfo.SERIE)
        else:
            element.setMediaType(MediaInfo.MOVIE)

        results = Sync().syncWithId(element)
        if results is not None:
            return results
        else:
            if istvshow is False:
                element.setMediaType(MediaInfo.SERIE)
            else:
                element.setMediaType(MediaInfo.MOVIE)

            results = Sync().syncWithId(element)
            if results is not None:
                return results
        return None
示例#11
0
    def updateAll(self,
                  notifyOutput=None,
                  notifyProgress=None,
                  notifyRange=None):
        episodes = self.getAll(self.TVSHOWSEPISODES)
        total = len(episodes)
        progress = 0

        if notifyRange is not None:
            notifyRange(total)

        if notifyProgress is not None:
            notifyProgress(0)

        for episode in episodes:
            if episode.Title is None or episode.Season is None or episode.Episode is None:
                continue
            tvshow = self.getMedia(episode.ParentId)
            if episode.Title == tvshow.Title:
                printl(
                    "Episode has same title as tvshow so probably update needed (%s %dx%d)"
                    % (episode.Title, episode.Season, episode.Episode), self,
                    "I")
                if notifyOutput is not None:
                    notifyOutput(
                        Utf8.utf8ToLatin(
                            "Updating %s %dx%d" %
                            (episode.Title, episode.Season, episode.Episode)))
                id = episode.Id
                seen = self.isMediaSeen(episode.Id)
                episode.setMediaType(episode.SERIE)
                newElement = Sync().syncWithId(episode)
                if newElement is not None:
                    if len(newElement) == 2:
                        episode = newElement[1]
                    else:
                        episode = newElement[0]

                    self.deleteMedia(id)
                    ret = self.insertMedia(episode)
                    if seen:
                        self.MarkAsSeen(ret["id"])
            progress = progress + 1
            printl(
                "Update progress %.2f (%d/%d)" %
                ((progress / total) * 100.0, progress, total), self, "I")
            if notifyProgress is not None:
                notifyProgress(progress)

        notifyProgress(total)
示例#12
0
    def op_sync(self):
        conf = self.get_config()
        pname = self._load_profile()

        startt_old = conf.get_last_sync_start(pname)
        stopt_old = conf.get_last_sync_stop(pname)

        if self.is_sync_all():
            # This is the case the user wants to force a sync ignoring the
            # earlier sync states. This is useful when ASynK code changes -
            # and let's say we add support for synching a enw field, or some
            # such.
            #
            # This works by briefly resetting the last sync start and stop
            # times to fool the system. If the user is doing a dry run, we
            # will restore his earlier times dutifully.
            if self.is_dry_run():
                logging.debug('Temporarily resetting last sync times...')
            conf.set_last_sync_start(pname, val="1980-01-01T00:00:00.00+00:00")
            conf.set_last_sync_stop(pname, val="1980-01-01T00:00:00.00+00:00")

        sync = Sync(conf, pname, self.get_db(), dr=self.is_dry_run())
        if self.is_dry_run():
            sync.prep_lists(self.get_sync_dir())
            # Since it is only a dry run, resetting to the timestamps to the
            # real older sync is sort of called for.
            conf.set_last_sync_start(pname, val=startt_old)
            conf.set_last_sync_stop(pname, val=stopt_old)
            logging.debug('Reset last sync timestamps to real values')
        else:
            try:
                startt = conf.get_curr_time()
                result = sync.sync(self.get_sync_dir())
                if result:
                    conf.set_last_sync_start(pname, val=startt)
                    conf.set_last_sync_stop(pname)
                    logging.info('Updating item inventory...')
                    sync.save_item_lists()
                    logging.info('Updating item inventory...done')
                else:
                    logging.info(
                        'timestamps not reset for profile %s due to '
                        'errors (previously identified).', pname)
            except Exception, e:
                logging.critical('Exception (%s) while syncing profile %s',
                                 str(e), pname)
                logging.critical(traceback.format_exc())
                return False
    def __init__(self, port, virtual_world, camera_mgr, sync_session):
        self.port = port
        self.virtual_world = virtual_world
        self.cam_mgr = camera_mgr

        self.task_mgr = virtual_world.taskMgr
        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cReader.setRawMode(True)
        self.cWriter = ConnectionWriter(self.cManager, 1)
        self.cWriter.setRawMode(True)
        self.tcpSocket = self.cManager.openTCPServerRendezvous(port, BACKLOG)
        self.cListener.addConnection(self.tcpSocket)

        self.activeSessions = {}
        self.connection_map = {}
        self.set_handlers()

        hostname = socket.gethostname()
        a, b, address_list = socket.gethostbyname_ex(hostname)
        self.ip = address_list[0]
        logging.info("Addresses %s" % address_list)
        logging.info("Server is running on ip: %s, port: %s" %
                     (self.ip, self.port))

        self.client_counter = 0
        self.read_buffer = ''
        self.read_state = 0
        self.read_body_length = 0
        self.packet = SocketPacket()

        controller = virtual_world.getController()
        self.sync = Sync(self.task_mgr, controller, camera_mgr, sync_session)
        self.vv_id = None
        if sync_session:
            logging.info("Waiting for Sync Client!")

        self.showing_info = False
        virtual_world.accept("i", self.toggleInfo)
        self.sync_session = sync_session
        self.createInfoLabel()

        atexit.register(self.exit)
示例#14
0
def main():
    patch_win_unicode()
    try:
        config = Config()
        config.read()

        src_storage = _get_storage(config, config.src)
        if config.list_only or config.list_folders:
            walker = _get_walker(config, src_storage, config.list_format)
            walker.walk()
        else:
            dest_storage = _get_storage(config, config.dest)
            sync = Sync(config, src_storage, dest_storage)
            sync.run()

    except urllib2.URLError as e:
        logger.error("Error connecting to server. {!r}".format(e))
        sys.exit(1)
    except KeyboardInterrupt:
        sys.exit()
示例#15
0
async def run():
    async def face_loop():
        nonlocal face, running
        while running:
            face.processEvents()
            await asyncio.sleep(0.01)
    event_loop = asyncio.get_event_loop()
    event_loop.create_task(face_loop())

    running = True
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())

    sync = Sync(prefix=Name("/git"), face=face, on_update=on_update)
    sync.run()

    while True:
        await sync.publish_data(branch="test_branch", timestamp=None)
        await asyncio.sleep(5)
示例#16
0
    def __init__(self):
        parser = ArgumentParser()
        parser.add_argument('-c')
        args = parser.parse_args()
        if not os.path.exists(args.c):
            raise Exception('Error while reading config')

        config = ConfigParser()
        config.read(args.c)
        fileConfig(args.c)
        self.Logger = getLogger(__name__)
        self.client = Sync(config)
        self.to_get_queue = gevent.queue.Queue(maxsize=500)
        self.to_put_queue = gevent.queue.Queue(maxsize=500)
        db_url = create_db_url(
            config.get('user', 'username'),
            config.get('user', 'password'),
            config.get('db', 'host'),
            config.get('db', 'port'),
        )
        self.get_db(db_url, config.get('db', 'name'))
示例#17
0
def prepare_sync(key: bytes, app_id: int, installation_id: int) -> Sync:
    gh = GitHub()
    gh.login_as_app_installation(key, app_id, installation_id)
    auth = "x-access-token:" + gh.session.auth.token

    repos = {}

    print(f"Checking GitHub repositories for installation {installation_id}")
    for r in _app_installation_repositories(gh):
        if not r.homepage:
            print(f"NOTE: Skipping repository {r.full_name} (no homepage)")
            continue

        assert r.name not in repos, 'Duplicate repository name: ' + r.name

        # FIXME: Should we always append .git?
        src = parse_url(r.homepage + ".git")
        dest = parse_url(r.clone_url)._replace(auth=auth)

        repos[r.name] = Repo(src, dest)

    return Sync(repos)
示例#18
0
    def start(self):
        """
        Starts an experiment.
        """
        print("Starting experiment...")

        self.sync = Sync(
            device=self.attr_device,
            counter_input=self.attr_counter_input,
            counter_output=self.attr_counter_output,
            counter_bits=self.attr_counter_bits,
            event_bits=self.attr_event_bits,
            output_path=self.attr_output_path,
            freq=self.attr_pulse_freq,
            verbose=True,
            force_sync_callback=False,
        )

        lines = eval(self.attr_line_labels)
        for index, line in enumerate(lines):
            self.sync.add_label(index, line)

        self.sync.start()
示例#19
0
文件: app.py 项目: nickila/auto-sync
from config import ConfigLoader
from sync import Sync
from util import read_file
from worker import Worker

# Load all properties from INI and point to the folder where resources are stored
props_file = "app.ini"
cl = ConfigLoader.load(props_file, 'sync_resource')

# Just for process output
with open("logging.yml") as log_cfg:
    logging.config.dictConfig(yaml.safe_load(log_cfg))

sync_options = cl.get_config('sync')
resources_config = cl.get_resource_config()
log_folder = sync_options.get("log_folder")
os.makedirs(log_folder, exist_ok=True)

# The "base" config into which sync config gets merged
template_config = resources_config.merge_with(sync_options.values)
template_config.set_value("log_folder", os.path.abspath(log_folder))

# Read in the set of example syncs
example_sync_data = read_file("../example_sync/example.yml")

# Execute (single thread for now)
for config in example_sync_data:
    sync = Sync(config)
    w = Worker(sync, template_config)
    w.run()
示例#20
0
 def run(self):
     sync = Sync(show_progress=self._isManual,
                 run_silent=self._runSilent,
                 library=self._library,
                 api=globals.traktapi)
     sync.sync()
示例#21
0
from sync import Sync
import logger

INVALID_FILENAME_CHARS = '\/:*?"<>|'
STRIPTAGS = re.compile(r'<[^>]+>')
STRIPHEAD = re.compile("<head>.*?</head>", re.DOTALL)
EMPTYP = re.compile('<p style=\"-qt-paragraph-type:empty;.*(?=<p>)', re.DOTALL)

NOTESPATH = os.path.expanduser('~/.ownnotes/')

COLOR_TITLE = '#441144'
COLOR_LINK = '#115511'
COLOR_SUBTITLE = '#663366'

settings = Settings()
sync = Sync()

if not os.path.exists(NOTESPATH):
    os.makedirs(NOTESPATH)


def _getValidFilename(filepath):
    dirname, filename = os.path.dirname(filepath), os.path.basename(filepath)
    return os.path.join(dirname, ''.join(car for car in filename
                        if car not in INVALID_FILENAME_CHARS))


def setColors(title_color, subtitle_color, link_color):
    global COLOR_TITLE
    global COLOR_LINK
    global COLOR_SUBTITLE
示例#22
0
def main():
    parser = argparse.ArgumentParser(
        description='Sync current folder to your flickr account.')

    parser.add_argument('--monitor',
                        action='store_true',
                        help='Start monitoring daemon.')
    parser.add_argument(
        '--starts-with',
        type=str,
        help='Only sync those paths that start with this text, e.g. "2015/06."'
    )
    parser.add_argument(
        '--download',
        type=str,
        help='Download photos from flickr. Specify a path or use "." for all.')
    parser.add_argument('--dry-run',
                        action='store_true',
                        help='Do not download or upload anything.')
    parser.add_argument('--ignore-videos',
                        action='store_true',
                        help='Ignore video files.')
    parser.add_argument('--ignore-images',
                        action='store_true',
                        help='Ignore image files.')
    parser.add_argument(
        '--ignore-ext',
        type=str,
        help=
        'Comma separated list of filename extensions to ignore, e.g. "jpg,png".'
    )
    parser.add_argument('--fix-missing-description',
                        action='store_true',
                        help='Replace missing set description with set title.')
    parser.add_argument('--version',
                        action='store_true',
                        help='Output current version: ' + version)
    parser.add_argument('--sync-path',
                        type=str,
                        default=os.getcwd(),
                        help='Specify sync path (default: current dir).')
    parser.add_argument(
        '--sync-from',
        type=str,
        help=
        'Only one supported value: "all". Upload anything not on flickr. Download anything not on the local filesystem.'
    )
    parser.add_argument(
        '--custom-set',
        type=str,
        help='Customize set name from path with regex, e.g. "(.*)/(.*)".')
    parser.add_argument(
        '--custom-set-builder',
        type=str,
        help=
        'Build custom set title, e.g. "{0} {1}" joins first two groups (default behavior merges groups using a hyphen).'
    )
    parser.add_argument(
        '--update-custom-set',
        action='store_true',
        help=
        'Updates set title from custom-set (and custom-set-builder, if given).'
    )
    parser.add_argument(
        '--custom-set-debug',
        action='store_true',
        help=
        'When testing custom sets: ask for confirmation before creating an album.'
    )
    parser.add_argument('--username',
                        type=str,
                        help='Token username argument for API.')
    parser.add_argument('--keyword',
                        action='append',
                        type=str,
                        help='Only upload files matching this keyword.')

    args = parser.parse_args()

    if args.version:
        logger.info(version)
        exit()

    # Windows OS
    args.is_windows = os.name == 'nt'
    args.sync_path = args.sync_path.rstrip(os.sep) + os.sep
    if not os.path.exists(args.sync_path):
        logger.error('Sync path does not exist.')
        exit(0)

    local = Local(args)
    remote = Remote(args)
    sync = Sync(args, local, remote)
    sync.start_sync()
示例#23
0
    def __init__(self, options):
        super(DriverWindow, self).__init__()
        #uic.loadUi('ui/driverGUI.ui', self)
        self.options = options
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.tabWidget.setCurrentIndex(0)
        self.resetInfo(initial=True)
        self.ui.labelTest = {
            "MS5611": self.ui.label_baroTest,
            "MPU6050": self.ui.label_MPUTest,
            "HMC5883L": self.ui.label_magTest
        }

        self.state = STATE.DISCONNECTED

        # ROS
        self.d = Dialog(options)
        self.ros = ROSNode(options, self)

        # FLIE
        self.flie = FlieControl(self)
        self.ui.checkBox_pktHZ.toggled.connect(
            lambda on: self.flie.setPacketUpdateSpeed(self.ui.spinBox_pktHZ.
                                                      value() if on else 0))
        self.ui.spinBox_pktHZ.valueChanged.connect(self.flie.inKBPS.setHZ)
        self.ui.spinBox_pktHZ.valueChanged.connect(self.flie.outKBPS.setHZ)
        self.ui.spinBox_pktHZ.valueChanged.emit(
            self.ui.spinBox_pktHZ.value())  # force update
        self.ui.checkBox_kill.toggled.connect(self.flie.setKillswitch)
        self.flie.setKillswitch(self.ui.checkBox_kill.isChecked())
        self.ui.checkBox_xmode.toggled.connect(
            self.flie.crazyflie.commander.set_client_xmode)
        self.flie.crazyflie.commander.set_client_xmode(
            self.ui.checkBox_xmode.isChecked())

        # Set up ParamManager
        self.paramManager = ParamManager(self.flie.crazyflie, self)
        self.ui.tab_param.layout().addWidget(self.paramManager)

        # Set up LogManager
        self.logManager = LogManager(self.flie.crazyflie, self)
        self.ui.tab_log.layout().addWidget(self.logManager)
        self.ui.checkBox_logHZ.toggled.connect(self.logManager.setEstimateHzOn)
        self.ui.spinBox_logHZ.valueChanged.connect(
            self.logManager.setFreqMonitorFreq)
        self.logManager.sig_rosData.connect(self.ros.receiveCrazyflieLog)

        self.autoRetryTimer = QTimer()
        self.autoRetryTimer.setInterval(1500)
        self.autoRetryTimer.timeout.connect(lambda: self.connectPressed(
            self.ui.comboBox_connect.currentText(), auto=True))
        self.autoRetryTimer.setSingleShot(True)

        # Set up TrackManager
        self.trackManager = TrackManager(self.ros.sub_tf, self.ros.pub_tf,
                                         self)
        self.ui.tab_tracking.layout().addWidget(self.trackManager)

        # AI
        self.ai = AttitudeIndicator(self.ui.tab_hud)
        self.logManager.sig_rpy.connect(self.ai.setRollPitchYaw)
        self.ui.tab_hud.layout().addWidget(self.ai)
        self.ui.checkBox_AI.stateChanged.connect(self.ai.setUpdatesEnabled)
        self.ui.spinBox_AIHZ.valueChanged.connect(self.ai.setUpdateSpeed)
        self.logManager.sig_hoverTarget.connect(self.ai.setHover)
        self.logManager.sig_baroASL.connect(self.ai.setBaro)
        self.logManager.sig_accZ.connect(self.ai.setAccZ)
        self.logManager.sig_motors.connect(self.ai.setMotors)
        self.logManager.sig_batteryUpdated.connect(self.ai.setBattery)
        self.logManager.sig_batteryState.connect(self.ai.setPower)
        self.logManager.sig_temp.connect(self.ai.setTemp)
        self.logManager.sig_cpuUpdated.connect(self.ai.setCPU)
        self.logManager.sig_pressure.connect(self.ai.setPressure)
        self.logManager.sig_aslLong.connect(self.ai.setAslLong)
        self.paramManager.sig_gyroCalib.connect(self.ai.setCalib)
        self.flie.inKBPS.sig_KBPS.connect(self.ai.setPktsIn)
        self.flie.outKBPS.sig_KBPS.connect(self.ai.setPktsOut)
        self.flie.sig_flieLink.connect(self.ai.setLinkQuality)
        self.flie.sig_stateUpdate.connect(self.ai.setFlieState)
        self.ui.checkBox_reconnect.stateChanged.connect(
            self.ai.setAutoReconnect)
        self.logManager.sig_hzMeasure.connect(self.ai.updateHz)
        self.logManager.sig_logStatus.connect(self.ai.updateHzTarget)

        # Yaw offset
        self.ui.doubleSpinBox_yaw.valueChanged.connect(
            lambda yaw: self.ui.horizontalSlider_yaw.setValue(yaw * 10))
        self.ui.horizontalSlider_yaw.valueChanged.connect(
            lambda yaw: self.ui.doubleSpinBox_yaw.setValue(yaw / 10))
        self.ui.doubleSpinBox_yaw.valueChanged.connect(
            self.logManager.setYawOffset)
        self.ui.checkBox_yaw.stateChanged.connect(
            lambda x: self.logManager.setYawOffset(self.ui.doubleSpinBox_yaw.
                                                   value() if x else 0))
        self.ui.checkBox_yaw.stateChanged.emit(
            self.ui.checkBox_yaw.checkState())  # force update
        self.ui.pushButton_north.clicked.connect(
            lambda: self.ui.doubleSpinBox_yaw.setValue(self.logManager.getYaw(
            )))

        # ASL offset
        self.ui.doubleSpinBox_ground.valueChanged.connect(
            self.logManager.setGroundLevel)
        self.ui.checkBox_ground.stateChanged.connect(
            lambda x: self.logManager.setGroundLevel(
                self.ui.doubleSpinBox_ground.value() if x else 0))
        self.ui.checkBox_ground.stateChanged.emit(
            self.ui.checkBox_ground.checkState())
        self.ui.pushButton_ground.clicked.connect(
            lambda: self.ui.doubleSpinBox_ground.setValue(self.logManager.
                                                          getASL()))
        self.ros.sig_baro.connect(self.logManager.setAslOffset)

        # init previous settings
        self.readSettings()

        # Sync
        self.sync = Sync(self.flie.crazyflie)
        self.sync.sig_delayUp.connect(
            lambda x: self.ui.label_up.setText(str(round(x, 2)) + "ms"))
        self.sync.sig_delayDown.connect(
            lambda x: self.ui.label_down.setText(str(round(x, 2)) + "ms"))

        self.ui.groupBox_sync.toggled.connect(self.sync.enable)
        self.ui.spinBox_syncHz.valueChanged.connect(self.sync.setSyncRate)
        self.ui.spinBox_syncHz.valueChanged.emit(
            self.ui.spinBox_syncHz.value())
        self.ui.groupBox_sync.toggled.emit(self.ui.groupBox_sync.isChecked())
        self.sync.sig_cpuTime.connect(
            lambda x: self.ui.label_cputime.setText("%08.03fs" % x))
        self.sync.sig_flieTime.connect(
            lambda x: self.ui.label_flietime.setText("%08.03fs" % x))
        self.sync.sig_diffTime.connect(
            lambda x: self.ui.label_difftime.setText("%08.03fs" % x))

        self.ui.checkBox_rosLog.stateChanged.connect(
            self.logManager.setPubToRos)
        self.ui.groupBox_ros.clicked.connect(
            lambda x: self.logManager.setPubToRos(
                min(self.ui.groupBox_ros.isChecked(),
                    self.ui.checkBox_rosLog.checkState())))  #

        # Updating the GUI (if we didnt do this, every change would result in an update...)
        self.guiUpdateQueue = {}
        self.guiUpdateQueueSave = 0
        self.guiUpdateTimer = QTimer()
        self.guiUpdateTimer.setInterval(1000 / self.ui.spinBox_guiHZ.value())
        self.ui.spinBox_guiHZ.valueChanged.connect(
            lambda x: self.guiUpdateTimer.setInterval(1000 / x))
        self.guiUpdateTimer.timeout.connect(self.updateGui)
        self.guiUpdateTimer.start()

        # Defaults according to settings within GUI
        self.beepOn = self.ui.checkBox_beep.isChecked()
        self.killOn = self.ui.checkBox_kill.isChecked()
        self.autoReconnectOn = self.ui.checkBox_reconnect.isChecked()
        self.startupConnectOn = self.ui.checkBox_startupConnect.isChecked()
        self.ui.groupBox_input.toggled.connect(
            lambda x: self.ros.sig_joydata.connect(self.setInputJoy)
            if x else self.ros.sig_joydata.disconnect(self.setInputJoy))
        if self.ui.groupBox_input.isChecked():
            self.ros.sig_joydata.connect(self.setInputJoy)

        # Set up URI scanner
        self.scanner = ScannerThread(radio=options.radio)
        self.scanner.start()

        # Connections from GUI
        self.ui.pushButton_connect.clicked.connect(
            lambda: self.connectPressed(self.ui.comboBox_connect.currentText(),
                                        auto=False))  # Start button -> connect
        self.ui.comboBox_connect.currentIndexChanged.connect(self.uriSelected)

        self.ui.checkBox_beep.toggled.connect(self.setBeep)
        self.ui.checkBox_kill.toggled.connect(self.setKill)
        self.ui.checkBox_kill.toggled.connect(self.ai.setKillSwitch)
        self.ui.checkBox_kill.toggled.emit(
            self.ui.checkBox_kill.checkState())  # force update
        self.ui.checkBox_hover.toggled.connect(self.flie.setHoverDisabled)
        self.ui.checkBox_hover.toggled.emit(
            self.ui.checkBox_hover.checkState())  # force update

        self.ui.checkBox_reconnect.toggled.connect(self.setAutoReconnect)
        self.ui.checkBox_startupConnect.toggled.connect(self.setStartupConnect)
        self.ui.pushButton_genRosMsg.clicked.connect(self.genRosMsg)

        self.ui.pushButton_baro.clicked.connect(self.updateBaroTopics)

        self.ui.groupBox_baro.toggled.connect(
            lambda x: self.updateBaroTopics(not x))

        # Connections to GUI
        self.flie.sig_packetSpeed.connect(self.updatePacketRate)
        self.flie.sig_flieLink.connect(self.ui.progressbar_link.setValue)
        self.paramManager.sig_baroFound.connect(
            lambda found: self.ui.label_baroFound.setText("Yes"
                                                          if found else "No"))
        self.paramManager.sig_magFound.connect(
            lambda found: self.ui.label_magFound.setText("Yes"
                                                         if found else "No"))
        self.paramManager.sig_test.connect(lambda name, p: self.ui.labelTest[
            str(name)].setText("Pass" if p else "FAIL"))
        self.paramManager.sig_firmware.connect(
            lambda fw, mod: self.ui.label_fw.setText(fw))
        self.paramManager.sig_firmware.connect(
            lambda fw, mod: self.ui.label_fwMod.setText(mod))
        self.logManager.sig_batteryUpdated.connect(lambda v: self.setToUpdate(
            "vbat", self.ui.progressbar_bat.setValue, v))
        self.logManager.sig_cpuUpdated.connect(lambda v: self.setToUpdate(
            "cpu", self.ui.progressbar_cpu.setValue, v))
        self.flie.inKBPS.sig_KBPS.connect(
            lambda hz: self.updatePacketRate(self.ui.progressBar_pktIn, hz))
        self.flie.outKBPS.sig_KBPS.connect(
            lambda hz: self.updatePacketRate(self.ui.progressBar_pktOut, hz))

        # Connections GUI to GUI

        # Connections Within
        self.scanner.sig_foundURI.connect(self.receiveScanURI)
        self.sig_requestScan.connect(self.scanner.scan)
        self.sig_requestConnect.connect(self.flie.requestConnect)
        self.sig_requestDisconnect.connect(self.flie.requestDisconnect)
        self.flie.sig_stateUpdate.connect(self.updateFlieState)
        self.flie.sig_console.connect(self.ui.console.insertPlainText)

        # Show window
        self.show()

        # Initiate an initial Scan
        init_drivers(enable_debug_driver=False)
        self.startScanURI()
示例#24
0
	present_mode = not present_mode
	if present_mode:
		write("Present mode")
	else:
		write("Attendance mode")

# Calls the sync_data method and alerts user on success or failure
def sync(data):
	global present_mode
	write("Syncing...")
	if s.sync_data(data + ',' + ('P' if present_mode else 'A')):
		write("Successfully    synced data")
	else:
		write("Error syncing, please try again")

# Calls the scan method and returns the found data
def scan_code():
	write("Please display  code")
	return scan()

write("System starting up...")
present_mode = False
s = Sync()

cad = pifacecad.PiFaceCAD()
listener = pifacecad.SwitchEventListener(chip=cad)
listener.register(4, pifacecad.IODIR_FALLING_EDGE, scan_and_sync)
listener.register(0, pifacecad.IODIR_FALLING_EDGE, switch_modes)
listener.activate()
write("Startup complete...")
示例#25
0
ALARM_FORMAT = re.compile(r'([<>])(\d+(?:\.\d+)*) (btc|usd)')
closing = threading.Event()

def send(to, msg):
    requests.get('https://api.telegram.org/%s/sendMessage'%BOT_ID,
                  params = {'chat_id':to, 'text':unicode.encode(msg, 'utf-8')}
                )

#retrieve previous data
try:
    print "recovering environment:",
    env_file = open('env', 'rb')
    environ = pickle.load(env_file)
    offset = environ['offset']
    alarms = Sync(environ['alarms'])
    chats = Sync(environ['chats'])
    last_price_btc = environ['last_price_btc']
    last_price_usd = environ['last_price_usd']
    env_file.close()
    print "success"
except Exception as e:
    env_file = open('env', 'wb')
    alarms = Sync({})
    chats = Sync({})
    offset = 0
    last_price_btc = 0
    last_price_usd = 0
    environ = {'offset':offset, 'alarms':alarms.container, 'chats':chats.container, 'last_price_btc': last_price_btc, 'last_price_usd':last_price_usd}
    pickle.dump(environ, env_file)
    env_file.close()
示例#26
0
        if purge_time:
            self.purge_counter += 1
            if self.purge_counter == purge_sleep_ratio:
                try:
                    purge = Purge(self.__prefs, purge_time)
                except Exception, e:
                    logging.getLogger().exception(e)
                    raise
                self.purge_counter = 0

        if sync_sleep_ratio:
            #debug("sync count: %d", self.sync_counter)
            self.sync_counter += 1
            if self.sync_counter == sync_sleep_ratio:
                try:
                    sync = Sync(self.__prefs)
                    if self.__sync_upload:
                        debug("sync upload")
                        timestamp = sync.send_new_hosts()
                    if self.__sync_download:
                        debug("sync download")
                        new_hosts = sync.receive_new_hosts()
                        if new_hosts:
                            info("received new hosts: %s", str(new_hosts))
                            self.get_denied_hosts()
                            self.update_hosts_deny(new_hosts)
                    sync.xmlrpc_disconnect()
                except Exception, e:
                    logging.getLogger().exception(e)
                    raise
                self.sync_counter = 0
示例#27
0
def main():
    parser = argparse.ArgumentParser(
        description='Upload, download or sync photos and videos to Flickr.')
    parser.add_argument(
        '--custom-set',
        type=str,
        help=
        'customize set title from path using standard regex, e.g. "(.*)/(.*)"')
    parser.add_argument(
        '--custom-set-builder',
        type=str,
        help=
        'build a custom set title using matched groups, e.g. "{0}{1}" joins first two "(.*)/(.*)"'
    )
    parser.add_argument(
        '--download',
        type=str,
        help='download photos; specify a path or use "." for all')
    parser.add_argument(
        '--dry-run',
        action='store_true',
        help='report actions but do not change local/remote sets')
    parser.add_argument('--fix-missing-description',
                        action='store_true',
                        help='replace missing set description with set title')
    parser.add_argument(
        '--ignore-extensions',
        type=str,
        help='comma separated list of filename extensions to ignore')
    parser.add_argument(
        '--ignore-images',
        action='store_true',
        help='ignore image files: jpg, jpeg, png, gif, tif, tiff, bmp')
    parser.add_argument(
        '--ignore-videos',
        action='store_true',
        help=
        'ignore video files: m4v, mp4, avi, wmv, mov, mpg, mpeg, 3gp, mts, m2ts, ogg, ogv'
    )
    parser.add_argument(
        '--keywords',
        action='append',
        type=str,
        help='only upload files with IPTC metadata matching these keywords')
    parser.add_argument(
        '--nobrowser',
        action='store_true',
        help='support manual authentication when no web browser is available')
    parser.add_argument('--starts-with',
                        type=str,
                        help='only upload paths starting with this text')
    parser.add_argument(
        '--sync',
        action='store_true',
        help=
        'upload anything not on Flickr; download anything not on local filesystem'
    )
    parser.add_argument(
        '--sync-path',
        type=str,
        default=os.getcwd(),
        help=
        'sync path (default: current dir); individual files in --sync-path root are not synced to avoid disorganized Flickr sets'
    )
    parser.add_argument('--version',
                        action='store_true',
                        help='print current version: ' + version)

    args = parser.parse_args()

    args.windows = os.name == "nt"

    if args.version:
        logger.info('--version %s', version)
        exit(0)
    else:
        logger.debug('--version %s', version)

    args.sync_path = args.sync_path.rstrip(
        os.sep) + os.sep  # ensure sync path ends with "/"
    if not os.path.exists(args.sync_path):
        logger.error('--sync-path "%s" does not exist', args.sync_path)
        exit(0)

    local = Local(args)
    remote = Remote(args)
    sync = Sync(args, local, remote)
    sync.start_sync()
示例#28
0
import gevent
import sys

from sync import Sync
from settings import generateDefaultSetting
from BoardCode import HAKSA

if __name__ == "__main__":
    setting = generateDefaultSetting()
    sync = Sync(setting, HAKSA)
    if len(sys.argv) > 1:
        if sys.argv[1] == "firstRun":
            sync.firstRun()
            print(len(sync.keys()))

        elif sys.argv[1] == "Run":
            keys = len(sync.keys())
            [sync.delete(i) for i in range(keys - 3, keys + 1)]
            print(len(sync.keys()))
            sync.Run()
            print(len(sync.keys()))
            [sync.delete(i) for i in range(keys - 30, keys + 1)]
            print(len(sync.keys()))
            sync.Run()
            print(len(sync.keys()))
示例#29
0
def main():
    parser = argparse.ArgumentParser(
        description='Sync current folder to your flickr account.')
    parser.add_argument('--monitor',
                        action='store_true',
                        help='starts a daemon after sync for monitoring')
    parser.add_argument(
        '--starts-with',
        type=str,
        help='only sync that path starts with this text, e.g. "2015/06"')
    parser.add_argument(
        '--download',
        type=str,
        help='download the photos from flickr, specify a path or . for all')
    parser.add_argument('--ignore-videos',
                        action='store_true',
                        help='ignore video files')
    parser.add_argument('--ignore-images',
                        action='store_true',
                        help='ignore image files')
    parser.add_argument(
        '--ignore-ext',
        type=str,
        help='comma separated list of extensions to ignore, e.g. "jpg,png"')
    parser.add_argument('--version',
                        action='store_true',
                        help='output current version: ' + version)
    parser.add_argument(
        '--sync-path',
        type=str,
        default=os.getcwd(),
        help='specify the sync folder (default is current dir)')
    parser.add_argument(
        '--sync-from',
        type=str,
        help=
        'Only supported value: "all". Uploads anything that isn\'t on flickr, and download anything that isn\'t on the local filesystem'
    )
    parser.add_argument(
        '--custom-set',
        type=str,
        help='customize your set name from path with regex, e.g. "(.*)/(.*)"')
    parser.add_argument(
        '--custom-set-builder',
        type=str,
        help=
        'build your custom set title, e.g. "{0} {1}" to join the first two groups (default merges groups with hyphen)'
    )
    parser.add_argument(
        '--update-custom-set',
        action='store_true',
        help=
        'updates your set title from custom-set (and custom-set-builder, if given)'
    )
    parser.add_argument(
        '--custom-set-debug',
        action='store_true',
        help=
        'for testing your custom sets, asks for confirmation when creating an album on flickr'
    )
    parser.add_argument(
        '--username', type=str,
        help='token username')  # token username argument for api
    parser.add_argument('--keyword',
                        action='append',
                        type=str,
                        help='only upload files matching this keyword')

    args = parser.parse_args()

    if args.version:
        logger.info(version)
        exit()

    # validate args
    args.is_windows = os.name == 'nt'
    args.sync_path = args.sync_path.rstrip(os.sep) + os.sep
    if not os.path.exists(args.sync_path):
        logger.error('Sync path does not exists')
        exit(0)

    local = Local(args)
    remote = Remote(args)
    sync = Sync(args, local, remote)
    sync.start_sync()
示例#30
0
 def init_sync(self):
     self._sync = Sync(self._root_dir_path, self._working_dir_path, self._content, self._db, self._ipfs_client,
                       self._cipher)