def on_touch_down(self, touch): """Handler when a task is touched. Checks for button touches first.""" x, y = touch.x, touch.y if self.dup_button.collide_point(x, y): # Duplicate the task self.dup_button.color = (.9, .6, 0, 1) Logger.debug("PendingTask: Duplicating task %s" % self.tid) if self.is_new(): self.manyman.new_task(self.command, self.name) else: self.manyman.comm.duplicate_task(self.tid) return False if self.start_button.collide_point(x, y): # Smart-start the task self.start_button.color = (.9, .6, 0, 1) if self.is_new(): self.manyman.comm.start_task(self.name, self.command) else: self.manyman.comm.move_task(self) self.parent.remove_widget(self) return False if not super(PendingTask, self).on_touch_down(touch): return False return True
def _on_gst_message(bus, message): Logger.trace('gst-bus: %s' % str(message)) # log all error messages if message.type == gst.MESSAGE_ERROR: error, debug = list(map(str, message.parse_error())) Logger.error('gstreamer_video: %s' % error) Logger.debug('gstreamer_video: %s' % debug)
def core_select_lib(category, llist, create_instance=False): category = category.lower() for option, modulename, classname in llist: try: # module activated in config ? if option not in kivy.kivy_options[category]: Logger.debug('%s: option <%s> ignored by config' % (category.capitalize(), option)) continue # import module mod = __import__(name='%s.%s' % (category, modulename), globals=globals(), locals=locals(), fromlist=[modulename], level=-1) cls = mod.__getattribute__(classname) # ok ! Logger.info('%s: using <%s> as %s provider' % (category.capitalize(), option, category)) if create_instance: cls = cls() return cls except Exception as e: Logger.warning('%s: Unable to use <%s> as %s' 'provider' % (category.capitalize(), option, category)) Logger.debug('', exc_info = e) Logger.critical('%s: Unable to find any valuable %s provider ' 'at all!' % (category.capitalize(), category.capitalize()))
def __init__(self, name, tid, core, status, **kwargs): Logger.debug("CoreTask: Inited coretask %s" % tid) self.tid = tid self._core = core self._status = status self.info_built = False self.info_showing = False self.info_button = None self.label = None self.info = None self.stop_button = None self.pause_button = None self.move_button = None self.kill_button = None self.button_strings = dict() self.scroll = None self._outfile = None self._out = [] self._cpu = 0.0 self._mem = 0.0 super(CoreTask, self).__init__(name, core.manyman, **kwargs) self._build()
def log_mesg(self, mesg="you forgot something..."): """For log messages. Arguments: - `mesg`: The debug message. """ Logger.debug("DiceKV: " + mesg)
def CreateAtlas(oPicPath,oAtlasFile,uDebugMsg): ''' creates an atlas file from all picture files in a folder ''' if oORCA.bIgnoreAtlas: return #can\'t get JPEG lib included in package, so just ignore atlas #if oORCA.uPlatform=='macosx' or oORCA.uPlatform=="ios" or oORCA.uPlatform=="win": if oORCA.uPlatform=='macosx' or oORCA.uPlatform=="ios": return try: if not FileExists(oAtlasFile): Logger.debug(uDebugMsg) #aExtensions=[u'.png',u'.jpg',u'.bmp',u'.gif'] # we exclude gifs as they might be animated aExtensions=[u'.png',u'.jpg',u'.bmp'] aPicFiles=[] oDirList=GetFileList(oPicPath, bSubDirs=True,bFullPath=True) for uFileName in oDirList: uExtension = os.path.splitext(uFileName)[1].lower() if uExtension in aExtensions: if uFileName.find( AdjustPathToOs(oORCA.uSkinPath+u'/atlas/'))==-1: aPicFiles.append(uFileName) try: Atlas.create(oAtlasFile[:-6],aPicFiles,1024) except Exception: pass except Exception as e: LogError(u'Error creating Atlas File:',e)
def resource_add_path(path): '''Add a custom path to search in ''' if path in resource_paths: return Logger.debug('Resource: add <%s> in path list' % path) resource_paths.append(path)
def config_updated(self, config): self.wifi_config = config.wifi_config Logger.debug("WifiConfig: got config: {}".format(self.wifi_config.to_json())) wifi_switch = self.ids.wifi_enabled wifi_switch.setControl(SettingsSwitch(active=self.wifi_config.active)) wifi_switch.control.bind(active=self.on_wifi_enable_change) wifi_client_switch = self.ids.client_mode wifi_client_switch.setControl(SettingsSwitch(active=self.wifi_config.client_mode_active)) wifi_client_switch.control.bind(active=self.on_client_mode_enable_change) wifi_ap_switch = self.ids.ap_mode wifi_ap_switch.setControl(SettingsSwitch(active=self.wifi_config.ap_mode_active)) wifi_ap_switch.control.bind(active=self.on_ap_mode_enable_change) ap_encryption = self.ids.ap_encryption ap_encryption.bind(on_setting=self.on_ap_encryption) encryption_spinner = SettingsMappedSpinner() self.load_ap_encryption_spinner(encryption_spinner, self.wifi_config.ap_encryption) ap_encryption.setControl(encryption_spinner) ap_channel = self.ids.ap_channel channel_spinner = SettingsMappedSpinner() self.build_ap_channel_spinner(channel_spinner, str(self.wifi_config.ap_channel)) ap_channel.bind(on_setting=self.on_ap_channel) ap_channel.setControl(channel_spinner) self.ids.client_ssid.text = self.wifi_config.client_ssid self.ids.client_password.text = self.wifi_config.client_password self.ids.ap_ssid.text = self.wifi_config.ap_ssid self.ids.ap_password.text = self.wifi_config.ap_password
def _initialize_image(self, step=-1): if step == -1: step = self.idx_stp try: if self.seq_images[step] == "": #Logger.debug("_initialize_image: same image for background:{}".format(self.bg_img)) pass else: Logger.debug("{}-{}".format(self.base_seq_dir, self.seq_images[step])) file_name = "" if os.path.exists(os.path.join("..", self.seq_images[step])): file_name = self.seq_images[step] elif os.path.exists(os.path.join(self.base_seq_dir, self.seq_images[step])): file_name = os.path.join(self.base_seq_dir, self.seq_images[step]) Logger.debug("_initialize_image: Initializing {}".format(file_name)) if not file_name == "": self.bg_img = file_name Logger.debug("_initialize_image: new image for background:{}".format(file_name)) else: self.bg_img = self.default_bg_img Logger.debug("_initialize_image: error ({}) and then default for bg:{}".format( file_name, self.default_bg_img)) except IndexError: self.bg_img = self.default_bg_img Logger.debug("_initialize_image: IndexError. Default for bg:{}".format( self.default_bg_img))
def pool_updated(self): """ Called when the expense pool has been updated """ Logger.debug("Ndf Pool : pool updated") self.settings.set('main', 'expenses', self.pool.stored_version()) self.property('pool').dispatch(self)
def core_register_libs(category, libs, base='kivy.core'): if 'KIVY_DOC' in os.environ: return category = category.lower() libs_loaded = [] libs_ignored = [] for option, lib in libs: try: # module activated in config ? if option not in kivy.kivy_options[category]: Logger.debug('{0}: option <{1}> ignored by config'.format( category.capitalize(), option)) libs_ignored.append(lib) continue # import module __import__(name='{2}.{0}.{1}'.format(category, lib, base), globals=globals(), locals=locals(), fromlist=[lib], level=0) libs_loaded.append(lib) except Exception as e: Logger.trace('{0}: Unable to use <{1}> as loader!'.format( category.capitalize(), option)) Logger.trace('', exc_info=e) libs_ignored.append(lib) Logger.info('{0}: Providers: {1} {2}'.format( category.capitalize(), ', '.join(libs_loaded), '({0} ignored)'.format( ', '.join(libs_ignored)) if libs_ignored else ''))
def on_touch_down(self, touch): if super(HexMapCell, self).on_touch_down(touch): return False coord_x, coord_y = self.even_r_coords if not self.visible_on_map: return False with self.canvas.after: Color(*kivy.utils.get_color_from_hex('#000000')) radius = 2 * self.height self.ell = Line(circle=(self.x, self.y, radius, 0, 360, 6), width=2) if not self.collide_with_bounding_circle(touch.x, touch.y): return False Logger.debug('Selected: ({}, {})'.format(coord_x, coord_y)) with self.canvas.after: if 'button' in touch.profile and touch.button == 'left': Color(*kivy.utils.get_color_from_hex('#00FF00')) if 'button' in touch.profile and touch.button == 'right': # TODO Will refactor to have separate on_touch_up for selected target hex instead. Color(*kivy.utils.get_color_from_hex('#FF0000')) radius = 2 * self.height self.ell = Line(circle=(self.x, self.y, radius, 0, 360, 6), width=2) self.parent.game.update_selected_cell(self.even_r_coords, self.terrain_colour) return True
def activate_module(self, name, win): '''Activate a module on a window''' if not name in self.mods: Logger.warning('Modules: Module <%s> not found' % name) return if not 'module' in self.mods[name]: try: self.import_module(name) except ImportError: return module = self.mods[name]['module'] if not self.mods[name]['activated']: # convert configuration like: # -m mjpegserver:port=8080,fps=8 # and pass it in context.config token config = dict() args = Config.get('modules', name) if args != '': values = Config.get('modules', name).split(',') for value in values: x = value.split('=', 1) if len(x) == 1: config[x[0]] = True else: config[x[0]] = x[1] msg = 'Modules: Start <%s> with config %s' % (name, str(config)) Logger.debug(msg) self.mods[name]['context'].config = config module.start(win, self.mods[name]['context'])
def storage_table(self, shorten_len=40, action_dict={}): "Display Store in table format." if not self._storage.keys(): return None table = restTable(["ID"] + list(self._store_keys)) for sid in self._storage.keys(): row = [sid] _dict = self._storage[sid] for k in _dict.keys(): # get value v = _dict[k] # Apply action for (key, action) in action_dict.iteritems(): if k == key: Logger.debug('STORE: Performing action on {}'.format(k)) v = action(v) # Check on length if (len(str(v)) > shorten_len): row += ["{}*".format(v[:shorten_len])] else: row += [v] table.add_row(row) return table
def recover_connection(self): if self._disconnect_callback: self._disconnect_callback() if self._enable_autodetect.is_set(): Logger.debug("RCPAPI: attempting to recover connection") self.run_auto_detect()
def _libc_clock_gettime_wrapper(): from os import strerror class struct_tv(ctypes.Structure): _fields_ = [('tv_sec', ctypes.c_long), ('tv_usec', ctypes.c_long)] _clock_gettime = _libc.clock_gettime _clock_gettime.argtypes = [ctypes.c_long, ctypes.POINTER(struct_tv)] if 'linux' in platform: _clockid = 4 # CLOCK_MONOTONIC_RAW (Linux specific) elif 'freebsd' in platform: # clockid constants from sys/time.h # _clockid = 4 # CLOCK_MONOTONIC (FreeBSD specific) # 11: CLOCK_MONOTONIC_PRECISE (FreeBSD known OK for 10.2) _clockid = 11 # _clockid = 12 # 12: CLOCK_MONOTONIC_FAST (FreeBSD specific) Logger.debug('clock.py: {{{:s}}} clock ID {:d}'.format( platform, _clockid)) else: _clockid = 1 # CLOCK_MONOTONIC tv = struct_tv() def _time(): if _clock_gettime(ctypes.c_long(_clockid), ctypes.pointer(tv)) != 0: _ernno = ctypes.get_errno() raise OSError(_ernno, strerror(_ernno)) return tv.tv_sec + (tv.tv_usec * 0.000000001) return _time
def clientConnectionFailed(self, connector, reason): "Run when attempt to connect with server fails." Logger.debug("AUTH: Connection failed. {}".format(reason.getErrorMessage())) # Display error on app console self.app._print("{}".format(reason.getErrorMessage()))
def load_wallet_by_name(self, path, ask_if_wizard=False): if not path: return if self.wallet and self.wallet.storage.path == path: return wallet = self.daemon.load_wallet(path, None) if wallet: if wallet.has_password(): self.password_dialog(wallet, _('Enter PIN code'), lambda x: self.load_wallet(wallet), self.stop) else: self.load_wallet(wallet) else: Logger.debug('Electrum: Wallet not found or action needed. Launching install wizard') def launch_wizard(): storage = WalletStorage(path, manual_upgrades=True) wizard = Factory.InstallWizard(self.electrum_config, self.plugins, storage) wizard.bind(on_wizard_complete=self.on_wizard_complete) action = wizard.storage.get_action() wizard.run(action) if not ask_if_wizard: launch_wizard() else: from .uix.dialogs.question import Question def handle_answer(b: bool): if b: launch_wizard() else: try: os.unlink(path) except FileNotFoundError: pass self.stop() d = Question(_('Do you want to launch the wizard again?'), handle_answer) d.open()
def destroy(self): """ Explicitly removes this image from the video memory and Kivy's cache. This functionality requires the custom kivy version at http://github.com/arcticshores/kivy """ if self.image is None or self.image is self.EMPTY_IMAGE: return from kivy.cache import Cache from kivy.graphics.opengl import glBindTexture, glDeleteTextures from kivy.logger import Logger Logger.debug("MyrmidonGFX: Destroying {0}".format(self.filename if self.filename else self.image)) # Remove from cache self.image.remove_from_cache() # Convert the ID to the right byte format for the GL method a1 = (self.image.texture.id >> 0) & 0xFF a2 = (self.image.texture.id >> 8) & 0xFF a3 = (self.image.texture.id >> 16) & 0xFF a4 = (self.image.texture.id >> 24) & 0xFF # Remove texture completely glBindTexture(self.image.texture.target, 0) glDeleteTextures(1, bytes(bytearray([a1, a2, a3, a4]))) # Since we've done a manual removal kivy shouldn't do it's own removal later self.image.texture.nofree = 1 # Stop this image from being used as a texture now self.image = None
def update_current(self): data_id = Data.current data = Data.get_data() Logger.debug('Update data: {}'.format(data)) data = json.dumps(data) RestClient.patch(data, '/{}'.format(data_id)) self.get_all()
def load(self, filename): Logger.debug("Image: Load <%s>" % filename) try: im = pygame.image.load(filename) except: Logger.warning("Image: Unable to load image <%s>" % filename) raise fmt = "" if im.get_bytesize() == 3: fmt = "rgb" elif im.get_bytesize() == 4: fmt = "rgba" # image loader work only with rgb/rgba image if fmt not in ("rgb", "rgba"): try: imc = im.convert(32) fmt = "rgba" except: Logger.warning("Image: Unable to convert image <%s> to rgba (was %s)" % filename, im.fmt) raise im = imc # update internals self.filename = filename data = pygame.image.tostring(im, fmt.upper(), True) return ImageData(im.get_width(), im.get_height(), fmt, data)
def on_keypress(self, window, keycode1, keycode2, text, modifiers): # Gestión del botón atrás. # Logger.debug("%s: on_keypress k1: %s, k2: %s, text: %s, mod: %s" % ( # APP, keycode1, keycode2, text, modifiers)) if self.scmgr.current == 'alarma' and keycode1 == 27: # escape self.cancelar_alarma(source="on_keypress") return True elif self.scmgr.current == 'alarma'\ and keycode1 == 1001: # Back button return True # Backbutton no hace nada durante la alarma elif keycode1 in [27, 1001]: if self._app_settings in self._app_window.children: self.close_settings() return True if self.scmgr.current == 'sectores': self.scmgr.transition.direction = 'down' self.scmgr.current = 'principal' return True elif self.scmgr.current == 'image': self.hide_image() return True else: Logger.debug("Pulsado el boton BACK") if platform == 'android': if self.service is not None: self.toast(text="Alarmas activas") activity.moveTaskToBack(True) return True return False
def cmd_send(self, cmdline=[]): """ Command: send Send a message to another peer's given ID. Peer must be present in the swarm. To view swarm use command 'peers'. Usage: send <pid> <message> Alternative Short Usage: @<pid> <message> """ try: (pid, msg) = ( cmdline[0], ' '.join(cmdline[1:])) except IndexError: self.print_message("Incorrect use of command 'send'") self.cmd_help("send") return None else: if not msg: Logger.warn("CORE: Please enter a message to send.") return None if self.services["COMM"].pass_message(pid, msg): # command log Logger.debug("CORE: Message sent to peer {}.".format(pid)) # Display send message self.print_message("[>> {}] : {}".format(pid, msg)) else: # command output self.print_message( "Unable to send message." )
def on_selected(self, instance, value): if value > 0: if self.selected in self.tracks_info: s = self.tracks_info[self.selected] # if s.arturl != 'data/image-loading.gif': # self.bgimg = s.arturl else: self.generate_empty_dict([value]) s = self.tracks_info[self.selected] # self.tracks_info.update({self.selected: Track( # artist=s.artist, title=s.title, album=s.album, # genre=s.genre, url=s.url, id=s.id, # arturl=s.arturl, color=(.7, .7, .7, .8), # duration=s.duration, is_selected=False)}) self.info = s.title if s.arturl != 'data/icons/wait.zip': # print('224: %s' % s.arturl) self.bgimg = s.arturl idx = self.idlist.index(value) if idx > 3 and len(self.idlist) > 8: # self.ids.trackslist.adapter.get_view(idx) # print(float(idx) / float(len(self.idlist))) # self.ids.trackslist.children[0].scroll_y = 1.000 -\ # float(idx + 3) / float(len(self.idlist)) self.ids.trackslist.scroll_to(idx - 3) Logger.debug('scroll to %s' % str(idx - 3)) else: # self.ids.trackslist.children[0].scroll_y = 1 self.ids.trackslist.scroll_to(0) Logger.debug('scroll to 0')
def register_renderer(self, uid): if uid != self.active_device: # if uid != 'local': # # self.bgimg = 'data/icons/wait2.gif' self.lists.update({self.active_device: ( self._idarray, self.idlist, self.tracks_info)}) self.tracks_info = {} self._idarray = '' self.idlist = [] self.bgimg = 'data/icons/background_icon2.png' self.selected = -1 # self.ids.trackslist.children[0].scroll_y = 1 # self.ids.trackslist.scroll_to(0) self.active_device = uid if uid == 'local': if self.pop: self.popup.dismiss() # print('Local Renderer') else: if uid in self.lists: self._idarray, self.idlist, self.tracks_info = self.lists[ uid] self.popup.dismiss() self.pop = False # if self.realparent.current_device['type'] == 'oh': Logger.debug( str(self.controller.parent.devices[uid]['services'])) self.get_subscriptions(uid)
def set_status(self, value): """Setter for the task's status. Binds and unbinds buttons.""" if self._status == value: return Logger.debug("CoreTask: Set status to %s" % value) self._status = value self.label.text = '%s\nStatus: %s' % (self.name, value) self.update_title() if not self.info_built: return if self.status == "Running": self.unbind_button(self.pause_button) self.pause_button.image = self.manyman.settings['task_pause_image'] self.bind_button(self.stop_button, self.stop) self.bind_button(self.pause_button, self.pause) self.bind_button(self.move_button, self.move) self.bind_button(self.kill_button, self.kill) elif self.status == "Stopped": self.unbind_button(self.pause_button) self.pause_button.image = \ self.manyman.settings['task_resume_image'] self.bind_button(self.pause_button, self.resume) elif self.status == "Finished" or self.status == "Killed": Clock.unschedule(self.request_output)
def on_start(self): Logger.debug("%s: on_start %s" % (APP, datetime.now())) from kivy.core.window import Window Window.bind(on_keyboard=self.on_keypress) if platform == 'android': android.map_key(android.KEYCODE_BACK, 1001) import android.activity as python_activity python_activity.bind(on_new_intent=self.on_new_intent) self.on_new_intent(activity.getIntent()) self.server_url = self.config.get('general', 'server_url') self.root.bind( on_touch_down=lambda *a: setattr(self, 'delay_image_loading', True), on_touch_up=lambda *a: setattr(self, 'delay_image_loading', False)) imagedir = ImageDir(server_url=self.server_url) wp = 'with_previous' imagedir.bind( on_navigate_top=lambda *a: setattr(self.root, wp, False), on_navigate_down=lambda *a: setattr(self.root, wp, True), on_img_selected=self.load_carousel, path=lambda w,v: setattr(self.root, 'title', v), on_loading_start=lambda *a: setattr(self.root, 'loading', True), on_loading_stop=lambda *a: setattr(self.root, 'loading', False)) self.imagedir = imagedir self.root.container.add_widget(imagedir) self.root.bind(on_touch_down=lambda *a: Loader.pause(), on_touch_up=lambda *a: Loader.resume()) Loader.max_upload_per_frame = 1 # Maximize interactivity
def detect(self, win, size): w, h = map(float, size) ratio = h / w portrait = ratio > 1. if portrait: aspect = h / w major = h / Metrics.dpi tall = aspect > LANDSCAPE_ASPECT_RATIO_CUTOFF else: aspect = w / h major = w / Metrics.dpi tall = aspect > PORTRAIT_ASPECT_RATIO_CUTOFF tablet = major > TABLET_SIZE_CUTOFF o = self.orient if tall != o.tall or portrait != o.portrait or tablet != o.tablet: o.portrait = portrait o.tall = tall o.tablet = tablet self.property('orient').dispatch(self) Logger.debug('portrait: {}, tall: {}, tablet: {}'.format( o.portrait, o.tall, o.tablet) )
def info_dismiss(self, *largs): """Handler when the detailed task info popup is closed.""" Logger.debug("CoreTask: Hiding info") self.info_showing = False # Stop requesting for output Clock.unschedule(self.request_output)
def add_data(self): data = Data.get_data() data['id'] = None # чтобы на сервере id сгенерилось Logger.debug('Add data: {}'.format(data)) data = json.dumps(data) RestClient.post(data) RestClient.get()
def cmd_sequence_worker(self): while True: try: command = self._command_queue.get() #this blocks forever command_list = command.command_list rootName = command.rootName winCallback = command.winCallback failCallback = command.failCallback comms = self.comms Logger.info('RCPAPI: Execute Sequence begin') if not comms.isOpen(): self.run_auto_detect() q = self.cmdSequenceQueue responseResults = {} cmdCount = 0 cmdLength = len(command_list) self.notifyProgress(cmdCount, cmdLength) try: for rcpCmd in command_list: payload = rcpCmd.payload index = rcpCmd.index option = rcpCmd.option level2Retry = 0 name = rcpCmd.name result = None self.addListener(name, self.rcpCmdComplete) while not result and level2Retry <= self.level_2_retries: if not payload == None and not index == None and not option == None: rcpCmd.cmd(payload, index, option) elif not payload == None and not index == None: rcpCmd.cmd(payload, index) elif not payload == None: rcpCmd.cmd(payload) else: rcpCmd.cmd() retry = 0 while not result and retry < DEFAULT_READ_RETRIES: try: result = q.get(True, self.msg_rx_timeout) msgName = result.keys()[0] if not msgName == name: Logger.info( 'RCPAPI: rx message did not match expected name ' + str(name) + '; ' + str(msgName)) result = None except Exception as e: Logger.info( 'RCPAPI: Read message timeout ' + str(e)) self.recoverTimeout() retry += 1 if not result: Logger.info('RCPAPI: Level 2 retry for (' + str(level2Retry) + ') ' + name) level2Retry += 1 if not result: raise Exception('Timeout waiting for ' + name) responseResults[name] = result[name] self.removeListener(name, self.rcpCmdComplete) cmdCount += 1 self.notifyProgress(cmdCount, cmdLength) if rootName: winCallback({rootName: responseResults}) else: winCallback(responseResults) except CommsErrorException: self.recover_connection() except Exception as detail: Logger.error('RCPAPI: Command sequence exception: ' + str(detail)) Logger.debug(traceback.format_exc()) failCallback(detail) self.recover_connection() Logger.info('RCPAPI: Execute Sequence complete') except Exception as e: Logger.error('RCPAPI: Execute command exception ' + str(e))
def rating_set(self,base,index,instance): Logger.debug('Application: rating_set('+instance.rating+')') instance.popup.dismiss() kmpc.kmpcmanager.mainmpdconnection.protocol.sticker_set('song',base,'rating',instance.rating).addCallback(partial(self.handle_rating_set,index,instance.rating,True)).addErrback(partial(self.handle_rating_set,index,instance.rating,False))
def nfc_disable_exchange(self): ''' Disable/Stop ndef exchange ''' Logger.debug('NFC: disable nfc exchange')
def nfc_enable_exchange(self, data): ''' Start sending data ''' Logger.debug('NFC: sending data {}'.format(data))
def nfc_enable(self): Logger.debug('NFC: enable') if self._initialised: Clock.schedule_interval(self.on_new_intent, 22)
Config.adddefaultsection('input') Config.adddefaultsection('postproc') Config.adddefaultsection('widgets') Config.adddefaultsection('modules') # Upgrade default configuration until we have the current version need_save = False if version != KIVY_CONFIG_VERSION and 'KIVY_NO_CONFIG' not in environ: Logger.warning('Config: Older configuration version detected' ' (%d instead of %d)' % ( version, KIVY_CONFIG_VERSION)) Logger.warning('Config: Upgrading configuration in progress.') need_save = True while version < KIVY_CONFIG_VERSION: Logger.debug('Config: Upgrading from %d to %d' % (version, version + 1)) if version == 0: # log level Config.setdefault('kivy', 'keyboard_repeat_delay', '300') Config.setdefault('kivy', 'keyboard_repeat_rate', '30') Config.setdefault('kivy', 'log_dir', 'logs') Config.setdefault('kivy', 'log_enable', '1') Config.setdefault('kivy', 'log_level', 'info') Config.setdefault('kivy', 'log_name', 'kivy_%y-%m-%d_%_.txt') Config.setdefault('kivy', 'window_icon', '') # default graphics parameters Config.setdefault('graphics', 'display', '-1') Config.setdefault('graphics', 'fullscreen', 'no')
def auto_detect_worker(self): class VersionResult(object): version_json = None def on_ver_win(value): version_result.version_json = value version_result_event.set() while True: try: self._auto_detect_event.wait() self._auto_detect_event.clear() self._enable_autodetect.wait() Logger.info("RCPAPI: Starting auto-detect") self._auto_detect_busy.set() self.sendCommandLock.acquire() self.addListener("ver", on_ver_win) comms = self.comms if comms and comms.isOpen(): comms.close() version_result = VersionResult() version_result_event = Event() version_result_event.clear() if comms.port: ports = [comms.port] else: ports = comms.get_available_ports() Logger.info('RCPAPI: Searching for device on all ports') testVer = VersionConfig() for p in ports: try: Logger.info('RCPAPI: Trying ' + str(p)) if self.detect_activity_callback: self.detect_activity_callback(str(p)) comms.port = p comms.open() self.sendGetVersion() version_result_event.wait(1) version_result_event.clear() if version_result.version_json != None: testVer.fromJson( version_result.version_json.get('ver', None)) if testVer.major > 0 or testVer.minor > 0 or testVer.bugfix > 0: break #we found something! else: try: Logger.warn('RCPAPI: Giving up on ' + str(p)) comms.close() finally: pass except Exception as detail: Logger.error('RCPAPI: Not found on ' + str(p) + " " + str(detail)) try: comms.close() finally: pass if version_result.version_json != None: Logger.info("RCPAPI: Found device version " + str(testVer) + " on port: " + str(comms.port)) self.detect_win(testVer) else: Logger.info('RCPAPI: Did not find device') comms.close() comms.port = None if self.detect_fail_callback: self.detect_fail_callback() except Exception as e: Logger.error('RCPAPI: Error running auto detect: ' + str(e)) Logger.debug(traceback.format_exc()) finally: Logger.info("RCPAPI: auto detect finished. port=" + str(comms.port)) self._auto_detect_busy.clear() self.removeListener("ver", on_ver_win) self.sendCommandLock.release() sleep(AUTODETECT_COOLOFF_TIME)
def _set_size(self, size): if super(WindowBase, self)._set_size(size): Logger.debug('Window: Resize window to %s' % str(self.size)) self.dispatch('on_resize', *size) return True return False
def updateAvailablePorts(self): Logger.debug('Settings: Setting port options') self.setPanelOptions('port', SerialAdapter.getPortNames())
def get_partly_visible_edge(self, edge, top, bottom, left, right, node, edge_equation): """ :param edge: an edge that can be seen onscreen but where at least one node is not visible :param top: equation representing the top border of the screen :param bottom: equation representing the bottom border of the screen :param left: equation representing the left border of the screen :param right: equation representing the right border of the screen :param node: the visible node connected to the edge, or None if no node is visible :param edge_equation: the equation of the checked edge :return: A tuple containing two NodeObjects, each representing a one of the edge's nodes, the edge's slope and the edge's equation. If one of the edge's nodes is not onscreen, the x,y coordinates represent the intersection between the edge and the screen, a new serial is created, size is set to 0 and real is set to False. """ first_node = None second_node = None if node: first_node = self.original_graph.get_node_by_serial(node.serial) # check if edge collides with top border if LineEquation.check_collision_point(edge_equation, top): col_point = LineEquation.get_equation_collision_point( edge_equation, top) location = {'x': round(col_point.x, 2), 'y': round(col_point.y, 2)} if first_node is not None: second_node = NodeObject(serial=get_serial(), location=location, size=0) second_node.real = False else: first_node = NodeObject(serial=get_serial(), location=location, size=0) first_node.real = False # check if edge collides with bottom border if LineEquation.check_collision_point(edge_equation, bottom): col_point = LineEquation.get_equation_collision_point( edge_equation, bottom) location = {'x': round(col_point.x, 2), 'y': round(col_point.y, 2)} if first_node is not None: second_node = NodeObject(serial=get_serial(), location=location, size=0) second_node.real = False else: first_node = NodeObject(serial=get_serial(), location=location, size=0) first_node.real = False # check if edge collides with left border if LineEquation.check_collision_point(edge_equation, left): col_point = LineEquation.get_equation_collision_point( edge_equation, left) location = {'x': round(col_point.x, 2), 'y': round(col_point.y, 2)} if first_node is not None: second_node = NodeObject(serial=get_serial(), location=location, size=0) second_node.real = False else: first_node = NodeObject(serial=get_serial(), location=location, size=0) first_node.real = False # check if edge collides with right border if LineEquation.check_collision_point(edge_equation, right): col_point = LineEquation.get_equation_collision_point( edge_equation, right) location = {'x': round(col_point.x, 2), 'y': round(col_point.y, 2)} if first_node is not None: second_node = NodeObject(serial=get_serial(), location=location, size=0) second_node.real = False else: first_node = NodeObject(serial=get_serial(), location=location, size=0) first_node.real = False if second_node is None: if first_node is None: return None else: Logger.debug( "Only One viable node for onscreen edge: {}".format( edge.print_by_serial())) return None # raise Exception("Only One viable node for onscreen edge: {}".format(edge.print_by_serial())) min_dist = edge.node1.get_radius() / 2 if first_node.distance(second_node) < min_dist: return None if first_node.x < second_node.x: curr_edge = (first_node, second_node, edge.slope, edge_equation) else: curr_edge = (second_node, first_node, edge.slope, edge_equation) return curr_edge
def set_config(self): app = App.get_running_app() self.system_id = app.config.get('experiment settings', 'systemid') paired_system_id = app.config.get('main image processing', 'paired_systemid') self.is_driving_system = app.config.get('main image processing', 'is_driving_system') self.top_dir_local = app.config.get('experiment settings', 'local_exp_path') self.top_dir_remote = app.config.get('experiment settings', 'remote_exp_path') # experiment length in minutes self.explength = app.config.getint('experiment settings', 'experimentlength') self.timelapse_option = app.config.get('LED matrix', 'timelapse_options') Logger.debug('Interface: timelapse option is %s' % str(self.timelapse_option)) self.hc_image_frequency = app.config.getint('LED matrix', 'hc_image_frequency') self.LEDcolor = app.config.get('LED matrix', 'ledcolor') self.matrix_radius = app.config.getint('LED matrix', 'matrixradius') self.led_center = (app.config.getint('LED matrix', 'ledx'), app.config.getint('LED matrix', 'ledy')) self.spreadsheet_id = app.config.get('experiment settings', 'google_spreadsheet_id') self.rclone_name = app.config.get('experiment settings', 'rclone_remote_name') self.teensy_config = TeensyConfig() # instantiate the ledMatrix self.ledMatrix = LEDMatrix(self.teensy_config, color=self.LEDcolor, radius=self.matrix_radius, mode='darkfield', center=self.led_center, do_timelapse=self.timelapse_option) res_string = app.config.get('main image processing', 'image_resolution') im_res = tuple(int(i) for i in res_string.split('x')) Logger.debug('Interface: image resolution is %s' % res_string) # if self.im_res_x != im_res[0] or self.im_res_y != im_res[1]: # # self._camera._camera.resolution = im_res # self.im_res_x, self.im_res_y = im_res[0], im_res[1] self.imaging_params['image_resolution'] = im_res self.imaging_params['video_resolution'] = app.config.get( 'camera settings', 'resolution') self.inter_video_interval = app.config.getint('camera settings', 'inter_video_interval') self.video_length = app.config.getint('camera settings', 'video_length') self.imaging_params['image_frequency'] = app.config.getint( 'main image processing', 'image_frequency') self.imaging_params['delta_threshold'] = app.config.getint( 'image delta', 'delta_threshold') self.imaging_params['num_pixel_threshold'] = app.config.getint( 'image delta', 'num_pixel_threshold') self.image_processing_mode = app.config.get('main image processing', 'image_processing_mode') self.nn_count_eggs = bool( int(app.config.get('neural net', 'nn_count_eggs'))) self.imaging_params[ 'image_processing_mode'] = self.image_processing_mode self.imaging_params['save_images'] = bool( app.config.getint('main image processing', 'save_images')) self.imaging_params['save_processed_images'] = \ bool(app.config.getint('main image processing', 'save_processed_images')) if paired_system_id in SYSTEM_IDS and self.image_processing_mode != 'None': self.paired_system_id = paired_system_id if self.is_exp_running: self.exp_code = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) Logger.debug('Interface: experiment code is %s' % self.exp_code) self.remote_savepath = self.top_dir_remote + '/'.join( [self.system_id, 'data', self.exp_code]) self.local_savepath = join(self.top_dir_local, self.system_id, 'data', self.exp_code) p1 = Popen([ "rclone", "mkdir", ':'.join([self.rclone_name, self.remote_savepath]) ]) app.config.set('experiment settings', 'remote_exp_path', self.remote_savepath) app.config.set('experiment settings', 'local_exp_path', self.local_savepath) app.config.write() video_save_dir = join(self.local_savepath, 'videos') calibrate_save_dir = join(self.local_savepath, 'images') if not exists(video_save_dir): makedirs(video_save_dir) if not exists(calibrate_save_dir): makedirs(calibrate_save_dir) if self.imaging_params['save_images']: unprocesspath = join(calibrate_save_dir, 'unprocessed') makedirs(unprocesspath) if self.imaging_params['save_processed_images']: processpath = join(calibrate_save_dir, 'processed') makedirs(processpath) p2 = Popen([ "rclone", "mkdir", ':'.join( [self.rclone_name, join(self.remote_savepath, 'videos')]) ]) p3 = Popen([ "rclone", "mkdir", ':'.join( [self.rclone_name, join(self.remote_savepath, 'images')]) ]) for p in [p1, p2, p3]: try: p.wait(timeout=2) except TimeoutExpired: p.kill() else: self.remote_savepath = self.top_dir_remote + '/'.join( [self.system_id, 'data', 'initial']) self.local_savepath = join(self.top_dir_local, self.system_id, 'data', 'initial') p = Popen([ "rclone", "mkdir", ':'.join([self.rclone_name, self.remote_savepath]) ]) try: p.wait(timeout=2) except TimeoutExpired: p.kill() if not os.path.exists(self.local_savepath): os.makedirs(self.local_savepath) self.LEDcolor = self.LEDcolor.lstrip('[').rstrip(']') self.LEDcolor = self.LEDcolor.replace(',', ';') # copy configuration to experiment folder file_to = '/'.join([self.local_savepath, basename(CONFIG_FILE)]) copyfile(CONFIG_FILE, file_to)
def addCallback(self, callback, section=None, key=None): Logger.debug('Settings: Adding callback: %s, %s', section, key) self.config.add_callback(callback, section, key) if key != None: callback(section, key, self.get(section, key))
def on_channels(self, instance, value): Logger.debug("TelemetryManager: Got channels") if self.telemetry_enabled: self.start()
if command.startswith('cd ') or command.startswith('export '): if command[0] == 'e': e_q = command[7:].find('=') _exprt = command[7:] if e_q: os.environ[_exprt[:e_q]] = _exprt[e_q + 1:] self.environment = os.environ.copy() else: try: if command[3] == os.sep: os.chdir(command[3:]) else: os.chdir(self.cur_dir + os.sep + command[3:]) self.cur_dir = os.getcwdu() except OSError, err: Logger.debug('Shell Console: err:' + err.strerror + ' directory:' + command[3:]) add_to_cache(u''.join((err.strerror, '\n'))) add_to_cache(u''.join((txtinput_command_line.text, '\n'))) txtinput_command_line.text = self.prompt() self.txtinput_command_line_refocus = True return txtinput_command_line.text = self.prompt() # store output in textcache parent = txtinput_command_line.parent # disable running a new command while and old one is running parent.remove_widget(txtinput_command_line) # add widget for interaction with the running command txtinput_run_command = TextInput(multiline=False, font_size=self.font_size, font_name=self.font_name)
def _send_auth(self): Logger.debug("TelemetryConnection: sending auth") auth_cmd = '{"cmd":{"schemaVer":2,"auth":{"deviceId":"' + self.device_id + '"}}}' self.send_msg(auth_cmd)
def stop_experiment(self, is_early): # finally, make sure to turn the blue LEDs off at the end of the experiment Logger.debug("Interface: updating with final parameters") led_commands = [{'matrix_mode': 'opto', 'is_on': str(0)}] self.experiment.ledMatrix.send_command(led_commands) # the experiment has ended in a regular way. if not is_early: # join the update process in the proper way # self.experiment.t_motion_queue_check.join() # Logger.debug('Interface: motion queue closed') self.experiment.update_process.join() self.experiment.piCam.join() Logger.debug('Interface: update process and camera closed') # the experiment has been ended prematurely else: # we'll have to terminate the update process self.experiment.update_process.terminate() # but we've waited for the camera to stop recording, so we should be able to join it self.experiment.piCam.join() Logger.debug( 'Interface: update process terminated and camera joined') # grab data from the spreadsheet and write it to a csv file, then save it to the cloud service max_row = self.explength + self.experiment.sheet.start_row cell_range = 'A1:L' + str(max_row) values = self.experiment.sheet.read_sheet(cell_range='A1:L') self.experiment.write_sheet_to_dbx(values) # copy logs to experiment folder # figure out the actual path by looking for the most recently modified folder. log_dir = '/'.join(['/home/pi/.kivy', LOG_DIR]) files = os.listdir(log_dir) paths = [os.path.join(log_dir, basename) for basename in files] log_path = max(paths, key=os.path.getctime) file_to = '/'.join([self.local_savepath, os.path.basename(log_path)]) copyfile(log_path, file_to) src = self.local_savepath dest = self.remote_savepath p3 = Popen([ "rclone", "copy", join(src, 'images/'), ':'.join([self.rclone_name, join(dest, 'images/')]) ]) p2 = Popen([ "rclone", "copy", join(src, 'videos/'), ':'.join([self.rclone_name, join(dest, 'videos/')]) ]) p1 = Popen(["rclone", "copy", src, ':'.join([self.rclone_name, dest])]) for p in [p1, p2, p3]: try: p.wait(timeout=30) except TimeoutExpired: p.kill() ManageLocalFiles.cleanup_files(src, dest, self.rclone_name) ManageLocalFiles.cleanup_files(join(src, 'videos/'), join(dest, 'videos/'), self.rclone_name) ManageLocalFiles.cleanup_files(join(src, 'images/'), join(dest, 'images/'), self.rclone_name) # reset folder names in .ini file for next experiment app = App.get_running_app() app.config.set('experiment settings', 'local_exp_path', self.top_dir_local) app.config.set('experiment settings', 'remote_exp_path', self.top_dir_remote) app.config.write() # update experiment button (changes button image and text and updates 'is_exp_running') self.is_exp_running = False self.snapshot_image_source = 'icons/snapshot_not_prepped.png' self.exp_image_source = 'icons/experiment_not_prepped.png' self.exp_text = 'Experiment over' Logger.info('Interface: experiment ended')
def on_telemetry_enabled(self, instance, value): Logger.debug("TelemetryManager: on_telemetry_enabled: " + str(value)) if value: self.start() else: self._user_stopped()
def _on_meta(self, channel_metas): Logger.debug("TelemetryManager: Got meta") self.channels = channel_metas
def register(classobj): '''Register a new class to load the sound.''' Logger.debug('Audio: register %s' % classobj.__name__) SoundLoader._classes.append(classobj)
def handle_accept(self): Logger.debug("TelemetryConnection: handle_accept()")
def load(filename, **kwargs): # atlas ? if filename[:8] == 'atlas://': # remove the url rfn = filename[8:] # last field is the ID try: rfn, uid = rfn.rsplit('/', 1) except ValueError: raise ValueError('Image: Invalid %s name for atlas' % filename) # search if we already got the atlas loaded atlas = Cache.get('kv.atlas', rfn) # atlas already loaded, so reupload the missing texture in cache, # because when it's not in use, the texture can be removed from the # kv.texture cache. if atlas: texture = atlas[uid] fn = 'atlas://%s/%s' % (rfn, uid) cid = '%s|%s|%s' % (fn, False, 0) Cache.append('kv.texture', cid, texture) return Image(texture) # search with resource afn = rfn if not afn.endswith('.atlas'): afn += '.atlas' afn = resource_find(afn) if not afn: raise Exception('Unable to found %r atlas' % afn) atlas = Atlas(afn) Cache.append('kv.atlas', rfn, atlas) # first time, fill our texture cache. for nid, texture in atlas.textures.items(): fn = 'atlas://%s/%s' % (rfn, nid) cid = '%s|%s|%s' % (fn, False, 0) Cache.append('kv.texture', cid, texture) return Image(atlas[uid]) # extract extensions ext = filename.split('.')[-1].lower() # prevent url querystrings if filename.startswith((('http://', 'https://'))): ext = ext.split('?')[0] # special case. When we are trying to load a "zip" file with image, we # will use the special zip_loader in ImageLoader. This might return a # sequence of images contained in the zip. if ext == 'zip': return ImageLoader.zip_loader(filename) else: im = None for loader in ImageLoader.loaders: if ext not in loader.extensions(): continue Logger.debug('Image%s: Load <%s>' % (loader.__name__[11:], filename)) im = loader(filename, **kwargs) break if im is None: raise Exception('Unknown <%s> type, no loader found.' % ext) return im
def load(self): Logger.debug('VideoPyGst: Load <%s>' % self._filename) self._playbin.set_state(gst.STATE_NULL) self._playbin.set_property('uri', self._get_uri()) self._playbin.set_state(gst.STATE_READY)
def set_active_track(self, track): Logger.debug("RCPAPI: setting active track: {}".format(track)) track_json = track.toJson() self.sendCommand({'setActiveTrack': {'track': track_json}})
def SaveRepositoryXML(self, uType, uDescription): """ Saves the main repository directory xml """ oPath = Globals.oPathTmp + "RepManager" oPath.Create() oPath = oPath + "repositories" oPath.Create() oPath = oPath + uType oPath.Create() oFnXml = cFileName(oPath) + 'repository.xml' oXMLRoot = Element('repository') oVal = SubElement(oXMLRoot, 'version') oVal.text = '1.00' oVal = SubElement(oXMLRoot, 'type') oVal.text = uType oVal = SubElement(oXMLRoot, 'description') oVal.text = uDescription oXMLEntries = SubElement(oXMLRoot, 'entries') for oEntry in self.oRepManagerEntries: Logger.debug('Saving Repository-Entry [%s]' % oEntry.oFnEntry.string) oEntry.oRepEntry.WriteToXMLNode(oXMLEntries) for oSource in oEntry.oRepEntry.aSources: bZipParentDir = cPath.CheckIsDir(oSource.uLocal) # Create according Zip if bZipParentDir: uUpper1 = os.path.split( os.path.abspath(oSource.uSourceFile))[0] uUpper2 = os.path.split(os.path.abspath(uUpper1))[0] uUpper = uUpper1[len(uUpper2) + 1:] uUpper = os.path.basename(oSource.uLocal) uUpper = os.path.basename(oSource.uSourceFile) uFinalPath = uType oDest = cFileName().ImportFullPath( '%s/RepManager/repositories/%s/%s' % (Globals.oPathTmp.string, uFinalPath, uUpper)) uUpper1 = os.path.split(os.path.abspath(oSource.uLocal))[0] uRoot = '%s/%s/' % (Globals.oPathRoot.string, uType) uRoot = AdjustPathToOs(ReplaceVars(uUpper1) + '/') self.aZipFiles.append({ 'filename': oSource.uLocal, 'dstfilename': oDest.string, 'removepath': uRoot, 'skipfiles': ToUnicode(oEntry.oRepEntry.aSkipFileNames) }) else: uDest = AdjustPathToOs( '%s/RepManager/repositories/%s/%s.zip' % (Globals.oPathTmp.string, uType, os.path.splitext(os.path.basename( oSource.uLocal))[0])) uRoot = AdjustPathToOs(Globals.oPathRoot.string + "/" + oSource.uTargetPath) self.aZipFiles.append({ 'filename': oSource.uLocal, 'dstfilename': uDest, 'removepath': uRoot }) oFSFile = open(oFnXml.string, 'w') uContent = XMLPrettify(oXMLRoot) uContent = ReplaceVars(uContent) if PY2: oFSFile.write(uContent.encode('utf8')) else: oFSFile.write(EscapeUnicode(uContent)) oFSFile.close()
def cmd_sequence_worker(self): Logger.info('RCPAPI: cmd_sequence_worker starting') while self._running.is_set(): try: # Block for 1 second for messages command = self._command_queue.get( True, RcpApi.COMMAND_SEQUENCE_TIMEOUT) command_list = command.command_list rootName = command.rootName winCallback = command.winCallback failCallback = command.failCallback comms = self.comms Logger.debug('RCPAPI: Execute Sequence begin') if not comms.isOpen(): self.run_auto_detect() q = self.cmdSequenceQueue responseResults = {} cmdCount = 0 cmdLength = len(command_list) self.notifyProgress(cmdCount, cmdLength) try: for rcpCmd in command_list: payload = rcpCmd.payload index = rcpCmd.index option = rcpCmd.option last = rcpCmd.last level2Retry = 0 name = rcpCmd.name result = None self.addListener(name, self.rcpCmdComplete) while not result and level2Retry <= self.level_2_retries: args = [] if payload is not None: args.append(payload) if index is not None: args.append(index) if option is not None: args.append(option) if last is not None: args.append(last) rcpCmd.cmd(*args) retry = 0 while not result and retry < DEFAULT_READ_RETRIES: try: result = q.get(True, self.msg_rx_timeout) msgName = result.keys()[0] if not msgName == name: Logger.warn( 'RCPAPI: rx message did not match expected name ' + str(name) + '; ' + str(msgName)) result = None except Exception as e: Logger.warn( 'RCPAPI: Read message timeout waiting for {}' .format(name)) self.recoverTimeout() retry += 1 if not result: Logger.warn('RCPAPI: Level 2 retry for (' + str(level2Retry) + ') ' + name) level2Retry += 1 if not result: raise Exception('Timeout waiting for ' + name) responseResults[name] = result[name] self.removeListener(name, self.rcpCmdComplete) cmdCount += 1 self.notifyProgress(cmdCount, cmdLength) if rootName: callback = self.callback_factory( winCallback, {rootName: responseResults}) else: callback = self.callback_factory( winCallback, responseResults) Clock.schedule_once(callback) except CommsErrorException: self.recover_connection() self.connected_version = None except Exception as detail: Logger.error('RCPAPI: Command sequence exception: ' + str(detail)) Logger.error(traceback.format_exc()) callback = self.callback_factory(failCallback, detail) Clock.schedule_once(callback) self.connected_version = None self.recover_connection() Logger.debug('RCPAPI: Execute Sequence complete') except Queue.Empty: pass except Exception as e: Logger.error('RCPAPI: Execute command exception ' + str(e)) Logger.info('RCPAPI: cmd_sequence_worker exiting') safe_thread_exit()
def auto_detect_worker(self): Logger.info('RCPAPI: auto_detect_worker starting') class VersionResult(object): version_json = None def on_ver_win(value): version_result.version_json = value version_result_event.set() while self._running.is_set(): self._auto_detect_event.wait() self._auto_detect_event.clear() self._enable_autodetect.wait() # check again if we're shutting down # to prevent a needless re-detection attempt if not self._running.is_set(): break try: Logger.debug("RCPAPI: Starting auto-detect") self._auto_detect_busy.set() self.sendCommandLock.acquire() self.addListener("ver", on_ver_win) comms = self.comms if comms and comms.isOpen(): comms.close() version_result = VersionResult() version_result_event = Event() version_result_event.clear() if comms.device: devices = [comms.device] else: devices = comms.get_available_devices() last_known_device = self._settings.userPrefs.get_pref( 'preferences', 'last_known_device') # if there was a last known device try this one first. if last_known_device: Logger.info( 'RCPAPI: trying last known device first: {}'. format(last_known_device)) # ensure we remove it from the existing list try: devices.remove(last_known_device) except ValueError: pass devices = [last_known_device] + devices Logger.debug('RCPAPI: Searching for device') testVer = VersionConfig() for device in devices: try: Logger.debug('RCPAPI: Trying ' + str(device)) if self.detect_activity_callback: self.detect_activity_callback(str(device)) comms.device = device comms.open() self.sendGetVersion() version_result_event.wait(2) version_result_event.clear() if version_result.version_json != None: testVer.fromJson( version_result.version_json.get('ver', None)) if testVer.is_valid: break # we found something! else: try: Logger.debug('RCPAPI: Giving up on ' + str(device)) comms.close() finally: pass except Exception as detail: Logger.error('RCPAPI: Not found on ' + str(device) + " " + str(detail)) Logger.error(traceback.format_exc()) try: comms.close() finally: pass if testVer.is_valid: Logger.debug("RCPAPI: Found device version " + str(testVer) + " on port: " + str(comms.device)) self.detect_win(testVer) self._auto_detect_event.clear() self._settings.userPrefs.set_pref('preferences', 'last_known_device', comms.device) else: Logger.debug('RCPAPI: Did not find device') comms.close() comms.device = None if self.detect_fail_callback: self.detect_fail_callback() except Exception as e: Logger.error('RCPAPI: Error running auto detect: ' + str(e)) Logger.error(traceback.format_exc()) if self.detect_fail_callback: self.detect_fail_callback() finally: Logger.debug("RCPAPI: auto detect finished. port=" + str(comms.device)) self._auto_detect_busy.clear() self.removeListener("ver", on_ver_win) self.sendCommandLock.release() comms.device = None sleep(AUTODETECT_COOLOFF_TIME) safe_thread_exit() Logger.debug('RCPAPI: auto_detect_worker exiting')
def enable_autorecover(self): Logger.debug("RCPAPI: Enabling auto recover") self._enable_autodetect.set()
def get_meta(self): Logger.debug("RCPAPI: sending meta") self.sendCommand({'getMeta': None})
def save(self, *args): """Put text in my store, return True if it changed""" if self.name_wid is None or self.store is None: Logger.debug("{}: Not saving, missing name_wid or store".format(type(self).__name__)) return if not (self.name_wid.text or self.name_wid.hint_text): Logger.debug("{}: Not saving, no name".format(type(self).__name__)) return if self.name_wid.text and self.name_wid.text[0] in string.digits + string.whitespace + string.punctuation: # TODO alert the user to invalid name Logger.debug("{}: Not saving, invalid name".format(type(self).__name__)) return if hasattr(self, '_do_parse'): try: parse(self.source) except SyntaxError: # TODO alert user to invalid source Logger.debug("{}: Not saving, couldn't parse".format(type(self).__name__)) return do_redata = False if self.name_wid.text: if ( self.name_wid.hint_text and self.name_wid.hint_text != self.name_wid.text and hasattr(self.store, self.name_wid.hint_text) ): delattr(self.store, self.name_wid.hint_text) do_redata = True if ( not hasattr(self.store, self.name_wid.text) or getattr(self.store, self.name_wid.text) != self.source ): Logger.debug("{}: Saving!".format(type(self).__name__)) setattr(self.store, self.name_wid.text, self.source) do_redata = True elif self.name_wid.hint_text: if ( not hasattr(self.store, self.name_wid.hint_text) or getattr(self.store, self.name_wid.hint_text) != self.source ): Logger.debug("{}: Saving!".format(type(self).__name__)) setattr(self.store, self.name_wid.hint_text, self.source) do_redata = True return do_redata
def disable_autorecover(self): Logger.debug("RCPAPI: Disabling auto recover") self._enable_autodetect.clear()