def submit_score(self, name, score): if self.client and self.is_connected(): Logger.info('Google: submit score %s to %s' % (score, name)) Games.Leaderboards.submitScore(self.client, settings.GOOGLE_PLAY_LEADERBOARD_IDS[name], score) else: Logger.info("Google: score is not submitted. Client: %s, is connected: %s" % ( self.client, self.is_connected()))
def test_logger(msg, peerid=None, intermediate=False, *args): start_color = '\033[94m' end_color = '\033[0m' if peerid: Logger.info("TRIAL: {}{} {}{}".format(start_color, peerid, msg, end_color)) else: Logger.info("TRIAL: {}{}{}".format(start_color, msg, end_color))
def _build_screen(self, name): Logger.info("Root widget: building %s screen" % name) if name == 'activity': from screens.activity import activity screen = activity.ActivityScreen() self.add_widget(screen) return if name == 'tasks': from screens.tasks import tasks screen = tasks.TasksScreen() self.add_widget(screen) return if name == 'purchases': from screens.purchases import purchases screen = purchases.PurchaseScreen() self.add_widget(screen) return if name == 'tutorial': from screens.tutorial import TutorialScreen screen = TutorialScreen() self.add_widget(screen) return raise RuntimeError("Unknown screen")
def load_data(csv_path, table_name): # TODO :: Add docstring Logger.info(f"Application: Data migration for {table_name} started.") start = timer() try: with open(csv_path) as f: csv_reader = csv.reader(f, delimiter=",") for row in csv_reader: try: if table_name == "dictionary": db_helper.add_dictionary(row) elif table_name == "screens": db_helper.add_screen(row) elif table_name == "scroll_direction": db_helper.add_scroll_direction(row) else: raise ValueError(f"Invalid table name: {table_name}.") except SQLAlchemyError: Logger.error(f"Application: {traceback.format_exc()}") continue except ValueError: Logger.error(f"Application: {traceback.format_exc()}") raise except Exception: Logger.error(f"Application: {traceback.format_exc()}") raise end = timer() Logger.info( f"Application: Data migration for {table_name} " f"completed in {end-start:.2f} secs." )
def get_events(self): active_calendar_ids = self.get_active_calendars().keys() ContentUris = autoclass('android.content.ContentUris') content_builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon() dtstart = datetime.now() - timedelta(days=1) dtend = datetime.now() + timedelta(days=14) ContentUris.appendId(content_builder, int(dtstart.strftime("%s")) * 1000) ContentUris.appendId(content_builder, int(dtend.strftime("%s")) * 1000) vec = ["calendar_id", "title", "begin", "end", "allDay"] selection_clause = "(calendar_id IN (%s))" % (",".join(active_calendar_ids)) order_clause = "begin ASC" contentResolver = python_activity.getContentResolver() try: cursor = contentResolver.query(content_builder.build(), vec, selection_clause, None, order_clause) except JavaException: return [] if not cursor: return [] cursor.moveToFirst() result = [] for i in range(cursor.getCount()): begin = datetime.fromtimestamp(int(cursor.getString(2)) / 1000) end = datetime.fromtimestamp(int(cursor.getString(3)) / 1000) result.append({ "calendar_id": cursor.getString(0), "title": cursor.getString(1), "begin": begin, "end": end, "all_day": cursor.getString(4) == '1', }) cursor.moveToNext() Logger.info("Android Calendar: %s entries in calendar found" % len(result)) return result[-self.MAX_EVENTS:]
def __init__(self, *args, **kwargs): super(LoadingScreen, self).__init__(*args, **kwargs) self.bus = list() self.app = None self.size = Window.size img = Image("resources/textures/loadingScreenBackground.png").texture goOver = (Window.height * (img.width / img.height)) - Window.width with self.canvas: Rectangle(pos=(goOver / -2, 0), size=(Window.height * (img.width / img.height), Window.height), texture=img) self.label = Label(text="Loading", color=(1, 1, 1, 1), font_size=Window.height / 10, font_name="resources/ComicSans.ttf") self.label.pos_hint = {"y": -0.25} self.add_widget(self.label) Logger.info("Application: Loading Screen setup")
def press(self, selector, release=False): Logger.info("Simulation: Press %s" % selector) self.rebuild_tree() self.trigger_event('on_press', selector) if release: self.trigger_event('on_release', selector)
def __init__(self, **kwargs): super(Progression, self).__init__(**kwargs) Logger.info('Progression: Initialized {}'.format(self)) # self.sch_event = Clock.schedule_interval(self.progression_bar, 0.09) self.sch_event = Clock.schedule_interval(self.progression_bar_handler, 1 / 60)
def on_device_disconnect(self, device, error=None): if error: Logger.error("BLE: device disconnected: {}".format(error)) else: Logger.info("BLE: device disconnected") self.connected = None self.ble_should_scan = True
def writable(fname): try: touch(fname) except (OSError, IOError) as ex: Logger.info("OS: %s is not writable: %s" % (fname, unicode(ex))) return False return True
def __init__(self, **kwargs): super(MainViewScManager, self).__init__(**kwargs) Logger.info('MainViewScManager: Initialized {}'.format(self)) self.add_widget(SearchView()) self.add_widget(LatestView()) self.add_widget(MoviesView()) self.add_widget(SeriesView())
def vibrate(self, length): if not self.turned_on(): Logger.error( "Android Vibration: won't vibrate, turned off in settings...") return Logger.info("Vibrator: vibrate %s milliseconds...", length)
def print_all(self): s = (datetime.now() - self.start).total_seconds() message = "" for label in self.times: message += "%s: %s, %.2f%%\n" % (label, self.times[label], 100. * self.times[label] / s) Logger.info("Profiling: summary:\n%s" % message)
def start_server(self, *args): import server.flaskserver as flaskserver global server_thread quality = self.quality() if not self.ids.stop_btn.disabled: # 品質のみの再起動の場合は、品質のみ変えるように。 if flaskserver.port == int(self.ids.port_text.text): if flaskserver.get_quality == quality: Logger.info("shutdown server now") flaskserver.shutdown_server() time.sleep(.5) Logger.info("=====SHUTDOWN MAYBE COMPLETE=====") else: flaskserver.set_quality(quality) return False if not self.check_port(): self.ids.start_btn.disabled = False return False flaskserver.quality = quality flaskserver.port = int(self.ids.port_text.text) server_thread = threading.Thread(target=flaskserver.startServer) server_thread.start() self.ids.stop_btn.disabled = False self.ids.start_btn.disabled = False self.ids.start_btn.text = "再起動"
def init_nfc(self): # http://code.tutsplus.com /tutorials/reading-nfc-tags-with-android--mobile-17278 activity = PythonActivity.mActivity self.nfc_adapter = NfcAdapter.getDefaultAdapter(activity) if not self.nfc_adapter: Toast.makeText(activity, "This device doesn't support NFC.", Toast.LENGTH_LONG).show() activity.finish() if not self.nfc_adapter.isEnabled(): self.nfc_status.text = "NFC not enabled" else: self.nfc_status.text = "NFC waiting for a touch" # https://github.com/nadam/nfc-reader/blob/master/src/se/anyro/nfc_reader/TagViewer.java#L75 nfc_present_intent = Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) # http://cheparev.com/kivy-receipt-notifications-and-service/ pending_intent = PendingIntent.getActivity(activity, 0, nfc_present_intent, 0) # http://developer.android.com/reference/android/nfc/NfcAdapter.html#enableForegroundDispatch%28android.app.Activity,%20android.app.PendingIntent,%20android.content.IntentFilter[],%20java.lang.String[][]%29 self.nfc_adapter.enableForegroundDispatch(activity, pending_intent, None, None) # We get the following in adb logs and on_activity_result doesn't seem to work # W ActivityManager: startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.nfc.action.TAG_DISCOVERED flg=0x20000000 cmp=com.opensourcehacker.webkivy/org.renpy.android.PythonActivity (has extras) } # android.activity.bind(on_activity_result=self.on_activity_result) # https://github.com/kivy/python-for-android/blob/master/pythonforandroid/recipes/android/src/android/activity.py android.activity.bind(on_new_intent=self.on_new_intent) Logger.info("NFC ready")
def on_connection_established(self, characteristic, error): if error: Logger.error("BLE: connection failed: {}".format(error)) self.on_device_disconnect(None) return Logger.info("BLE: connection established {}".format(repr(characteristic.value))) self.start_data()
def __init__(self): # Check and see if constants rebinding is unsuccessful try: constants.REBIND_CHECK = False except const.ConstError: Logger.info("ENV: Environment constants are secure.") else: raise Exception("Error with environment setup.") # Environment self.env_dict = {} # Create cache Cache.register(category='envcache', limit=2) # Populate constants for attr in dir(constants): if attr.isupper(): self.env_dict[attr] = str( getattr(constants, attr) ).encode('string_escape') # Initiate memory tracker if constants.PYMPLER_AVAILABLE: self.mem_tracker = tracker.SummaryTracker()
def post_enter(self): Logger.info("Application: IntroShip Screen entered") self.starClock = Clock.schedule_interval(self.draw_star, self.Globals.GameSettings.intro_ship_star_new_frame_delay) self.shipClock = Clock.schedule_interval(self.draw_ship, self.Globals.GameSettings.intro_ship_ship_new_frame_delay) self.meteorClock = Clock.schedule_once(self.move_meteor, self.Globals.GameSettings.intro_ship_meteor_delay) self.meteorClock2 = Clock.schedule_interval(self.draw_meteor, 0) self.meteorHitSoundClock = Clock.schedule_once(lambda x: self.Globals.Audio.meteorHit.play(), self.Globals.GameSettings.intro_ship_meteor_hit_sound_delay) self.tintClock = Clock.schedule_once(self.start_alarm, self.Globals.GameSettings.intro_ship_alarm_delay) self.alarmSoundClock = Clock.schedule_once(lambda x: self.alarmSoundClock2.cancel(), self.Globals.GameSettings.intro_ship_alarm_sound_stop_delay) self.alarmSoundClock = Clock.schedule_once(self.start_alarm_sounds, self.Globals.GameSettings.intro_ship_alarm_sound_delay) self.shipShakeClock = Clock.schedule_once(self.shake, self.Globals.GameSettings.intro_ship_ship_shake_delay) self.shipFallClock = Clock.schedule_once(self.move, self.Globals.GameSettings.intro_ship_ship_fall_delay) self.shipFallSoundClock = Clock.schedule_once(lambda x: self.Globals.Audio.shipFall.play(), self.Globals.GameSettings.intro_ship_ship_fall_sound_delay) self.endClock = Clock.schedule_once(lambda x: self.Globals.get_screen_manager().sendTo("IntroCrashScreen"), self.Globals.GameSettings.intro_ship_end_delay) Logger.info("Application: IntroShip Ship Screen clocks created")
def mabyDoPasswordAndLogins(self, screen): if Config.getboolean("Misc", "saveLogins"): screen.ids["UsrNameInput"].text = Config.get("Misc", "username") screen.ids["PwdInput"].text = decode( str(Config.get("Misc", "password")), "JonIsGreen") Logger.info("Logins: Loaded")
def connect(self): self.path = self.get_database_path() import sqlite3 self._connection = sqlite3.connect(self.path, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES, timeout=1) self._connection.row_factory = sqlite3.Row cursor = self._connection.cursor() create_tables_query = ''' CREATE TABLE IF NOT EXISTS steps ( id INTEGER NOT NULL, "key" VARCHAR NOT NULL, families VARCHAR NOT NULL, duration FLOAT, efficiency FLOAT NOT NULL, weekday INTEGER NOT NULL, hour INTEGER NOT NULL, created DATETIME NOT NULL, PRIMARY KEY (id) ) ''' cursor.execute(create_tables_query) self._connection.commit() if not os.path.exists(self.path): Logger.info("Database: create database on %s" % self.path) else: Logger.info("Database: found database at %s" % self.path) cursor.close()
def update_entries(self): from kivy.animation import Animation from datetime import datetime from utils import _ billing = App.get_running_app().billing purchased_items = billing.get_purchased_items() if not settings.INAPP_PURCHASES: is_premium = True else: is_premium = 'lifetime_premium' in purchased_items or 'premium_subscription' in purchased_items for entry in self.entries: entry.family = self.family try: if not entry.all_day: efficiency = self.data['hours'][entry.begin.hour] * .5 efficiency += self.data['days'][entry.begin.weekday()] * .5 else: efficiency = self.data['days'][entry.begin.weekday()] except KeyError: Logger.info("Calendar: key error in efficiency, set to 1...") efficiency = 2. if not is_premium and entry.begin > datetime.now(): entry.efficiency_bar.label.text = _("GET PREMIUM") entry.efficiency_bar.on_press = lambda *args: billing.buy('lifetime_premium', callbacks=[self.update]) entry.efficiency = 2. else: entry.efficiency_bar.on_press = lambda *args: None Animation(efficiency=efficiency, d=.5, t='in_out_cubic').start(entry) entry.efficiency_bar.label.text = "%.0f%%" % (efficiency * 100)
def guide_move(self, _=None): Logger.info("Application: IntroCrash Screen guide move started") animation = Animation(pos=self.guideLayout1.pos, duration=0) animation += Animation(pos=(0, 0), duration=self.Globals.GameSettings.intro_crash_guide_speed) animation.start(self.guideLayout1)
def post_enter(self): Logger.info("Application: IntroCrash Screen entered") self.canyonClock = Clock.schedule_once(self.move_canyon, self.Globals.GameSettings.intro_crash_move_delay) self.starClock = Clock.schedule_once(self.move_stars, self.Globals.GameSettings.intro_crash_move_delay) self.drawClock = Clock.schedule_interval(self.draw, 0) self.guideClock = Clock.schedule_once(self.guide_move, self.Globals.GameSettings.intro_crash_guide_delay) self.click1Clock = Clock.schedule_once(self.click1allow, self.Globals.GameSettings.intro_crash_click_1_delay)
def move_canyon(self, _=None): Logger.info("Application: IntroCrash Screen canyon move started") animation = Animation(pos=self.canyonLayout.pos, duration=0) animation += Animation(pos=((self.w * -1) + self.Globals.width, self.canyonLayout.pos[1]), duration=self.Globals.GameSettings.intro_crash_move_length) animation.start(self.canyonLayout)
def start(self, *args, **kwargs): App.get_running_app().sounds['start'].play() self.intro_hint.tutorial.stop() self.main_area.remove_widget(self.intro_hint) self.intro_hint = None self.add_main_widgets() Clock.schedule_interval(self._calculate_seconds_to_success, 1. / 2) Logger.info("Start class %s started..." % self.__class__)
def __init__(self, **kwargs): super(LatestView, self).__init__(**kwargs) Logger.info('LatestView: Initialized {}'.format(self)) # print(self.ids) Clock.schedule_once(self.pr, 9) self.connn = Connector()
def add_content(self, *args, **kwargs): if self.container.parent != self: App.get_running_app().tracker.send_event('clicks', 'menu', 'purchase') Logger.info("Purchases: container initialization finished") self.loading.hide(self._container) else: self.container.start()
def onConnected(self, connectionHint): Logger.info("Google: successfully logged in") Games.setViewForPopups(self.client, PythonActivity.mActivity.getWindow().getDecorView().findViewById(Rid.content)) Logger.info("Google: set view for popup") if self.on_connected_callback: self.on_connected_callback()
def is_connected(self): super(AndroidGoogleClient, self).is_connected() if self.client: is_connected = self.client.isConnected() Logger.info('Google: is connected %s' % is_connected) return is_connected else: return False
def add_save_paths(app): Globals = get_Globals() Globals.User_data.save_path = str( os.path.join(str(app.user_data_dir), "user_data.json")) Globals.Settings_data.save_path = str( os.path.join(str(app.user_data_dir), "settings_data.json")) Logger.info("Loader: Added save paths")
def create_Globals(app): init() Globals = get_Globals() Globals.width = Window.width Globals.height = Window.height Globals.app = app Logger.info("Loader: Created Globals")
def import_kv(path): import os base_path = os.path.dirname(os.path.abspath(__file__)) kv_path = os.path.relpath(path, base_path).rsplit(".", 1)[0] + ".kv" kv_path = os.path.join('kv', kv_path) if kv_path not in Builder.files: Builder.load_file(kv_path, rulesonly=True) Logger.info("KV: load %s, overall: %s" % (kv_path, len(Builder.files)))
def __init__(self, sname, **kwargs): super(Item, self).__init__(**kwargs) Logger.info('Item: Initialized {}'.format(self)) self.megs = sname print(self.megs) self.popup = Popup(title='Test popup', content=Label(text=self.megs), size_hint=(None, None), size=(600, 600))
def billing_callback(self, purchase, *largs): if not purchase: return Logger.info("Billing: callback, sku: %s, largs: %s" % (purchase['productId'], largs)) if self.callbacks: for callback in self.callbacks: callback(purchase, *largs)
def vibrate_cb(self, time=1): try: vibrator.vibrate(time) except (NotImplementedError, ImportError): Logger.warn( "DEVICE: No vibrate function defined for {} platform.".format( constants.PLATFORM)) else: Logger.info("DEVICE: BUZZ!!")
def start_advertising(self): Logger.info("BLE: start advertising") service = ble_peripheral.Service(self.beacon_uuid) # char = ble_peripheral.Characteristic(uuid4(), # value=b'1', permissions=ble_peripheral.Characteristic.permission.readable, # properties=ble_peripheral.Characteristic.property.read) ble_peripheral.add_service(service) ble_peripheral.start_advertising("SmartModule Demo") self.ble_advertising = True self.ble_should_scan = True
def play(self, *args): if not self._loaded_stream: self.select_stream(self.current_stream) try: self._loaded_stream.play() Logger.info("Radio: playing %s" % self.stream_list[0]) self.is_playing = True self.play_status = 'Radio: Pornit' except Exception as e: self.play_status = 'Radio: Eroare' Logger.error('Radio: Failed to play stream: {}'.format(e.message))
def central_discovered_peripheral(self, device): if self.connecting or self.connected: return print("discovered peripheral, state", iprop(device.peripheral.state)) uuid_bytes = self.client_base_uuid_bytes for uuid, service in device.services.items(): if uuid.bytes[4:] == uuid_bytes: Logger.info("BLE: found device {}".format(uuid)) self.ble_should_scan = False self.stop_scanning() self.connect_uuid = uuid self.connect(device) return
def on_discover_services(self, services, error): if error: Logger.error("BLE: error discovering services: {}".format(error)) return Logger.info("BLE: discovered services: {}".format(services.keys())) service = services[self.connect_uuid] if not service: Logger.error("BLE: service not found!") return service.discover_characteristics(on_discover=self.on_discover_characteristics)
def dump_config(self): # Start config parser config = ConfigParser.SafeConfigParser() # Set env constants into section config.add_section('Environment') for (k, v) in self.env_dict.iteritems(): if '%' not in v: print k config.set('Environment', k, v.encode('string_escape')) # Writing our configuration file to 'defaults.cfg' with open('{}/core/env/defaults.cfg'.format(constants.PROJECT_PATH), 'wb') as configfile: config.write(configfile) Logger.info("ENV: Dumped environment to config file.")
def on_device_connect(self, device, error=None): self.connecting = None if error: Logger.error("BLE: failed to connect to device: {}".format(error)) self.ble_should_scan = True return Logger.info("BLE: connected to device {}".format(device)) self.connected = device # device.discover_services(uuids=(self.connect_uuid,), on_discover=self.on_discover_services) service = device.services[self.connect_uuid] if service: Logger.info("BLE: found service {}".format(service)) self.on_discover_services(device.services, None) else: device.discover_services(on_discover=self.on_discover_services)
def memory_summary(self, summarize=True): "Using pympler summarize module to view memory summary." if summarize: all_objects = muppy.get_objects() Logger.info("ENV: \nMemory Footprint:") Logger.info("-----------------") return summary.print_(summary.summarize(all_objects), limit=50) else: Logger.info("ENV: \nMemory Tracker:") Logger.info("---------------") self.mem_tracker.print_diff()
def on_start(self): """Event handler for the on_start event, which is fired after initialization (after build() has been called), and before the application is being run. """ Logger.info("TESTSERVER: Cryptikchaos Test server started.") # Initiate Twisted Server self.comm_service = CommService( peerid=constants.LOCAL_TEST_PEER_ID, host=constants.LOCAL_TEST_HOST, port=constants.LOCAL_TEST_PORT, clientinit=False, printer=self.print_message, ) self.device_service = DeviceService() # Register device service with comm service self.comm_service.register_device_service(self.device_service)
def list_constants(self, shorten=True, show_indx=False): "List all env constants." consts = Cache.get(category='envcache', key='constants') if not consts: Logger.info("ENV: Building env constants list.") consts = [] i = 1 for k in sorted(self.env_dict.keys()): v = self.env_dict[k].strip() row = [] if show_indx: if shorten and len(v[:50]) > 50: row = (i, k,v[:50]) else: row = (k, v) consts.append(row) i += 1 # Cache constants Logger.info("ENV: Caching constants.") Cache.append(category='envcache', key='constants', obj=consts) else: Logger.info("ENV: Retrieved constants from cache.") return consts
def __init__(self, **kwargs): super(HeatMap, self).__init__(**kwargs) self.appname = sys.argv[0] if self.appname == '': self.appname = 'python' elif self.appname[-3:] == '.py': self.appname = self.appname[:-3] self.filename = fn = 'heatmap-%s.db' % self.appname self.db = sqlite3.connect(self.filename) try: self.db.execute(''' CREATE TABLE heatmap ( x NUMERIC, y NUMERIC, time NUMERIC ) ''') self.db.commit() msg = 'Heatmap: Create new database for heatmap in %s' % fn Logger.info(msg) except sqlite3.OperationalError: Logger.info('Heatmap: Fill heatmap database in %s' % fn)
def read_credit_card_file(self, iso, resp): """Read credit card data fiel off the the card.""" # http://stackoverflow.com/questions/23107685/reading-public-data-of-emv-card/23113332#23113332 text = "" # 00 B2 01 0C 00 # B2 read record # 01 record number # 0C short fille identified (record number) shifted 4 bits left - http://www.openscdp.org/scripts/tutorial/emv/reademv.html # 00 max length apdu_cmd = [00, 0xB2, 0x01, 0x0C, 00] apdu_cmd_hex = [hex(c) for c in apdu_cmd] Logger.info("Sending read record command %s", apdu_cmd_hex) resp = iso.transceive(apdu_cmd) Logger.info("Received APDU response: %s", byte_array_to_hex(resp)) bs = byte_array_to_byte_string(resp) return bs.decode("utf-8", "ignore")
def mapped_widgets(self, mapping): Logger.info("matching emitters: %s" % mapping) result = set() for source in mapping.sources: filtered_emitters = set(self.grid.values()) for k, v in source.items(): if k == "class": for emitter in list(filtered_emitters): if emitter.__class__.__name__ != v: filtered_emitters.remove(emitter) elif k == "controls": for emitter in list(filtered_emitters): for field_k, field_v in source["controls"].items(): emitter_v = getattr(emitter, field_k, None) if emitter_v != field_v and emitter_v != None: filtered_emitters.remove(emitter) result.update(filtered_emitters) Logger.info("result: %s" % list(result)) return result
def on_discover_characteristics(self, characteristics, error): if error: Logger.error("BLE: error discovering characteristics: {}".format(error)) return # Logger.info('BLE: discovered characteristics: {}'.format(characteristics.keys())) for uuid, char in characteristics.items(): Logger.info("BLE: discovered characteristic: {} {:02x}".format(uuid, char.properties)) if uuid == self.connection_uuid: Logger.info("BLE: found connection characteristic") char.read(on_read=self.on_connection_established) elif uuid == self.module_message_uuid: Logger.info("BLE: found module message characteristic") self.module_message_characteristic = char
def run_kivy_app(cls): app = cls() try: Logger.info("UTILITIES: Opening {} Kivy Application.".format(type(app).__name__)) # Start App mainloop app.run() except KeyboardInterrupt: Logger.info("UTILITIES: Recieved Keyboard interrupt. [CTRL+C]") else: Logger.info("UTILITIES: Closed {} Kivy Application.".format(type(app).__name__)) finally: # Stop services app.on_stop()
def on_stop(self): """Event handler for the on_stop event, which is fired when the application has finished running (e.g. the window is about to be closed). """ Logger.info("TESTSERVER: Closing services.") # Close services try: self.comm_service.__del__() except AttributeError: pass Logger.info("TESTSERVER: Successfully closed services.") Logger.info("TESTSERVER: Closing Cryptikchaos Test Server.")
def display_table(self, show_indx=False): """ View Application environment constants. (useful for realtime debugging) Usage: env """ table = Cache.get(category='envcache', key='table') if not table: Logger.info("ENV: Generating environment table.") constants = self.list_constants(show_indx=show_indx) if constants: if show_indx: table = restTable(["S.NO", "CONSTANT", "VALUE"]) else: table = restTable(["CONSTANT", "VALUE"]) for c in constants: table.add_row(c) else: return "No environment variables defined." # Cache table for next run Logger.info("ENV: Caching table.") Cache.append(category='envcache', key='table', obj=table) else: Logger.info("ENV: Retrieving cached table.") return """ Environment Constants:\n To see value use: 'eko <constant name>'\n \n{} """.format(table)
def pack_stream(self, stream_type, stream_content, stream_host, stream_flag=STREAM_TYPES.AUTH, shared_key=None): "Pack data into stream." # Check length of content. if len(stream_content) > constants.STREAM_CONTENT_LEN: raise StreamOverflowError(constants.STREAM_CONTENT_LEN) # Check length of capsule type. if len(stream_type) > constants.STREAM_TYPE_LEN: raise StreamOverflowError(constants.STREAM_TYPE_LEN) # Generate uid stream_uid = generate_uuid(stream_host) # Stream type stream_type = stream_type.upper() # Stream peer key stream_token = None #For testing _debug_stream_content = stream_content # Shuffle content if constants.ENABLE_SHUFFLE: Logger.info("STREAM: Scrambling content...") stream_content = shuffler( string=stream_content, iterations=constants.STREAM_CONT_SHUFF_ITER ) # Check stream signing mode if stream_flag == STREAM_TYPES.UNAUTH: # Stream key is peer key # NOTE peer public key is sent during # authentication. stream_token = num_to_bytes(self.public_key) elif stream_flag == STREAM_TYPES.AUTH: # Generate token at source side stream_token = generate_token(stream_uid, shared_key) # AES Encryption if constants.AES_AVAILABLE: Logger.info("STREAM: Encrypting content...") # Generate iv from stream token iv = md5hash(stream_token, hexdigest=False) # Create AES object AES_obj = AES.new(shared_key, AES.MODE_CBC, iv) # Pad string stream_content = self.pad(stream_content) # Encrypt string stream_content = AES_obj.encrypt(stream_content) # Create stream object stream_obj = Stream( stream_uid, stream_flag, stream_type, stream_content, stream_token, ) # Add stream to store self.add_store( stream_uid, stream_obj.dict ) if stream_flag == STREAM_TYPES.UNAUTH: Logger.info("STREAM: Packing Authentication Stream...") # Pack store into authentication stream stream = struct.pack( "!?{}s{}s{}s{}s".format( constants.STREAM_TYPE_LEN, constants.STREAM_CONTENT_LEN, constants.STREAM_PEER_KEY_LEN, constants.STREAM_CHKSUM_LEN ), self.get_store_item(stream_uid, 'STREAM_FLAG'), self.get_store_item(stream_uid, 'STREAM_TYPE'), self.get_store_item(stream_uid, 'STREAM_CONTENT'), self.get_store_item(stream_uid, 'STREAM_PKEY'), self.get_store_hmac(stream_uid) ) elif stream_flag == STREAM_TYPES.AUTH: Logger.info("STREAM: Packing Message Stream...") # Pack store into message block stream stream = struct.pack( "!?{}s{}s{}s{}s".format( constants.STREAM_TYPE_LEN, constants.STREAM_CONTENT_LEN, constants.STREAM_TOKEN_LEN, constants.STREAM_CHKSUM_LEN ), self.get_store_item(stream_uid, 'STREAM_FLAG'), self.get_store_item(stream_uid, 'STREAM_TYPE'), self.get_store_item(stream_uid, 'STREAM_CONTENT'), self.get_store_item(stream_uid, 'STREAM_PKEY'), self.get_store_hmac(stream_uid) ) else: Logger.error("STREAM: Invalid Stream Flag received.") return None def pkey_action(val): val = md5hash(val) return val if stream_flag == STREAM_TYPES.UNAUTH: Logger.debug("""STREAM: Packing: \n{}""".format( self.storage_table(shorten_len=64, action_dict={"STREAM_PKEY":pkey_action}) )) Logger.debug("""DEBUG STREAM: FLAG: {} TYPE: {} CONTENT: {} KEY: {} CHECKSUM: {} """.format( self.get_store_item(stream_uid, 'STREAM_FLAG'), self.get_store_item(stream_uid, 'STREAM_TYPE'), _debug_stream_content, b64encode(self.get_store_item(stream_uid, 'STREAM_PKEY')), self.get_store_hmac(stream_uid))) # Compress stream if constants.ENABLE_COMPRESSION: Logger.info("STREAM: Compressing Stream...") stream = compress(stream) Logger.info("STREAM: Succesfully packed stream.") return stream
def unpack_stream(self, stream, shared_key=None): "Unpack serial data into stream." # Decompress data stream if constants.ENABLE_COMPRESSION: Logger.info("STREAM: Decompressing Stream...") stream = decompress(stream) # Check if data is of expected chunk size if len(stream) != constants.STREAM_SIZE_AUTH_BLOCK and \ len(stream) != constants.STREAM_SIZE_MSG_BLOCK: raise StreamOverflowError() if len(stream) == constants.STREAM_SIZE_AUTH_BLOCK: Logger.info("STREAM: Unpacking Authentication Stream...") # Unpack auth stream to variables ( stream_flag, stream_type, stream_content, stream_token, stream_hmac ) = struct.unpack( "!?{}s{}s{}s{}s".format( constants.STREAM_TYPE_LEN, constants.STREAM_CONTENT_LEN, constants.STREAM_PEER_KEY_LEN, constants.STREAM_CHKSUM_LEN ), stream ) elif len(stream) == constants.STREAM_SIZE_MSG_BLOCK: Logger.info("STREAM: Unpacking Message Stream...") # Unpack msg block stream to variables ( stream_flag, stream_type, stream_content, stream_token, stream_hmac ) = struct.unpack( "!?{}s{}s{}s{}s".format( constants.STREAM_TYPE_LEN, constants.STREAM_CONTENT_LEN, constants.STREAM_TOKEN_LEN, constants.STREAM_CHKSUM_LEN ), stream ) else: Logger.error("STREAM: Invalid Stream Length received.") return [None] * 3 # Remove all null characters if present stream_content = stream_content.rstrip('\0') stream_token = stream_token.rstrip('\0') # Get uid stream_uid = generate_uuid(self.peer_host) # Get stream object stream_obj = Stream( stream_uid, stream_flag, stream_type, stream_content, stream_token, ) # Add stream to store self.add_store(stream_uid, stream_obj.dict) # Verify stream integrity if not self.check_hmac(stream_uid, stream_hmac): Logger.error("STREAM: Stream Checksum mismatch.") return [None] * 3 # Check stream signing mode if stream_flag == STREAM_TYPES.UNAUTH: # Stream key is peer public key pass elif stream_flag == STREAM_TYPES.AUTH: # Generate token at destination side # Perform key challenge if generate_token(stream_uid, shared_key) != stream_token: Logger.error("STREAM: Token challenge Fail!") Logger.error("STREAM: RCVD: {}".format(b64encode(stream_token))) Logger.error("STREAM: EXPD: {}".format(b64encode(generate_token(stream_uid, shared_key)))) return [None] * 3 else: Logger.info("STREAM: Token challenge Pass!") # AES Decryption if constants.AES_AVAILABLE: Logger.info("STREAM: Decrypting content...") # Generate iv from stream token iv = md5hash(stream_token, hexdigest=False) # Create AES object AES_obj = AES.new(shared_key, AES.MODE_CBC, iv) # Decrypt content stream_content = AES_obj.decrypt(stream_content) # Upad decrypted content stream_content = self.unpad(stream_content) def pkey_action(val): val = md5hash(val) return val if stream_flag == STREAM_TYPES.UNAUTH: Logger.debug("""STREAM: Unpacking: \n{}""".format( self.storage_table(shorten_len=64, action_dict={"STREAM_PKEY":pkey_action}) )) Logger.debug("""DEBUG STREAM: FLAG: {} TYPE: {} CONTENT: {} KEY: {} CHECKSUM: {} """.format( self.get_store_item(stream_uid, 'STREAM_FLAG'), self.get_store_item(stream_uid, 'STREAM_TYPE'), stream_content, b64encode(self.get_store_item(stream_uid, 'STREAM_PKEY')), self.get_store_hmac(stream_uid))) # Unshuffle contentself._storage[sid].hmac() if constants.ENABLE_SHUFFLE: Logger.info("STREAM: Unscrambling content...") stream_content = unshuffler( shuffled_string=stream_content, iterations=constants.STREAM_CONT_SHUFF_ITER ) if stream_flag == STREAM_TYPES.UNAUTH: Logger.info("STREAM: Successfully unpacked AUTH Stream.") return (self.get_store_item(stream_uid, "STREAM_TYPE"), self.get_store_item(stream_uid, "STREAM_CONTENT"), bytes_to_num( self.get_store_item(stream_uid, "STREAM_PKEY") )) elif stream_flag == STREAM_TYPES.AUTH: Logger.info("STREAM: Successfully unpacked MSG Stream.") return (self.get_store_item(stream_uid, "STREAM_TYPE"), stream_content, self.get_store_item(stream_uid, "STREAM_PKEY")) else: Logger.info("STREAM: Unpack of stream unsuccessfull.") return [None] * 3
from cryptikchaos.libs.utilities import decompress from cryptikchaos.libs.utilities import enum from cryptikchaos.libs.utilities import num_to_bytes from cryptikchaos.libs.utilities import bytes_to_num from cryptikchaos.libs.utilities import md5hash from cryptikchaos.libs.obscure import shuffler from cryptikchaos.libs.obscure import unshuffler from cryptikchaos.exceptions.streamExceptions import \ StreamOverflowError from cryptikchaos.core.comm.stream.stream import Stream if constants.AES_AVAILABLE: Logger.info("STREAM: AES Crypto available.") from Crypto.Cipher import AES else: Logger.warn("STREAM: AES Crypto unavailable.") import struct STREAM_TYPES = enum(UNAUTH=False, AUTH=True) class StreamManager(StoreManager): "Stream manager class." def __init__(self, peerid, peerkey, peerhost):
def update(self, topic, payload): Logger.info("main: update for %s" % topic) payload = json.loads(payload) device_id = payload['deviceId'] readings = payload['readings'] self.devices[device_id].update(readings)
_clipboards.append( ('xsel', 'clipboard_xsel', 'ClipboardXsel')) if USE_SDL2: _clipboards.append( ('sdl2', 'clipboard_sdl2', 'ClipboardSDL2')) else: _clipboards.append( ('pygame', 'clipboard_pygame', 'ClipboardPygame')) _clipboards.append( ('dummy', 'clipboard_dummy', 'ClipboardDummy')) Clipboard = core_select_lib('clipboard', _clipboards, True) CutBuffer = None if platform == 'linux': _cutbuffers = [ ('xclip', 'clipboard_xclip', 'ClipboardXclip'), ('xsel', 'clipboard_xsel', 'ClipboardXsel'), ] if Clipboard.__class__.__name__ in (c[2] for c in _cutbuffers): CutBuffer = Clipboard else: CutBuffer = core_select_lib('cutbuffer', _cutbuffers, True, basemodule='clipboard') if CutBuffer: Logger.info('CutBuffer: cut buffer support enabled')
if logTimeSinceLastCheckedModification > 0: logtext = open(self.logFileName).read() logtext = stringReplace(logtext, '\r\n', '\r\n ') logtext = '::\r\n\r\n ' + logtext + '\r\n' self.title = self.logFileName.rpartition('/')[2] self.text = logtext Clock.schedule_once(self.gotoEnd, 0.3) Clock.schedule_once(self.onLoggerCheck, 1) # had a recent change so check aggresively else: Clock.schedule_once(self.onLoggerCheck, min(15, 16)) def gotoEnd(self, dt=None): self.scroll_y = 0 from kivy.app import App class LoggerWidgetTestApp(App): def build(self): loggerWidget = LoggerWidget() return loggerWidget # self run, self test if __name__ == "__main__": Logger.info(__file__ + ': running from __name__') eyeTrackerTestApp = LoggerWidgetTestApp() eyeTrackerTestApp.run()
def notify_cb(self, title='', message='', timeout=1): try: notification.notify( title=title, message=message, app_name=constants.APP_NAME, app_icon=os.path.join(constants.KIVY_RESOURCE_PATH_1, 'icon.png'), timeout=timeout ) except (NotImplementedError, ImportError): Logger.warn( "DEVICE: No vibrate function defined for {} platform.".format( constants.PLATFORM)) else: Logger.info("DEVICE: Fired Notification!")