def _print(self, msg, dip=constants.PEER_HOST, port=constants.PEER_PORT, notify=False): "Print message on console with peer id." # Get peer ID peer_id = self.swarm_manager.get_peerid_from_ip(dip, port) # Print with local peer id if not peer_id: peer_id = self.peerid else: notify = constants.ENABLE_NOTIFICATIONS # Print the message if self._printer: self._printer(msg, peer_id) # Display device notifications if self._device: if notify: self._device.vibrate_cb() self._device.notify_cb(title="ID: {}".format(peer_id), message=msg, timeout=1) else: Logger.warn("COMM: No device service registered.") # Log message Logger.info("COMM: {} : {}".format(peer_id, msg))
def _update_track_status(self, status_data): try: track_status = status_data['status']['track'] detection_status = track_status['status'] if detection_status == 0: track_status_msg = 'Searching for Track' elif detection_status == 1: track_status_msg = 'User defined Track' else: if track_status['trackId'] != 0: track = self.track_manager.find_track_by_short_id( track_status['trackId']) if track is None: track_status_msg = '(Unknown Track)' else: track_status_msg = track.name configuration_name = track.configuration if configuration_name and len(configuration_name): track_status_msg += ' (' + configuration_name + ')' else: track_status_msg = 'No track detected' self.set_state_message(track_status_msg) except Exception as e: Logger.warn( "ToolbarView: Could not retrieve track detection status " + str(e))
def scan_finished(self, scan_command): """A scan has been finished. This is a callback function which might be called from a separate thread. Therefore it is decorated with `mainthread`. `scan_command` is the calling `FPScanCommand`. """ Logger.info("waeup.identifier: scan finished.") self.cmd_running = None if self.scan_canceled: self.scan_canceled = False return self.root.btn_scan_text = self._scan_button_old_text self.prevent_scanning = False path = get_fpm_path() if not os.path.isfile(path): # Scan failed Logger.warn("waeup.identifier: no such file: %s" % path) PopupScanFailed().open() return if self.mode == 'verify': self.handle_verify(scan_command.get_result()) return self.upload_fingerprint(path)
def add_peer(self, pid, key, host, port): "Add peer to database." # localhost - 127.0.0.1 mapping. if host == "localhost": host = constants.LOCAL_TEST_HOST Logger.debug("SWARM: Adding Peer {} , {}@{}".format(pid, host, port)) if pid in self.keys(): Logger.warn("SWARM: Peer {} already exists. No changes made.".format(pid)) return None else: Logger.debug("SWARM: Adding Peer {} , {}@{}".format(pid, host, port)) # Peer dictionary structure defined here self.add_store( pid, dictionary=Peer(pid, key, host, port).dict ) # init stream buffer self.peer_stream_buffer[pid] = [] # Add peer to swarm graph if constants.NETWORKX_AVAILABLE: self.add_swarm_graph_node(pid)
def realise(self,use_cache = False, *args): if not self.name.endswith('.kv'): return #Force the creation of an image from self.template, thourhg real display from kivy.clock import Clock #Force the creaiotn of the tmpl miniture for display from template import BGTemplate try: Logger.info('[SGM] Realise FileItemView calling From File') tmpl = BGTemplate.FromFile(self.name, use_cache)[-1] except IndexError: Logger.warn('Warning: template file %s contains no Template !!'%self.name) from utils import alert alert('Error while loading %s template'%self.name) return #App.get_running_app().root.ids['realizer'].add_widget(tmpl) #force draw of the beast self.tmplWidget = tmpl def inner(*args): from kivy.base import EventLoop EventLoop.idle() cim = tmpl.toImage() cim.texture.flip_vertical() self.ids['img'].texture = cim.texture #App.get_running_app().root.ids['realizer'].remove_widget(tmpl) Clock.schedule_once(inner, -1)
def start(self, name, duration=None): record_script = "arecord -r 22050 -c 3 -f S16_LE --file-type wav -B 1000000 -D {} {}".format( get_record_device(), name) self.process = subprocess.Popen(record_script, shell=True) time.sleep(1) if os.path.exists(name): Logger.info("Recording successfully started") self.recording = True if duration is not None: time.sleep(duration) if self.recording: Logger.warn("Time limit reached, stopping record") self.stop() else: Logger.error( "Recording failed to start - sound card probably not found") self.recording = False btn_text = 'Failed to start recording\nPlease go back and check if sound device is plugged-in correctly.' # create content and add to the popup content = Button(text=btn_text) popup = Popup(title='Recording error', content=content, size_hint=(None, None), size=(600, 400), auto_dismiss=False) # bind the on_press event of the button to the dismiss function content.bind(on_press=popup.dismiss) # open the popup popup.open()
def setTrack(self, track): if track is None: # create a default, empty track if none provided track = TrackMap() raceTrackView = self.ids.track raceTrackView.loadTrack(track) name = track.name configuration = '' if len(track.configuration) == 0 else ' ({})'.format(track.configuration) self.ids.name.text = name + configuration self.ids.length.text = '' if track.length == 0 else '{} mi.'.format(track.length) flag_image = self.ids.flag cc = track.country_code if cc: cc = cc.lower() try: flagImagePath = 'resource/flags/' + str(track.country_code.lower()) + '.png' flag_image.source = flagImagePath except Exception as detail: Logger.warn('Error loading flag for country code: {}'.format(detail)) else: flag_image.source = 'resource/flags/blank.png' self.track = track
def enable_autoreload(self): """ Enable autoreload manually. It is activated automatically if "DEBUG" exists in environ. It requires the `watchdog` module. """ try: from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler except ImportError: Logger.warn("{}: Autoreloader is missing watchdog".format( self.appname)) return Logger.info("{}: Autoreloader activated".format(self.appname)) rootpath = self.get_root_path() # print("this is the root path",rootpath) self.w_handler = handler = FileSystemEventHandler() handler.dispatch = self._reload_from_watchdog self._observer = observer = Observer() for path in self.AUTORELOADER_PATHS: # print(path,"paths dey") options = {"recursive": True} if isinstance(path, (tuple, list)): # print("iii") path, options = path observer.schedule(handler, join(rootpath, path), **options) observer.start()
def realise(self,withValue = False, use_cache=False): Logger.info('Calling realisze on %s (with Value %s / use_cache %s'%(self,withValue,use_cache)) #Force the creation of an image from self.template, thourhg real display #Skipt of computed image exists if self.image: return from kivy.clock import Clock #Force the creaiotn of the tmpl miniture for display from template import BGTemplate if not self.template: return try: if not use_cache: Logger.info('[SGM]Realize StackPart calling from file') tmpl = BGTemplate.FromFile(self.template, use_cache)[-1] except IndexError: Logger.warn( 'Warning: template file %s contains no Template !!'%self.template) from utils import alert alert('Error while loading template %s '%self.template) return #App.get_running_app().root.ids['realizer'].add_widget(tmpl) #force draw of the beast if withValue: tmpl.apply_values(self.values) self.tmplWidget = tmpl def inner(*args): #Here is hould loop on the template to apply them on values from kivy.base import EventLoop EventLoop.idle() cim = tmpl.toImage() cim.texture.flip_vertical() self.ids['img'].texture = cim.texture #App.get_running_app().root.ids['realizer'].remove_widget(tmpl) Clock.schedule_once(inner, -1)
def wrapper(self, *args, **kwargs): try: return func(self, *args, **kwargs) except dbus.exceptions.DBusException as err: Logger.warn(f'BTMusicDisplay: DBus error while calling {func.__name__}: {err}') self.setDefaultValues() self.triggerRefreshBTDevice()
def realise(self, use_cache=False, *args): if not self.name.endswith('.kv'): return #Force the creation of an image from self.template, thourhg real display from kivy.clock import Clock #Force the creaiotn of the tmpl miniture for display from template import BGTemplate try: Logger.info('[SGM] Realise FileItemView calling From File') tmpl = BGTemplate.FromFile(self.name, use_cache)[-1] except IndexError: Logger.warn('Warning: template file %s contains no Template !!' % self.name) from utils import alert alert('Error while loading %s template' % self.name) return #App.get_running_app().root.ids['realizer'].add_widget(tmpl) #force draw of the beast self.tmplWidget = tmpl def inner(*args): from kivy.base import EventLoop EventLoop.idle() cim = tmpl.toImage() cim.texture.flip_vertical() self.ids['img'].texture = cim.texture #App.get_running_app().root.ids['realizer'].remove_widget(tmpl) Clock.schedule_once(inner, -1)
def register(self, cls, instance=None): '''Registers the class and adds it to :attr:`funcs_cls`. It also creates an instance (unless ``instance`` is provided) of the class that is added to :attr:`funcs_inst` and :attr:`funcs_inst_default`. This function is should be called to register a new class from a plugin. :Params: `cls`: subclass of :class:`FuncBase` The class to register. `instance`: instance of `cls` The instance of `cls` to use. If None, a default class instance, using the default :attr:`FuncBase.name` is stored. Defaults to None. ''' name = cls.__name__ funcs = self.funcs_cls if name in funcs: Logger.warn('"{}" is already a registered function'.format(name)) funcs[name] = cls f = cls(function_factory=self) if instance is None else instance if f.function_factory is not self: raise ValueError('Instance function factory is set incorrectly') f.name = fix_name(f.name, self.funcs_inst) self.funcs_inst[f.name] = f self._cls_inst_funcs[cls] = f self.funcs_inst_default[f.name] = f self.dispatch('on_changed')
def _add_unselected_channels(self, channels, source_ref): ProgressSpinner.increment_refcount() def get_results(results): # Auto-switch to time mode in charts only if the user # did not request it. if ( self.line_chart_mode == LineChartMode.DISTANCE and not self._results_has_distance(results) ): if self._user_refresh_requested == True: toast("Warning: one or more selected laps have missing distance data", length_long=True) self._user_refresh_requested = False else: self.line_chart_mode = LineChartMode.TIME self._refresh_chart_mode_toggle() # clone the incoming list of channels and pass it to the handler if self.line_chart_mode == LineChartMode.TIME: Clock.schedule_once(lambda dt: self._add_channels_results_time(channels[:], results)) elif self.line_chart_mode == LineChartMode.DISTANCE: Clock.schedule_once(lambda dt: self._add_channels_results_distance(channels[:], results)) else: Logger.error('LineChart: Unknown line chart mode ' + str(self.line_chart_mode)) try: self.datastore.get_channel_data(source_ref, ['Interval', 'Distance'] + channels, get_results) except Exception as e: Logger.warn('Non existant channel selected, not loading channels {}; {}'.format(channels, e)) finally: ProgressSpinner.decrement_refcount()
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 msg_rx_worker(self): Logger.info('RCPAPI: msg_rx_worker starting') comms = self.comms error_count = 0 while self._running.is_set(): msg = None try: msg = comms.read_message() if msg: # clean incoming string, and drop illegal characters msg = unicode(msg, errors='ignore') msgJson = json.loads(msg, strict=False) if 's' in msgJson: Logger.trace('RCPAPI: Rx: ' + str(msg)) else: Logger.debug('RCPAPI: Rx: ' + str(msg)) Clock.schedule_once(lambda dt: self.on_rx(True)) error_count = 0 for messageName in msgJson.keys(): Logger.trace('RCPAPI: processing message ' + messageName) listeners = self.msgListeners.get(messageName, None) if listeners: for listener in listeners: try: listener(msgJson) except Exception as e: Logger.error( 'RCPAPI: Message Listener Exception for' ) Logger.debug(traceback.format_exc()) break msg = '' else: sleep(NO_DATA_AVAILABLE_DELAY) except PortNotOpenException: Logger.debug("RCPAPI: Port not open...") msg = '' sleep(1.0) except Exception as e: Logger.warn( 'RCPAPI: Message rx worker exception: {} | {}'.format( repr(msg), str(e))) Logger.debug(traceback.format_exc()) msg = '' error_count += 1 if error_count > 5 and not self._auto_detect_event.is_set(): Logger.warn( "RCPAPI: Too many Rx exceptions; re-opening connection" ) self.recover_connection() self.connected_version = None sleep(5) else: sleep(0.25) safe_thread_exit() Logger.info("RCPAPI: msg_rx_worker exiting")
def card_touch(self, card, touch): """ handle game logic """ if self.BUSY: Logger.debug('Memory: busy, cancel event') return True if self.opened_card == card: Logger.debug('Memory: skip same card') return False if card.on_touch_down_custom(touch): Logger.info('Memory: touched card #%s ' % card.ref) if self.opened_card is not None: if self.opened_card != card: self.BUSY = True # touched a 2nd different card if self.opened_card.ref == card.ref: Logger.info('Memory: good card touched !') card.disable() self.opened_card.disable() self.nb_cards_left -= 2 Clock.schedule_once(self.anim_completes, card.ANIM_DURATION) if self.nb_cards_left == 0: Clock.schedule_once(kivy.app.App.get_running_app().won, card.ANIM_DURATION * 2) else: # incorrect card Logger.warn('Memory: incorrect card touched !') Clock.schedule_once(card.flip, self.PAUSE_DURATION) Clock.schedule_once(self.opened_card.flip, self.PAUSE_DURATION) Clock.schedule_once(self.anim_completes, self.PAUSE_DURATION) self.opened_card = None else: Logger.info('Memory: picked a first card') self.BUSY = True self.opened_card = card Clock.schedule_once(self.anim_completes, card.ANIM_DURATION) return False
def scan_finished(self, scan_command): """A scan has been finished. This is a callback function which might be called from a separate thread. Therefore it is decorated with `mainthread`. `scan_command` is the calling `FPScanCommand`. """ Logger.info("waeup.identifier: scan finished.") self.cmd_running = None if self.scan_canceled: self.scan_canceled = False return self.root.btn_scan_text = self._scan_button_old_text self.prevent_scanning = False path = os.path.join(os.getcwd(), "data.fpm") if not os.path.isfile(path): # Scan failed Logger.warn("waeup.identifier: no such file: %s" % path) PopupScanFailed().open() return if self.mode == 'verify': self.handle_verify(scan_command.get_result()) return self.upload_fingerprint(path)
def stop(self): self._running.clear() try: self._status_thread.join() except Exception as e: Logger.warn( 'StatusPump: failed to join status_worker: {}'.format(e))
def _on_sample(self, sample): """ Sample listener for data from RC. Saves data to Datastore if a session is being recorded :param sample: :return: """ if not self.recording: return # Merging previous sample with new data to desparsify the data self._sample_accumulator.update(sample) qsize = self._sample_queue.qsize() if qsize == 0: self._speed_up_send_rate() deltaT_ms = (datetime.utcnow() - self._sample_last_send).microseconds / 1000 if ((deltaT_ms >= self._sample_send_delay) or (qsize < SessionRecorder.SAMPLE_QUEUE_SLOWING_THRESHOLD)): if qsize > SessionRecorder.SAMPLE_QUEUE_SLOWING_THRESHOLD: self._slow_down_send_rate() self._sample_last_send = datetime.utcnow() try: self._sample_queue.put_nowait( copy.deepcopy(self._sample_accumulator)) self._sample_queue_full = False except Full: if not self._sample_queue_full: # latch to prevent the log from filling up with warnings Logger.warn('SessionRecorder: dropping sample; queue full') self._sample_queue_full = True
def setTrack(self, track): if track is None: # create a default, empty track if none provided track = TrackMap() raceTrackView = self.ids.track raceTrackView.loadTrack(track) name = track.name configuration = '' if len( track.configuration) == 0 else ' ({})'.format(track.configuration) self.ids.name.text = name + configuration self.ids.length.text = '' if track.length == 0 else '{} mi.'.format( track.length) flag_image = self.ids.flag cc = track.country_code if cc: cc = cc.lower() try: flagImagePath = 'resource/flags/' + str( track.country_code.lower()) + '.png' flag_image.source = flagImagePath except Exception as detail: Logger.warn( 'Error loading flag for country code: {}'.format(detail)) else: flag_image.source = 'resource/flags/blank.png' self.track = track
def stop(self): self._running.clear() try: if self._status_thread: self._status_thread.join() except Exception as e: Logger.warn('StatusPump: failed to join status_worker: {}'.format(e))
def _transfer_data(self, pid, data_class, data_content, desthost=None): "Transfer data to client with peer id." # Get peer route. peer_route = self._router(pid) # Get peer connection conn = self.swarm_manager.connect_to_peer(peer_route) # Set destination host IP if not desthost: desthost = self.swarm_manager.peer_host(pid) # Get peer key shared_key = self.swarm_manager.get_peer_key(pid) if not shared_key: raise Exception("No valid peer key could be found.") # Content length enforcement. try: # Pack data into stream stream = self.stream_manager.pack_stream( stream_type=data_class, stream_content=data_content, stream_host=desthost, shared_key=shared_key ) except StreamOverflowError as SOError: self._printer(SOError.info, self.peerid) Logger.warn("COMM: " + SOError.info) return False else: # Send data over connection return self._write_into_connection(conn, stream)
def set(self, key, value): if key in self.data: self.data[key] = value Logger.info(self.name + ": Set " + str(key) + " to " + str(value)) else: Logger.warn(self.name + ": \"" + str(key) + "\" is an invalid key")
def on_tag_gained(self, instance, value): valid_card = self.validate_card(value) if valid_card is False: Logger.warn('User Manager: someone attempted to access the system with an invalid card.') else: Logger.info('User Manager: the tag [{}] was valid.'.format(value)) # self.app.root.current_screen.tag = value self.app.last_gained_tag = self.employee
def shutdown_comms(self): Logger.debug('RCPAPI: shutting down comms') try: self.comms.close() self.comms.device = None except Exception as e: Logger.warn('RCPAPI: Shutdown rx worker exception: {}'.format(e)) Logger.info(traceback.format_exc())
def edit_metadata(self, book): path = book['path'] if path and exists(path): self._metadata_popup.book_path = path self._metadata_popup.open() else: Logger.warn('BookHandler: Tried to open book metadata popup ' 'with path which does not exist')
def delete_peer(self, pid): "Remove unauth peer." Logger.warn("SWARM: Peer [{}] left swarm.".format(pid)) # remove peer connection del self.peer_connections[pid] return self.delete_store(pid)
def connectionLost(self, reason): "Run when connection is lost with server." Logger.warn( "SERVER: Lost connection with peer {}".format(self._peer_repr) ) self.factory.app.on_client_disconnection(self.transport)
def _on_meta(self, meta): Logger.info("TelemetryConnection: got new meta") if self.authorized: try: self._channel_metas = meta self._send_meta() except Exception as e: Logger.warn("TelemetryConnection: Failed to send meta: {}".format(e))
def start_server(self): if platform == 'android': from android import AndroidService service = AndroidService('Mazerace server', 'Server is running') service.start('service started') self.service = service else: Logger.warn('Not android: Please start service manually!')
def shutdown_comms(self): Logger.info('RCPAPI: shutting down comms') try: self.comms.close() self.comms.device = None except Exception: Logger.warn('RCPAPI: Message rx worker exception: {} | {}'.format(msg, str(Exception))) Logger.info(traceback.format_exc())
def demote(self, child): if child not in self.children: Logger.warn('Child demoted not in stack (%s). Abordting' % child) return index = self.children.index(child) newindex = max(index - 1, 0) self.remove_widget(child) self.add_widget(child, index=newindex) self.parent.scroll_to(child)
def demote(self, child): if child not in self.children: Logger.warn('Child demoted not in stack (%s). Abordting'%child) return index = self.children.index(child) newindex = max(index-1,0) self.remove_widget(child) self.add_widget(child, index=newindex) self.parent.scroll_to(child)
def _on_meta(self, meta): Logger.info("TelemetryConnection: got new meta") if self.authorized: try: self._channel_metas = meta self._send_meta() except Exception as e: Logger.warn( "TelemetryConnection: Failed to send meta: {}".format(e))
def connectionLost(self, reason): "Run when connection is lost with server." Logger.warn( "AUTH: Peer Authentication connection terminated : {}".format( self._peer_repr) ) self.factory.app.on_server_auth_close(self.transport)
def shutdown_comms(self): Logger.info('RCPAPI: shutting down comms') try: self.comms.close() self.comms.device = None except Exception: Logger.warn('RCPAPI: Message rx worker exception: {} | {}'.format( msg, str(Exception))) Logger.info(traceback.format_exc())
def _add_channels_results_time(self, channels, query_data): try: time_data_values = query_data['Interval'] for channel in channels: chart = self.ids.chart channel_data_values = query_data[channel] channel_data = channel_data_values.values # If we queried a channel that has no sample results, skip adding the plot if len(channel_data) == 0 or channel_data[0] is None: continue key = channel_data_values.channel + str( channel_data_values.source) plot = SmoothLinePlot(color=self.color_sequence.get_color(key)) channel_plot = ChannelPlot(plot, channel_data_values.channel, channel_data_values.min, channel_data_values.max, channel_data_values.source) chart.add_plot(plot) points = [] time_index = OrderedDict() sample_index = 0 time_data = time_data_values.values sample_count = len(time_data) interval = max(1, int(sample_count / self.MAX_SAMPLES_TO_DISPLAY)) Logger.info('LineChart: plot interval {}'.format(interval)) last_time = None time = 0 last_time = time_data[0] while sample_index < sample_count: current_time = time_data[sample_index] if last_time > current_time: Logger.warn( 'LineChart: interruption in interval channel, possible reset in data stream ({}->{})' .format(last_time, current_time)) last_time = current_time sample = channel_data[sample_index] time += current_time - last_time last_time = current_time points.append((time, sample)) time_index[time] = sample_index sample_index += interval channel_plot.chart_x_index = time_index plot.ymin = channel_data_values.min plot.ymax = channel_data_values.max plot.points = points self._channel_plots[str(channel_plot)] = channel_plot # sync max chart x dimension self._update_max_chart_x() self._update_x_marker_value() finally: ProgressSpinner.decrement_refcount()
def addObservationString(self, timestamp, name, value, source): Logger.info("addObservationString: {},{},{}".format(timestamp,name,value)) if timestamp is not None and timestamp is not '': conn = self.engine.connect() try: obsInsert = self.observations.insert().values(timestamp=timestamp.tz_convert(None),name=name,source=source,valueNum=None,valueString=value,isForecast=False) result = conn.execute(obsInsert) except SQLAlchemyError as e: Logger.warn("Error {}".format(e)) pass
def promote(self, child): if child not in self.children: Logger.warn('Child promoted not in stack (%s). Aborting' % child) return index = self.children.index(child) newindex = min(index + 1, len(self.children)) self.remove_widget(child) self.add_widget(child, index=newindex) #Scroll the view self.parent.scroll_to(child)
def change_font_size(self): ''' Auto resizes the timer widget if it spills over the edge of the bounding box ''' widget = self.ids.timer try: if widget.texture_size[0] > widget.width: widget.font_size -= 1 except Exception as e: Logger.warn('[PitstopTimerView] Failed to change font size: {}'.format(e))
def read_file(self): if os.path.exists(self.file_path): with open(self.file_path) as f: data = yaml.load(f, Loader=yaml.FullLoader) Logger.info(f'Donkeyrc: Donkey file {self.file_path} loaded.') return data else: Logger.warn(f'Donkeyrc: Donkey file {self.file_path} does not ' f'exist.') return {}
def process(self, data): if not self._shoot_mode == HandledPiCameraView.SHOOT_MODE_VIEWER: return True if self.cameraimage is not None: try: self.cameraimage.memory_data = data except: Logger.warn("Skipping Image") # Logger.error(sys.exc_info()[0]) return False
def promote(self, child): if child not in self.children: Logger.warn('Child promoted not in stack (%s). Aborting'%child) return index = self.children.index(child) newindex = min(index+1, len(self.children)) self.remove_widget(child) self.add_widget(child, index=newindex) #Scroll the view self.parent.scroll_to(child)
def status_worker(self): Logger.info('StatusPump: status_worker starting') self._rc_api.addListener('status', self._on_status_updated) while self._running.is_set(): self._rc_api.get_status() sleep(StatusPump.STATUS_QUERY_INTERVAL_SEC) if not self._ready.wait(StatusPump.READY_WAIT_TIMEOUT_SEC): Logger.warn('StatusPump: timed out waiting for status response') Logger.info('StatusPump: status_worker exited') safe_thread_exit()
def build_node_dictionary(node, dictionary): """Recursively builds a dictionary of names for node and its children""" try: dictionary[node.name] = node except AttributeError: # TODO: For some reason this error detection actually does not work for buttons! log.warn("gui.py: " + str(node) + " does not have the 'name' attribute. Will not be accessible") for child in node.children: build_node_dictionary(child, dictionary)
def get_value(self): """get the text as typed number, in this case int""" if self.text == '': return 0 else: try: return int(self.text) except ValueError: Logger.warn( 'NumberImput: Could not convert text input. Returning 0') return 0
def deactivate_video(self): if self.trackball: if not self.recording_video: Logger.warn(TrackballHelper.ERR_MSG_NOT_RECORDING) else: with self._video_lock: self.recording_video = False self.video_thread.join() self.video_thread = None else: Logger.error(TrackballHelper.ERR_MSG_NO_SETUP)
def get_screen(self, name): '''Return the screen widget associated with the name or raise a :class:`ScreenManagerException` if not found. ''' matches = [s for s in self.screens if s.name == name] num_matches = len(matches) if num_matches == 0: raise ScreenManagerException('No Screen with name "%s".' % name) if num_matches > 1: Logger.warn('Multiple screens named "%s": %s' % (name, matches)) return matches[0]
def get_screen(self, name): '''Return the screen widget associated to the name, or raise a :class:`ScreenManagerException` if not found. ''' matches = [s for s in self.screens if s.name == name] num_matches = len(matches) if num_matches == 0: raise ScreenManagerException('No Screen with name "%s".' % name) if num_matches > 1: Logger.warn('Multiple screens named "%s": %s' % (name, matches)) return matches[0]
def _get(url): try: req = requests.get(url) if req.status_code == 200: return req.text else: Logger.warn('OctoPrint: got response: {}'.format(req.status_code)) except requests.exceptions.ConnectionError as e: Logger.error('OctoPrint: Connection Error ({}): {}'.format( e.errno, e.strerror)) return None
def get_pos_length(): """ Return a tuple of the length and position, or return 0, 0""" sound = Sound._sound if sound: try: return sound.get_pos(), sound._get_length() except Exception as e: Logger.warn("audioplayer.py: Failed to load sound, {0}".format( e)) return 0, 0 else: return 0, 0
def msg_rx_worker(self): Logger.info('RCPAPI: msg_rx_worker starting') comms = self.comms error_count = 0 while self._running.is_set(): msg = None try: msg = comms.read_message() if msg: # clean incoming string, and drop illegal characters msg = unicode(msg, errors='ignore') msgJson = json.loads(msg, strict=False) if 's' in msgJson: Logger.trace('RCPAPI: Rx: ' + str(msg)) else: Logger.debug('RCPAPI: Rx: ' + str(msg)) Clock.schedule_once(lambda dt: self.on_rx(True)) error_count = 0 for messageName in msgJson.keys(): Logger.trace('RCPAPI: processing message ' + messageName) listeners = self.msgListeners.get(messageName, None) if listeners: for listener in listeners: try: listener(msgJson) except Exception as e: Logger.error('RCPAPI: Message Listener Exception for') Logger.debug(traceback.format_exc()) break msg = '' else: sleep(NO_DATA_AVAILABLE_DELAY) except PortNotOpenException: Logger.debug("RCPAPI: Port not open...") msg = '' sleep(1.0) except Exception as e: Logger.warn('RCPAPI: Message rx worker exception: {} | {}'.format(repr(msg), str(e))) Logger.debug(traceback.format_exc()) msg = '' error_count += 1 if error_count > 5 and not self._auto_detect_event.is_set(): Logger.warn("RCPAPI: Too many Rx exceptions; re-opening connection") self.recover_connection() self.connected_version = None sleep(5) else: sleep(0.25) safe_thread_exit() Logger.info("RCPAPI: msg_rx_worker exiting")
def _add_channels_results_time(self, channels, query_data): try: time_data_values = query_data['Interval'] for channel in channels: chart = self.ids.chart channel_data_values = query_data[channel] channel_data = channel_data_values.values # If we queried a channel that has no sample results, skip adding the plot if len(channel_data) == 0 or channel_data[0] is None: continue key = channel_data_values.channel + str(channel_data_values.source) plot = SmoothLinePlot(color=self.color_sequence.get_color(key)) channel_plot = ChannelPlot(plot, channel_data_values.channel, channel_data_values.min, channel_data_values.max, channel_data_values.source) chart.add_plot(plot) points = [] time_index = OrderedDict() sample_index = 0 time_data = time_data_values.values sample_count = len(time_data) interval = max(1, int(sample_count / self.MAX_SAMPLES_TO_DISPLAY)) Logger.info('LineChart: plot interval {}'.format(interval)) last_time = None time = 0 last_time = time_data[0] while sample_index < sample_count: current_time = time_data[sample_index] if last_time > current_time: Logger.warn('LineChart: interruption in interval channel, possible reset in data stream ({}->{})'.format(last_time, current_time)) last_time = current_time sample = channel_data[sample_index] time += current_time - last_time last_time = current_time points.append((time, sample)) time_index[time] = sample_index sample_index += interval channel_plot.chart_x_index = time_index plot.ymin = channel_data_values.min plot.ymax = channel_data_values.max plot.points = points self._channel_plots[str(channel_plot)] = channel_plot # sync max chart x dimension self._update_max_chart_x() self._update_x_marker_value() finally: ProgressSpinner.decrement_refcount()
def activate_video(self): if self.trackball: if self.recording_video: Logger.warn(TrackballHelper.ERR_MSG_ALREADY_RECORDING) else: with self._video_lock: self.recording_video = True self.video_thread = threading.Thread( target=self.flash_video_recording) self.video_thread.start() else: Logger.error(TrackballHelper.ERR_MSG_NO_SETUP)
def connectionLost(self, reason): "Run when connection is lost with server." Logger.warn("CLIENT: Lost connection with peer {}".format( self._peer_repr ) ) self.factory.app._print( "Lost connection with peer {}".format(self._peer_repr) ) self.factory.app.on_server_disconnection(self.transport)
def _on_meta(self, meta): Logger.debug("TelemetryConnection: got new meta") if self.authorized: self._channel_data = meta self._running.clear() try: self._sample_timer.join() except Exception as e: Logger.warn("TelemetryConnection: Failed to join sample_timer: " + str(e)) self._send_meta() self._start_sample_timer()
def check_load_suggested_lap(self, new_session_id): sessions_view = self.ids.sessions_view if len(sessions_view.selected_laps) == 0: best_lap = self._datastore.get_channel_min('LapTime', [new_session_id], ['LapCount']) if best_lap: best_lap_id = best_lap[1] Logger.info('AnalysisView: Convenience selected a suggested session {} / lap {}'.format(new_session_id, best_lap_id)) sessions_view.select_lap(new_session_id, best_lap_id, True) main_chart = self.ids.mainchart main_chart.select_channels(AnalysisView.SUGGESTED_CHART_CHANNELS) HelpInfo.help_popup('suggested_lap', main_chart, arrow_pos='left_mid') else: Logger.warn('AnalysisView: Could not determine best lap for session {}'.format(new_session_id))