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 populate(self): self._textures = [] fname = self.filename if __debug__: Logger.trace('Image: %r, populate to textures (%d)' % (fname, len(self._data))) for count in range(len(self._data)): # first, check if a texture with the same name already exist in the # cache chr = type(fname) uid = chr(u'%s|%d|%d') % (fname, self._mipmap, count) texture = Cache.get('kv.texture', uid) # if not create it and append to the cache if texture is None: imagedata = self._data[count] source = '{}{}|'.format( 'zip|' if fname.endswith('.zip') else '', self._nocache) imagedata.source = chr(source) + uid texture = Texture.create_from_data( imagedata, mipmap=self._mipmap) if not self._nocache: Cache.append('kv.texture', uid, texture) if imagedata.flip_vertical: texture.flip_vertical() # set as our current texture self._textures.append(texture) # release data if ask if not self.keep_data: self._data[count].release_data()
def log_mesg(self, mesg="you forgot something..."): """For log messages. Arguments: - `mesg`: The debug message. """ Logger.debug("DiceKV: " + mesg)
def on_focus(self, instance, value, *largs): win = self._win if not win: self._win = win = self.get_root_window() if not win: # we got argument, it could be the previous schedule # cancel focus. if len(largs): Logger.warning('Textinput: ' 'Cannot focus the element, unable to get root window') return else: Clock.schedule_once(partial(self.on_focus, self, value), 0) return if value: keyboard = win.request_keyboard(self._keyboard_released, self) self._keyboard = keyboard keyboard.bind( on_key_down=self._keyboard_on_key_down, on_key_up=self._keyboard_on_key_up) Clock.schedule_interval(self._do_blink_cursor, 1 / 2.) else: keyboard = self._keyboard keyboard.unbind( on_key_down=self._keyboard_on_key_down, on_key_up=self._keyboard_on_key_up) keyboard.release() self.cancel_selection() Clock.unschedule(self._do_blink_cursor) self._win = None
def run(self): self.haveSocket = False # create socket self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # fix trouble if python leave without cleaning well the socket # not needed under windows, he can reuse addr even if the socket # are in fin2 or wait state. if os.name in ['posix', 'mac'] and hasattr(socket, 'SO_REUSEADDR'): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # try to bind the socket, retry if necessary while not self.haveSocket and self.isRunning: try : self.socket.bind((self.ipAddr, self.port)) self.socket.settimeout(0.5) self.haveSocket = True except socket.error, e: error, message = e.args # special handle for EADDRINUSE if error == errno.EADDRINUSE: Logger.error('OSC: Address %s:%i already in use, retry in 2 second' % (self.ipAddr, self.port)) else: Logger.exception(e) self.haveSocket = False # sleep 2 second before retry time.sleep(2)
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 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 read(self, keep_reading): """ Reads data from the socket. Will continue to read until either "\r\n" is found in the data read from the socket or keep_reading.is_set() returns false :param keep_reading: Event object that is checked while data is read :type keep_reading: threading.Event :return: String or None """ msg = '' Logger.info("SocketConnection: reading...") while keep_reading.is_set(): try: data = self.socket.recv(4096) if data == '': return None msg += data if msg[-2:] == '\r\n': if msg != '': Logger.info("SocketConnection: returning data {}".format(msg)) return msg else: return None except socket.timeout: pass
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 build(self): # the root is created in pictures.kv root = self.root # get any files into images directory curdir = dirname(__file__) ## for filename in glob(join(curdir, 'images', '*')): #try: # # load the image # URL = 'https://farm1.staticflickr.com/176/478156552_9badc190eb_o.jpg' # img = AsyncImage(source=URL) # #picture = Picture(source=filename, rotation=randint(-30, 30)) # # add to the main field # #root.add_widget(picture) # root.add_widget(img) #except Exception as e: # Logger.exception('Pictures: Unable to load <%s>' % filename) for filename in glob(join(curdir, 'images', '*')): try: # load the image picture = Picture(source=filename, rotation=randint(-30, 30)) # add to the main field root.add_widget(picture) except Exception as e: Logger.exception('Pictures: Unable to load <%s>' % filename)
def on_play(self, instance, value): if not value: Logger.info('Recorder: Stop playing %r' % self.filename) EventLoop.remove_input_provider(self) return if not exists(self.filename): Logger.error('Recorder: Unable to found %r file, play aborted.' % ( self.filename)) return with open(self.filename, 'r') as fd: data = fd.read().splitlines() if len(data) < 2: Logger.error('Recorder: Unable to play %r, file truncated.' % ( self.filename)) return if data[0] != '#RECORDER1.0': Logger.error('Recorder: Unable to play %r, invalid header.' % ( self.filename)) return # decompile data self.play_data = [literal_eval(x) for x in data[1:]] self.play_time = time() self.play_me = {} Logger.info('Recorder: Start playing %d events from %r' % (len(self.play_data), self.filename)) EventLoop.add_input_provider(self)
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 delete_clock(self, touch, *args): # TODO: Fix touch_up passing through when popup dismissed. try: Clock.unschedule(touch.ud['event']) except KeyError: Logger.exception( 'Application: Touch up passed through and unscheduled clock event could not be unscheduled. A bug...')
def on_start(self): ''' This is the start point of the kivy ui ''' import time Logger.info('Time to on_start: {} <<<<<<<<'.format(time.clock())) Logger.info("dpi: {} {}".format(metrics.dpi, metrics.dpi_rounded)) win = Window win.bind(size=self.on_size, on_keyboard=self.on_keyboard) win.bind(on_key_down=self.on_key_down) win.softinput_mode = 'below_target' self.on_size(win, win.size) self.init_ui() self.load_wallet_by_name(self.electrum_config.get_wallet_path()) # init plugins run_hook('init_kivy', self) # default tab self.switch_to('history') # bind intent for bitcoin: URI scheme if platform == 'android': from android import activity from jnius import autoclass PythonActivity = autoclass('org.renpy.android.PythonActivity') mactivity = PythonActivity.mActivity self.on_new_intent(mactivity.getIntent()) activity.bind(on_new_intent=self.on_new_intent) # URI passed in config uri = self.electrum_config.get('url') if uri: self.set_URI(uri)
def read_from_in_pipe(self, *l): txt = '\n' txt_line = '' os_read = os.read self_stdin_pipe = self.stdin_pipe self_mode = self.mode self_write = self.write Clock_schedule_once = Clock.schedule_once self_update_cache = self.update_cache self_flush = self.flush obj = self.obj try: while txt != '': txt = os_read(self_stdin_pipe, 1) txt_line = u''.join((txt_line, txt)) if txt == '\n': if self_mode == 'stdin': # run command self_write(txt_line) else: Clock_schedule_once( partial(self_update_cache, txt_line, obj), 0) self_flush() txt_line = '' except OSError as e: Logger.exception(e)
def run(self): '''Launches the app in standalone mode. ''' if not self.built: self.load_config() self.load_kv(filename=self.kv_file) root = self.build() if root: self.root = root if self.root: if not isinstance(self.root, Widget): Logger.critical('App.root must be an _instance_ of Widget') raise Exception('Invalid instance in App.root') from kivy.core.window import Window Window.add_widget(self.root) # Check if the window is already created from kivy.base import EventLoop window = EventLoop.window if window: self._app_window = window window.set_title(self.get_application_name()) icon = self.get_application_icon() if icon: window.set_icon(icon) self._install_settings_keys(window) else: Logger.critical("Application: No window is created." " Terminating application run.") return self.dispatch('on_start') runTouchApp() self.stop()
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 _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 __init__(self, **kwargs): kwargs.setdefault('filename', None) kwargs.setdefault('eos', 'stop') kwargs.setdefault('async', True) kwargs.setdefault('autoplay', False) super(VideoBase, self).__init__() self._wantplay = False self._buffer = None self._filename = None self._texture = None self._volume = 1. self._state = '' self._autoplay = kwargs.get('autoplay') self._async = kwargs.get('async') self.eos = kwargs.get('eos') if self.eos == 'pause': Logger.warning("'pause' is deprecated. Use 'stop' instead.") self.eos = 'stop' self.filename = kwargs.get('filename') Clock.schedule_interval(self._update, 1 / 30.) if self._autoplay: self.play()
def tile_draw(self, nx, ny, tx, ty, sx, sy, zoom, bound): '''Draw a specific tile on the screen. Return False if the tile is not yet available.''' # nx, ny = index of tile # tx, ty = real position on scatter # sx, sy = real size on scatter # pzoom = current zoom level image = self.tileserver.get(nx, bound-ny-1, zoom, self.maptype) if image in (None, False): return if not image.texture: Logger.exception('Returned image has no texture.') return if image.texture.wrap is None: image.texture.wrap = GL_CLAMP alpha = Cache.get('tileserver.tilesalpha', image.id) if alpha is None: alpha = 0 if image.loaded: # as soon as we have the image alpha += min(self._dt * 4, 1.0) # fade it in Cache.append('tileserver.tilesalpha', image.id, alpha) with self.canvas: Color(1, 1, 1, alpha) Rectangle(pos=(tx, ty), size=(sx, sy), texture=image.texture)
def calculate_break_point(forces,material): materials = {13: 20.4, 16: 30.6, 18:38.5, 19:42.9, 22:57.2,25.4:75.8, 26:79.3 , 28:91.6, 30:105, 32:119 } ton = 2000 try: for force in forces: if abs(float(forces[0])) > materials[float(material)] * ton: print "BREAKS" print "\nMax tension to break:" print materials[float(material)] * ton print " \nCurrent tension:" print abs(float(forces[0])) pass_image.source = 'breaks.jpg' pass_image.reload() else: print "PASS" print "\nMax tension to break:" print materials[float(material)] * ton print " \nCurrent tension:" print abs(float(forces[0])) pass_image.source = 'pass.jpg' pass_image.reload() except Exception as e: Logger.exception('Material does not exist')
def on_start(self): ''' This is the start point of the kivy ui ''' import time Logger.info('Time to on_start: {} <<<<<<<<'.format(time.clock())) Logger.info("dpi: {} {}".format(metrics.dpi, metrics.dpi_rounded)) win = Window win.bind(size=self.on_size, on_keyboard=self.on_keyboard) win.bind(on_key_down=self.on_key_down) # Register fonts without this you won't be able to use bold/italic... # inside markup. from kivy.core.text import Label Label.register('Roboto', 'gui/kivy/data/fonts/Roboto.ttf', 'gui/kivy/data/fonts/Roboto.ttf', 'gui/kivy/data/fonts/Roboto-Bold.ttf', 'gui/kivy/data/fonts/Roboto-Bold.ttf') win.softinput_mode = 'below_target' self.on_size(win, win.size) self.init_ui() self.load_wallet_by_name(self.electrum_config.get_wallet_path()) # init plugins run_hook('init_kivy', self) # were we sent a url? self.uri = self.electrum_config.get('url') # default tab self.switch_to('send' if self.uri else 'history')
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 on_key_up(self, key, scancode=None, codepoint=None, modifier=None, **kwargs): '''Event called when a key is up (same arguments as on_keyboard)''' if 'unicode' in kwargs: Logger.warning("The use of the unicode parameter is deprecated, " "and will be removed in future versions. Use codepoint " "instead, which has identical semantics.")
def check_auth(self): """ Launch an authentication check """ Logger.info("Ndf : Checking auth : NDFAPP") _connection = self.get_connection() _connection.check_auth(self.check_auth_success, self.check_auth_error)
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 do_pause(self): # should go to app pause mode. from kivy.app import App from kivy.base import stopTouchApp app = App.get_running_app() if not app: Logger.info('WindowSDL: No running App found, exit.') stopTouchApp() return if not app.dispatch('on_pause'): Logger.info('WindowSDL: App doesn\'t support pause mode, stop.') stopTouchApp() return # XXX FIXME wait for sdl resume while True: event = self._win.poll() if event is False: continue if event is None: continue action, args = event[0], event[1:] if action == 'quit': EventLoop.quit = True self.close() break elif action == 'windowrestored': break app.dispatch('on_resume')
def ensure_window(self): '''Ensure that we have a window. ''' import kivy.core.window # NOQA if not self.window: Logger.critical('App: Unable to get a Window, abort.') sys.exit(1)
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 on_call_removed(self, path, properties): for call in self.calls: if call.path == path: self.calls.pop(call) Logger.info('HFP: Call destroyed')
def GetHeaderLabels(self) -> List[str]: # Empty function Logger.error("You must implement GetHeaderLabels") return ['']
def update(self): Logger.info("Smell Angle: {0}".format(self.smell())) Logger.info("Distance: {0}".format(self.distance())) pass
from sys import platform from os import environ from functools import wraps, partial from kivy.context import register_context from kivy.config import Config from kivy.logger import Logger from kivy.compat import clock as _default_time import time try: from kivy._clock import CyClockBase, ClockEvent, FreeClockEvent, \ CyClockBaseFree except ImportError: Logger.error( 'Clock: Unable to import kivy._clock. Have you perhaps forgotten to ' 'compile kivy? Kivy contains Cython code which needs to be compiled. ' 'A missing kivy._clock often indicates the Cython code has not been ' 'compiled. Please follow the installation instructions and make sure ' 'to compile Kivy') raise from threading import Event as ThreadingEvent # some reading: http://gameprogrammingpatterns.com/game-loop.html def _get_sleep_obj(): pass try: import ctypes
def _thread_run(self, **kwargs): input_fn = kwargs.get('input_fn') queue = kwargs.get('queue') device = kwargs.get('device') drs = kwargs.get('default_ranges').get touches = {} touches_sent = [] point = {} l_points = [] # prepare some vars to get limit of some component range_min_position_x = 0 range_max_position_x = 2048 range_min_position_y = 0 range_max_position_y = 2048 range_min_pressure = 0 range_max_pressure = 255 invert_x = int(bool(drs('invert_x', 0))) invert_y = int(bool(drs('invert_y', 0))) def process(points): actives = [args['id'] for args in points] for args in points: tid = args['id'] try: touch = touches[tid] if touch.sx == args['x'] and touch.sy == args['y']: continue touch.move(args) if tid not in touches_sent: queue.append(('begin', touch)) touches_sent.append(tid) queue.append(('update', touch)) except KeyError: touch = HIDMotionEvent(device, tid, args) touches[touch.id] = touch for tid in touches.keys()[:]: if tid not in actives: touch = touches[tid] if tid in touches_sent: touch.update_time_end() queue.append(('end', touch)) touches_sent.remove(tid) del touches[tid] def normalize(value, vmin, vmax): return (value - vmin) / float(vmax - vmin) # open the input fd = open(input_fn, 'rb') # get the controler name (EVIOCGNAME) device_name = fcntl.ioctl(fd, EVIOCGNAME + (256 << 16), " " * 256).split('\x00')[0] Logger.info('HIDMotionEvent: using <%s>' % device_name) # get abs infos bit = fcntl.ioctl(fd, EVIOCGBIT + (EV_MAX << 16), ' ' * sz_l) bit, = struct.unpack('Q', bit) for x in xrange(EV_MAX): # preserve this, we may want other things than EV_ABS if x != EV_ABS: continue # EV_ABS available for this device ? if (bit & (1 << x)) == 0: continue # ask abs info keys to the devices sbit = fcntl.ioctl(fd, EVIOCGBIT + x + (KEY_MAX << 16), ' ' * sz_l) sbit, = struct.unpack('Q', sbit) for y in xrange(KEY_MAX): if (sbit & (1 << y)) == 0: continue absinfo = fcntl.ioctl( fd, EVIOCGABS + y + (struct_input_absinfo_sz << 16), ' ' * struct_input_absinfo_sz) abs_value, abs_min, abs_max, abs_fuzz, \ abs_flat, abs_res = struct.unpack('iiiiii', absinfo) if y == ABS_MT_POSITION_X: range_min_position_x = drs('min_position_x', abs_min) range_max_position_x = drs('max_position_x', abs_max) Logger.info('HIDMotionEvent: ' + '<%s> range position X is %d - %d' % (device_name, abs_min, abs_max)) elif y == ABS_MT_POSITION_Y: range_min_position_y = drs('min_position_y', abs_min) range_max_position_y = drs('max_position_y', abs_max) Logger.info('HIDMotionEvent: ' + '<%s> range position Y is %d - %d' % (device_name, abs_min, abs_max)) elif y == ABS_MT_PRESSURE: range_min_pressure = drs('min_pressure', abs_min) range_max_pressure = drs('max_pressure', abs_max) Logger.info('HIDMotionEvent: ' + '<%s> range pressure is %d - %d' % (device_name, abs_min, abs_max)) # read until the end while fd: data = fd.read(struct_input_event_sz) if len(data) < struct_input_event_sz: break # extract each event for i in xrange(len(data) / struct_input_event_sz): ev = data[i * struct_input_event_sz:] # extract timeval + event infos tv_sec, tv_usec, ev_type, ev_code, ev_value = \ struct.unpack('LLHHi', ev[:struct_input_event_sz]) # sync event if ev_type == EV_SYN: if ev_code == SYN_MT_REPORT: if 'id' not in point: continue l_points.append(point) elif ev_code == SYN_REPORT: process(l_points) l_points = [] elif ev_type == EV_MSC and ev_code in (MSC_RAW, MSC_SCAN): pass else: # compute multitouch track if ev_code == ABS_MT_TRACKING_ID: point = {} point['id'] = ev_value elif ev_code == ABS_MT_POSITION_X: val = normalize(ev_value, range_min_position_x, range_max_position_x) if invert_x: val = 1. - val point['x'] = val elif ev_code == ABS_MT_POSITION_Y: val = 1. - normalize(ev_value, range_min_position_y, range_max_position_y) if invert_y: val = 1. - val point['y'] = val elif ev_code == ABS_MT_ORIENTATION: point['orientation'] = ev_value elif ev_code == ABS_MT_BLOB_ID: point['blobid'] = ev_value elif ev_code == ABS_MT_PRESSURE: point['pressure'] = normalize( ev_value, range_min_pressure, range_max_pressure) elif ev_code == ABS_MT_TOUCH_MAJOR: point['size_w'] = ev_value elif ev_code == ABS_MT_TOUCH_MINOR: point['size_h'] = ev_value
def __init__(self, device, args): super(HIDInputMotionEventProvider, self).__init__(device, args) self.input_fn = None self.default_ranges = dict() # split arguments args = args.split(',') if not args: Logger.error('HIDInput: Filename missing in configuration') Logger.error('HIDInput: Use /dev/input/event0 for example') return None # read filename self.input_fn = args[0] Logger.info('HIDInput: Read event from <%s>' % self.input_fn) # read parameters for arg in args[1:]: if arg == '': continue arg = arg.split('=') # ensure it's a key = value if len(arg) != 2: Logger.error('HIDInput: invalid parameter ' '%s, not in key=value format.' % arg) continue # ensure the key exist key, value = arg if key not in HIDInputMotionEventProvider.options: Logger.error('HIDInput: unknown %s option' % key) continue # ensure the value try: self.default_ranges[key] = int(value) except ValueError: err = 'HIDInput: invalid value "%s" for "%s"' % (key, value) Logger.error(err) continue # all good! Logger.info('HIDInput: Set custom %s to %d' % (key, int(value)))
def toggle_nav_drawer(self): Logger.warning( "KivyMD: The 'toggle_nav_drawer' method is deprecated, " "use 'set_state' instead." ) self.set_state("toggle", animation=True)
def on_netstat_changed(self, sender, message): Logger.info('Network: ' + sender + ' ' + str(message)) if sender == 'Name': self.carrier = message elif sender == 'Strength': self.network_strength = message
def call(self, number): self.modem.Dial(number, '') Logger.info('HFP: Call initialised')
def on_call_added(self, path, properties): call = Call(path, self.bluetooth, properties, self) self.calls.append(call) Logger.info('HFP: Call created')
'No class named <%s> in module <%s>' % (name, item['module'])) cls = item['cls'] = getattr(module, name) elif item['baseclasses']: rootwidgets = [] for basecls in item['baseclasses'].split('+'): rootwidgets.append(Factory.get(basecls)) cls = item['cls'] = type(str(name), tuple(rootwidgets), {}) else: raise FactoryException('No information to create the class') return cls get = __getattr__ #: Factory instance to use for getting new classes Factory = register_context('Factory', FactoryBase) # Now import the file with all registers # automatically generated by build_factory import kivy.factory_registers # NOQA Logger.info('Factory: %d symbols loaded' % len(Factory.classes)) if __name__ == '__main__': Factory.register('Vector', module='kivy.vector') Factory.register('Widget', module='kivy.uix.widget')
def on_property_changed(self, sender, message): Logger.info('Telephony: ' + sender + ' changed to ' + message) if sender == 'State': self.status = message elif sender == 'Name': self.network_name = message
os.environ['KIVY_NO_FILELOG'] = '1' os.environ['KIVY_NO_CONSOLELOG'] = '1' os.environ["KIVY_NO_ARGS"] = "1" from queue import Queue import time from kivy.config import Config from kivy.logger import Logger from kivy.base import runTouchApp, EventLoop from kivy.clock import Clock from kivy.uix.widget import Widget as KivyWidget for handler in Logger.handlers: Logger.removeHandler(handler) sys.stderr = sys.__stderr__ import mpfmc import mpfmc.core from mpf.tests.MpfBcpTestCase import MockBcpClient from mpf.tests.MpfTestCase import MpfTestCase, patch, UnitTestConfigLoader class TestBcpClient(MockBcpClient): def __init__(self, machine, name, bcp): super().__init__(machine, name, bcp) self.queue = Queue() self.exit_on_close = False
def __init__(self, bluetooth): Logger.info('HFP: Loading hfp-module') bluetooth.bind(modems=self.on_modems_change) self.bluetooth = bluetooth self.on_modems_change(self, bluetooth.modems)
def on_quotes(self, d): Logger.info("on_quotes") self._trigger_update_history()
def register(classobj): '''Register a new class to load the sound.''' Logger.debug('Audio: register %s' % classobj.__name__) SoundLoader._classes.append(classobj)
self._text_size = x text_size = property(_get_text_size, _set_text_size, doc='''Get/set the (width, height) of the ' 'contrained rendering box''') usersize = property(_get_text_size, _set_text_size, doc='''(deprecated) Use text_size instead.''') # Load the appropriate provider label_libs = [] if USE_SDL2: label_libs += [('sdl2', 'text_sdl2', 'LabelSDL2')] else: label_libs += [('pygame', 'text_pygame', 'LabelPygame')] label_libs += [('pil', 'text_pil', 'LabelPIL')] Text = Label = core_select_lib('text', label_libs) if 'KIVY_DOC' not in os.environ: if not Label: from kivy.logger import Logger import sys Logger.critical('App: Unable to get a Text provider, abort.') sys.exit(1) # For the first initialization, register the default font Label.register(DEFAULT_FONT, *_default_font_paths)
def on_history(self, d): Logger.info("on_history") self._trigger_update_history()
async def send_to_all(self, message): Logger.info("Sending to everyone!") for s in self._connections: s.write(bytes(message + "\n", encoding="UTF-8"))
def on_language(self, instance, language): Logger.info('language: {}'.format(language)) _.switch_lang(language)
except ImportError: __hash__ = __date__ = '' # internals for post-configuration __kivy_post_configuration = [] if platform == 'macosx' and sys.maxsize < 9223372036854775807: r = '''Unsupported Python version detected!: Kivy requires a 64 bit version of Python to run on OS X. We strongly advise you to use the version of Python that is provided by Apple (don't use ports, fink or homebrew unless you know what you're doing). See http://kivy.org/docs/installation/installation-macosx.html for details. ''' Logger.critical(r) def require(version): '''Require can be used to check the minimum version required to run a Kivy application. For example, you can start your application code like this:: import kivy kivy.require('1.0.1') If a user attempts to run your application with a version of Kivy that is older than the specified version, an Exception is raised. The Kivy version string is built like this:: X.Y.Z[-tag[-tagrevision]]
def _restart_json_serial(self): Logger.info( 'FirmwareUpdateView: Re-enabling RaceCapture Communications') self.rc_api.enable_autorecover() self.rc_api.run_auto_detect()
def on_resume(self): Logger.debug("FGcontroller resumed") # Here you can check if any data needs replacing (usually nothing) pass
def require(version): '''Require can be used to check the minimum version required to run a Kivy application. For example, you can start your application code like this:: import kivy kivy.require('1.0.1') If a user attempts to run your application with a version of Kivy that is older than the specified version, an Exception is raised. The Kivy version string is built like this:: X.Y.Z[-tag[-tagrevision]] X is the major version Y is the minor version Z is the bugfixes revision The tag is optional, but may be one of 'dev', 'alpha', or 'beta'. The tagrevision is the revision of the tag. .. warning:: You must not ask for a version with a tag, except -dev. Asking for a 'dev' version will just warn the user if the current Kivy version is not a -dev, but it will never raise an exception. You must not ask for a version with a tagrevision. ''' def parse_version(version): # check for tag tag = None tagrev = None if '-' in version: v = version.split('-') if len(v) == 2: version, tag = v elif len(v) == 3: version, tag, tagrev = v else: raise Exception('Revision format must be X.Y.Z[-tag]') # check x y z v = version.split('.') if len(v) != 3: if 'dev0' in v: tag = v.pop() else: raise Exception('Revision format must be X.Y.Z[-tag]') return [int(x) for x in v], tag, tagrev # user version revision, tag, tagrev = parse_version(version) # current version sysrevision, systag, systagrev = parse_version(__version__) # ensure that the required version don't contain tag, except dev if tag not in (None, 'dev'): raise Exception('Revision format must not have any tag except "dev"') if tag == 'dev' and systag != 'dev': Logger.warning('Application requested a -dev version of Kivy. ' '(You have %s, but the application requires %s)' % (__version__, version)) # not tag rev (-alpha-1, -beta-x) allowed. if tagrev is not None: raise Exception('Revision format must not contain any tagrevision') # finally, checking revision if sysrevision < revision: raise Exception('The version of Kivy installed on this system ' 'is too old. ' '(You have %s, but the application requires %s)' % (__version__, version))
def update_ctrl(self,data): controls=data.strip("\n").split(',') self.controlsFG = controls speed = int(float(controls[14])) altitude = int(float(controls[15])/10) vsi = int(float(controls[16])/100) heading = int(float(controls[19])) if self.apmenu.ctrlupdate: self.apmenu.toController() if self.current['speed']!=speed: self.current['speed']=speed self.ids.label_spd.text = 'SPD:'+str(speed) if self.current['altitude']!=altitude: self.current['altitude']=altitude self.ids.label_alt.text = 'ALT:'+str(altitude)+'0' if self.current['vsi']!=vsi: self.current['vsi']=vsi self.ids.label_vsi.text = 'VSI:'+str(vsi)+'00' if self.current['heading']!=heading: self.current['heading']=heading self.ids.label_hdg.text = 'HDG:'+str(heading) if not self.grabbed.has_key('throttleleft'): throttleleft = float(controls[2]) if self.current['throttleleft']!=throttleleft: self.throttleleft.toController(throttleleft) Logger.debug("update throttleleft from FG") if not self.grabbed.has_key('throttleright'): throttleright = float(controls[3]) if self.current['throttleright']!=throttleright: self.throttleright.toController(throttleright) Logger.debug("update throttleright from FG") if not self.grabbed.has_key('flaps'): flaps = float(controls[8]) if self.current['flaps']!=flaps: self.flaps.toController(flaps) Logger.debug("update flaps from FG") if not self.grabbed.has_key('elevatortrim'): elevatortrim = float(controls[5]) if self.current['elevatortrim']!=elevatortrim: self.elevatortrim.toController(elevatortrim) Logger.debug("update elevatortrim from FG") if not self.grabbed.has_key('rudder'): rudder = round(float(controls[4]),3) if self.current['rudder']!=rudder: Logger.debug("update rudder from FG, old value %f, new value %f" %(self.current['rudder'],rudder)) self.rudder.toController(rudder) if not self.grabbed.has_key('brakes'): brakes = float(controls[6]) if self.current['brakes']!=brakes: self.brakes.toController(brakes) Logger.debug("update brakes from FG") if not self.grabbed.has_key('speedbrake'): speedbrake = float(controls[9]) if self.current['speedbrake']!=speedbrake: self.speedbrake.toController(speedbrake) Logger.debug("update brakes from FG") if not self.grabbed.has_key('reverse'): reverse = float(controls[7]) if self.ids.reverse.state != self.FGToToogleButton(reverse): self.ids.reverse.state = self.FGToToogleButton(reverse) Logger.debug("update reverse from FG") if not self.grabbed.has_key('gear'): gear = int(controls[10]) if self.current['gear']!=gear: self.gear.toController(gear) Logger.debug("update gear from FG") if not self.grabbed.has_key('parkingbrake'): parkingbrake = float(controls[11]) if self.ids.parkingbrake.state != self.FGToToogleButton(parkingbrake): self.ids.parkingbrake.state = self.FGToToogleButton(parkingbrake) Logger.debug("update parkingbrake from FG") if self.padctrl.padactive and not self.grabbed.has_key('pad'): aileron = float(controls[0]) elevator = float(controls[1]) if (self.current['aileron']!=aileron): self.current['aileron']=aileron self.padctrl.FGToControllerCoordinates(aileron,elevator) Logger.debug("update aileron from FG:"+str(aileron)) if (self.current['elevator']!=elevator): self.current['elevator']=elevator self.padctrl.FGToControllerCoordinates(aileron,elevator) Logger.debug("update elevator from FG:"+str(elevator)) if not self.grabbed.has_key('view'): view = int(controls[12]) if self.viewbuttons.current!=view: self.viewbuttons.setControllerView(view) Logger.debug("update view from FG:"+str(view)) if not self.grabbed.has_key('autobrake'): autobrake = int(controls[13]) if self.current['autobrake']!=autobrake: self.autobrake.setController(autobrake) Logger.debug("update autobrake from FG:"+str(autobrake))
def on_dismiss(self): Logger.debug("infopopup on_close") self.bindroot.infopopup = False
def probe(self): inputs = get_inputs(self.input_path) Logger.debug('ProbeSysfs: using probsysfs!') if not self.select_all: inputs = [ x for x in inputs if x.has_capability(ABS_MT_POSITION_X) ] for device in inputs: Logger.debug('ProbeSysfs: found device: %s at %s' % (device.name, device.device)) # must ignore ? if self.match: if self.use_regex: if not match(self.match, device.name, IGNORECASE): Logger.debug('ProbeSysfs: device not match the' ' rule in config, ignoring.') continue else: if self.match not in device.name: continue Logger.info('ProbeSysfs: device match: %s' % device.device) d = device.device devicename = self.device % dict(name=d.split(sep)[-1]) provider = MotionEventFactory.get(self.provider) if provider is None: Logger.info('ProbeSysfs: unable to found provider %s' % self.provider) Logger.info('ProbeSysfs: fallback on hidinput') provider = MotionEventFactory.get('hidinput') if provider is None: Logger.critical('ProbeSysfs: no input provider found' ' to handle this device !') continue instance = provider( devicename, '%s,%s' % (device.device, ','.join(self.args))) if instance: from kivy.base import EventLoop EventLoop.add_input_provider(instance)
def setFG(self,key,value): if self.checkTelnet(): Logger.debug("Arm telnet command:%s,%s"%(str(key),str(value))) self.telnetcommand.append("set %s %s \r\n" % (str(key),str(value)))
def load(self): Logger.debug('VideoGi: Load <{}>'.format(self._filename)) self._playbin.set_state(Gst.State.NULL) self._playbin.props.uri = self._get_uri() self._playbin.set_state(Gst.State.READY)
from jnius import autoclass # Set log level Config.set('kivy', 'log_level', 'debug') Config.write() # keep the screen always on try: PythonActivity = autoclass('org.renpy.android.PythonActivity') View = autoclass('android.view.View') Params = autoclass('android.view.WindowManager$LayoutParams') PythonActivity.mActivity.getWindow().addFlags(Params.FLAG_KEEP_SCREEN_ON) except: Logger.debug("jnius autoclass exception, app is not running on android") # for PC only #Window.size = (960, 540) #-------------------------------------------------------------------- # ---GLOBALS--- UPDATE_FG_RATE=20.0 #Hz Builder.load_file('APMenu.kv') Builder.load_file('ViewButtons.kv') Builder.load_file('LightsButtons.kv') Builder.load_file('Settings.kv')