Exemple #1
0
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 _start_app_as_slave(self):
        # from app::run
        if not self.mc.built:
            self.mc.load_config()
            self.mc.load_kv(filename=self.mc.kv_file)
            root = self.mc.build()
            if root:
                self.mc.root = root
        if self.mc.root:
            if not isinstance(self.mc.root, KivyWidget):
                Logger.critical('App.root must be an _instance_ of Kivy Widget')
                raise Exception('Invalid instance in App.root')
            from kivy.core.window import Window
            Window.add_widget(self.mc.root)

        # Check if the window is already created
        from kivy.base import EventLoop
        window = EventLoop.window
        if window:
            self.mc._app_window = window
            window.set_title(self.mc.get_application_name())
            icon = self.mc.get_application_icon()
            if icon:
                window.set_icon(icon)
            self.mc._install_settings_keys(window)
        else:
            Logger.critical("Application: No window is created."
                            " Terminating application run.")
            return

        self.mc.dispatch('on_start')
        runTouchApp(slave=True)  # change is here

        while not self.mc.is_init_done.is_set():
            EventLoop.idle()
    def add_picture_to_scroller(self, instance, widget):
		
        if self.parent is not None:
            self.parent.remove_widget(widget)

        item = widget

        # adjust the size of the image to allow for the borderimage background to be shown
        # fudge the borderimage into the equation (hard because it is drawn outside of the image,
        # and thus does not come into the calculations for the scrollview, which means
        # we need to manually fix up the left/right/top/bottom cases, for this to show
        # properly on the screen
        # 36 happens to the be border image size numbers we are using in the .kv file
        item.image.size = item.image.image_ratio*(self.scrollview_height-36), self.scrollview_height-36
        item.size = item.image.size[0]+36, item.image.size[1]+18
        item.size_hint_x = None

        # the scroller, effects size, and not the scale of the container, so we must adjust for this,
        # else the object will be in the container with its current transforms, which would look weird
        item.scale = 1
        item.rotation = 0

        try:
            self.items.add_widget(widget)
        except:
            Logger.debug("Vertical Scroller: (picture) timing issue, means user touched this object, so now it has a parent, when it shouldn't, so don't add to the scroller afterall")
Exemple #4
0
 def show_image(self, path):
     try:
         firefox = webbrowser.get('firefox')
         firefox.open(path)
     except Exception:
         Logger.exception(
             'Calibration: Unable to open image "{}"'.format(path))
    def nfc_card_presented(self, uid: str):
        Logger.debug("StellaPayUI: Read NFC card with uid" + uid)

        # If we are currently making a transaction, ignore the card reading.
        if App.get_running_app().active_user is not None:
            Logger.debug("StellaPayUI: Ignoring NFC card as we are currently making a transaction.")
            return

        # Show the spinner
        self.ids.spinner.active = True

        # Request user info for the specific UID to validate person
        response = App.get_running_app().session_manager.do_get_request(url=Connections.request_user_info() + uid)

        # Check response code to validate whether this user existed already. If so, proceed
        # to the productScreen, else proceed to the registerUID screen
        if response and response.ok:
            # store result in JSON
            query_json = response.json()

            # Move to WelcomeScreen
            self.manager.transition = SlideTransition(direction='left')

            # store user-mail for payment confirmation later
            user_mail = query_json["owner"]["email"]
            user_name = query_json["owner"]["name"]

            App.get_running_app().active_user = user_name

            # Go to the product screen
            self.manager.current = Screens.PRODUCT_SCREEN.value
        else:
            # User was not found, proceed to registerUID file
            self.manager.get_screen(Screens.REGISTER_UID_SCREEN.value).nfc_id = uid
            self.manager.current = Screens.REGISTER_UID_SCREEN.value
Exemple #6
0
 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)
Exemple #7
0
    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 on_fanState(self, instance, value):
     #TODO 3 send turn on/off fans to serial port
     Logger.exception(self.__class__.__name__ + ': in [' + whoAmI() + '] fanState is ' + str(self.fanState) + ' but NOT IMPLEMENTED YET')
     popup = Popup(title='fanState Not implemented yet',
                   content=Label(text='fanState Not implemented yet'),
                   size_hint=(0.4, 0.2) )
     popup.open()
    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")
Exemple #10
0
    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)
Exemple #11
0
    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 webpage_image_updater(self):
            while True:
                if self.do_webpage_image_update:
                    t = time.time()

                    Logger.debug("WebpageImage: Starting image update")

                    data = io.BytesIO(self.driver.get_screenshot_as_png())

                    coreImage = CoreImage(data, ext="png")
                    Clock.schedule_once(
                        lambda _: self.Gui.update_webpage_image(coreImage, t),
                        0)

                    try:
                        time.sleep(self.webpage_image_update_interval -
                                   (time.time() - t))
                    except ValueError:
                        Logger.warning(
                            "WebpageImage: Convert took to long, took " +
                            str(time.time() - t) + " and it should've took " +
                            str(self.webpage_image_update_interval))

                else:
                    time.sleep(self.webpage_image_update_interval)
    def update_webpage_image(self, coreImage, t):
        texture = coreImage.texture
        self.ids["WebpageImage"].texture = texture
        self.ids["WebpageImageLarge"].texture = texture

        Logger.debug("WebpageImage: Finished image update in " +
                     str(time.time() - t))
Exemple #14
0
    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 GetIPAddressV6() -> str:

    uPreferredAdapter: str = u'eth0'
    uInet_Type: str = u'AF_INET6'
    uRet: str = u'127.0.0.0'
    aFound: List[str] = []
    iInet_num: int

    try:
        iInet_num = getattr(netifaces, uInet_Type)
        aInterfaces: List = netifaces.interfaces()

        for uNetiface in aInterfaces:
            dNetInfo: Dict = netifaces.ifaddresses(uNetiface)
            aNetDetails: List = dNetInfo.get(iInet_num)
            if aNetDetails is not None and len(aNetDetails) > 0:
                dNetDetails: Dict = aNetDetails[0]
                uIP = dNetDetails["addr"]
                if uIP != "::1":
                    aFound.append(uIP)
                    if uNetiface == uPreferredAdapter:
                        aFound = [uIP]
                        break
    except Exception as e:
        Logger.error("Error on GetIPAddressV6:" + str(e))

    if len(aFound) > 0:
        uRet = aFound[-1]

    # remove stuff like %eth0 that gets thrown on end of some addrs
    uRet = uRet.split('%')[0]
    return uRet
Exemple #16
0
def try_update_for_testing():
    try:
        bar = window("update")
        if open(os.path.join(globals.baseSysPath,
                             globals.baseSysConfig.get("main", "name") + "Files", "OSVer"), "r").read() \
                != open(os.path.join(globals.HexOSPath, "OSVer"), "r").read():
            copy(
                bar,
                os.path.join(
                    globals.baseSysPath,
                    globals.baseSysConfig.get("main", "name") + "Files"))

    except FileNotFoundError:
        bar.parent.parent.parent.dismiss()
        Logger.error(
            "HexOSBase: Could not find OSVer file, asking user to hard reinstall"
        )

        popup = Popup(
            title="HexOS has missing files",
            content=Button(text="Reinstall",
                           on_release=lambda *args: install(),
                           on_press=lambda *args: popup.dismiss()),
            size_hint=(globals.baseSysConfig.get("os_changes", "size_hint_x"),
                       globals.baseSysConfig.get("os_changes", "size_hint_y")),
            auto_dismiss=False)

        popup.open()
Exemple #17
0
 def __init__(self, path):
     self.path = path
     Logger.debug("FaceDetector.__init__()")
     self.scale_factor = 2
     self.detector = cv2.CascadeClassifier(
         os.path.join(self.path,
                      "./data/haarcascade_frontalface_default.xml"))
Exemple #18
0
    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 GetMACAddress() -> List:

    uInet_Type: str = u'AF_INET'
    iInet_num: int

    uRetColon: str = u'00:00:00:00:00:00'
    uRetDash: str = u'00-00-00-00-00-00'

    try:
        iInet_num = getattr(netifaces, uInet_Type)
        aInterfaces: List = netifaces.interfaces()
        for uNetiface in aInterfaces:
            dNetInfo: Dict = netifaces.ifaddresses(uNetiface)
            aNetDetails: List = dNetInfo.get(iInet_num)
            if aNetDetails is not None and len(aNetDetails) > 0:
                dNetDetails: Dict = aNetDetails[0]
                if dNetDetails["addr"] == Globals.uIPAddressV4:
                    uRetColon = netifaces.ifaddresses(uNetiface)[
                        netifaces.AF_LINK][0]['addr']
                    uRetDash = uRetColon.replace(":", "-")
                    return [uRetColon, uRetDash]
    except Exception:
        pass

    try:
        uRetColon = u':'.join(re.findall('..', '%012x' % uuid.getnode()))
        uRetDash = u'-'.join(re.findall('..', '%012x' % uuid.getnode()))
    except Exception as e:
        Logger.error("Error on GetMACAdress:" + str(e))
    return [uRetColon, uRetDash]
	def stringReceived(self, string):
		phone_data = json.loads(string)

		user      = phone_data["user"]
		directory = phone_data["directory"]
		filename  = phone_data["filename"]
		raw_data  = phone_data["raw_data"]
		has_raw_data = phone_data["has_raw_data"]

		Logger.debug("FilenameReceiver Server: received: {0}, {1}, {2}, {3}".format(user, directory, filename, has_raw_data))

		# Save the file to disk (if we have the file data)
		if has_raw_data == "1":
			image_data = raw_data.decode('base64')
			folder_path = os.getcwd() + os.sep + "received_files" + os.sep + directory
			if not os.path.exists(folder_path):
				os.makedirs(folder_path)

			f = open(folder_path+os.sep+filename, 'wb')
			f.write(image_data)
			f.close()
			Logger.debug("FilenameReceiver Server: wrote image file to, received_files/{0}/{1}".format(directory, filename))

		# Do something here, in terms of logic (assuming received the file).
		result = self.app_root.root.process_image_from_phone(int(user), folder_path+os.sep+filename, filename)
		if result is True:
			# Send an ack back to the computer (or phone), with the filename
			source = self.transport.getPeer() # retrieve the ip of the computer that sent us the payload

			output = {"filename": filename}
			line = json.dumps(output)
			ClientCreator(reactor, TCPSender).connectTCP(source.host, 7895).addCallback(sendMessage, "{0}".format(line)).addErrback(printError)
Exemple #21
0
    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)
Exemple #22
0
    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()
Exemple #23
0
    def update(self):
        self.news = feedparser.parse(self.feed_url)

        article_list = []

        xlocale = locale.getlocale(locale.LC_TIME)
        locale.setlocale(locale.LC_TIME, 'en_US.utf-8')

        if not self.news['items']:
            Logger.error('NEWS: Seems there\'s no news')
            return # Return here so we keep old news (if any)

        for x in self.news['items']:
            description = unicode(x['description']).strip()
            description = description.split('<', 1)[0].strip()
            title = unicode(x['title']).strip()
            if description == '.':
                title = u'[color=#FFDD63]{}[/color]'.format(title)
                description = ''
            article_date = (datetime.strptime(x['published'], "%a, %d %b %Y %H:%M:%S %Z") + timedelta(hours=2))
            article_relative_date = format_timedelta(article_date - datetime.now(),
                                                     granularity='minute',
                                                     locale='ro_RO.utf-8',
                                                     add_direction=True)
            article_list.append(u'{}\n[color=#777777]{}[/color]\n\n{}'.format(title,
                                                                              article_relative_date,
                                                                              description))
        locale.setlocale(locale.LC_TIME, xlocale)
        self.articles = deque(article_list)
Exemple #24
0
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."
    )
Exemple #25
0
 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()
Exemple #26
0
 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())
Exemple #27
0
 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 on_parent_size(self, widget, size):
        if not self.autosize:
            # Other code will set pos/scale
            return

        Logger.debug(self.__class__.__name__ + '.on_parent_size %s', size)
        p_width, p_height = size

        # Ignore default/zero sizes
        if p_height == 0.0 or p_height == 1:
            Logger.debug('ignoring size %s', size)
            return

        # self size is always set to Image size, instead just re-center and re-scale
        # Idea: Maybe avoid this if user has moved-resized?

        # Fit Image/Mesh within
        #self.image.size = size
        # TODO Control points should stay aligned with image
        #print(self.__class__.__name__, 'on_size', size)
        # FIXME Updating Image.size messes up ControlPoint references
        # Only do this once
        # if self._image_size_set:
        #     return
        # self.image.size = size
        # self._image_size_set = True
        img = self.image
        self.center = self.parent.center

        # scale up to fit, whichever dimension is smaller
        h_scale = p_height/float(self.height)
        w_scale = p_width/float(self.width)
        self.scale = min(h_scale, w_scale)
Exemple #29
0
 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 on_image_filepath(self, _, image_filepath):
        # self has default size at this point, sizing must be done in on_size

        try:
            self.canvas.remove(self._core_image)
            Logger.debug('%s: removed old _core_image', self.__class__.__name__)
        except:
            pass

        with self.canvas:
            # mipmap=True changes tex_coords and screws up calculations
            # TODO Research mipmap more
            self._core_image = cimage = CoreImage(image_filepath, mipmap=False)

        texture = cimage.texture

        self.image.texture = texture
        self.mesh.texture = texture
        self.texture = texture
        # TODO Position Image center/zoomed by default
        # Nexus 10 Image is smaller, test density independent
        # TODO Is there any benifit to Image vs Rectangle w/ Texture ?

        # No need for Image if we're not taking advantage of ratio maintaining code
        # img = Image(texture=texture, keep_ratio=True, allow_stretch=True)
        # img.bind(norm_image_size=self.on_norm_image_size)
        # self.add_widget(img)

        # Just set Scatter and Rectangle to texture size
        self.image.size = texture.size
        self.size = texture.size
Exemple #31
0
    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 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")
Exemple #33
0
    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")
Exemple #34
0
 def refresh(self, place):
     last_updated = now = datetime.now()
     tomorrow = now + timedelta(days=1)
     place_cache = self.weather_data.get(place, {})
     if place in self.update_stamps:
         last_updated = self.update_stamps[place]
     if not place_cache or (now - last_updated).total_seconds() >= self.update_interval:
         try:
             self.weather_data[place] = self.api_object.weather_at_place(place).get_weather()
             self.forecast_today_data[place] = self.api_object.daily_forecast(place).get_weather_at(
                 now.replace(hour=12))
             try:
                 self.forecast_tomorrow_data[place] = self.api_object.daily_forecast(place).get_weather_at(
                     tomorrow.replace(hour=12))
             except Exception:
                 self.forecast_tomorrow_data[place] = {}
             self.update_stamps[place] = datetime.now()
         except Exception as e:
             self.update_stamps[place] = datetime.now()
             Logger.error('WEATHER: Failed to get data: {}'.format(e))
             return False
         except APICallError as e:
             self.update_stamps[place] = datetime.now()
             Logger.error('WEATHER: Failed to get data: {}'.format(e))
             return False
     return True
Exemple #35
0
    def verifyCallback(self, connection, x509, errno, depth, preverifyOK):

        # default value of post verify is set False
        postverifyOK = False

        if not preverifyOK:
            # Pre-verification failed
            Logger.debug(
                "SSLCONTEXT: [Pre-verification] Certificate verification failed, {}".format(x509.get_subject()))

        else:
            # Add post verification callback here.
            # Get x509 subject
            subject = x509.get_subject()

            Logger.debug("SSLCONTEXT: [Pre-verification] Certificate [{}] Verfied.".format(subject))

            # Perform post verification checks
            postverifyOK = self.postverifyCallback(subject, preverifyOK)

            # Post verification tasks
            if postverifyOK:
                self.postverify_hook(connection, x509)

        return preverifyOK and postverifyOK
Exemple #36
0
    def postverifyCallback(self, subject, preverifyOK):
        
        if not preverifyOK:
            return preverifyOK

        # variables for post-verify callback check on cert fields
        _cert_fields = constants.SSL_CERT_FIELDS
        _values_dict = constants.SSL_POST_VERIF_VALUES

        # Passed checks
        checklist_count = 0

        # Get certificate components
        certificate_components = dict(subject.get_components())

        # Check fields
        for i in _values_dict.keys():
            
            if certificate_components[_cert_fields[i]] in _values_dict[i]:
                checklist_count += 1
            else:
                print certificate_components[_cert_fields[i]] 
                print _values_dict[i]

        # Checklist roundoff
        if checklist_count == len(_values_dict.keys()):
            Logger.debug("SSLCONTEXT: [Post-verification] certificate verfication passed.")
            return True
        else:
            Logger.debug(
                "SSLCONTEXT: [Post-verification] Certificate verification failed. ({}/{} checks passed)".format(checklist_count, len(_values_dict.keys())))
            return False
    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:]
Exemple #38
0
 def send_message(self, *args):
     if len(self.text) > 250:
         popup = MOPopup("Warning", "Message too long", "OK")
         popup.open()
         return
     elif len(self.text) == 0 and not self.icon_change_spam:
         self.icon_change_spam = True
         Clock.schedule_once(self.enable_icon_change, 0.25)
         App.get_running_app().get_user_handler().send_icon()
         return
     main_scr = App.get_running_app().get_main_screen()
     Clock.schedule_once(main_scr.refocus_text)
     msg = escape_markup(self.text)
     if not self.message_is_valid(msg):
         return
     self.text = ""
     msg = self.extend_message(msg)
     if self.message_is_command(msg):
         try:
             self.handle_command(msg)
         except (AttributeError, IndexError) as e:
             Logger.warning(traceback.format_exc())
             return
     else:
         user_handler = App.get_running_app().get_user_handler()
         try:
             user_handler.send_message(msg)
         except Exception as e:
             popup = MOPopup("Warning", "Something went wrong. " + str(e),
                             "OK")
             popup.open()
Exemple #39
0
 def log(self, message, level='info', tag='CoatiraneAdventures'):
     Logger.log({
         'info': 20,
         'warn': 30,
         'debug': 10,
         'error': 40
     }[level], f"{tag}: {message}")
Exemple #40
0
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 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)
Exemple #42
0
    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")
Exemple #43
0
    def on_release(self):
        if (self.owner.mode == "range" and self.owner._end_range_date
                and self.owner._start_range_date):
            return
        if (not self.owner._input_date_dialog_open
                and not self.owner._select_year_dialog_open):
            if self.owner.mode == "range" and not self.owner._start_range_date:
                self.owner._start_range_date = date(self.current_year,
                                                    self.current_month,
                                                    int(self.text))
                self.owner.min_date = self.owner._start_range_date
            elif (self.owner.mode == "range" and not self.owner._end_range_date
                  and self.owner._start_range_date):
                self.owner._end_range_date = date(self.current_year,
                                                  self.current_month,
                                                  int(self.text))
                if self.owner._end_range_date <= self.owner.min_date:
                    toast(self.owner.date_range_text_error)
                    Logger.error(
                        "`Data Picker: max_date` value cannot be less than "
                        "or equal to 'min_date' value.")
                    self.owner._start_range_date = 0
                    self.owner._end_range_date = 0
                    return
                self.owner.max_date = self.owner._end_range_date
                self.owner.update_calendar_for_date_range()

            self.owner.set_selected_widget(self)
Exemple #44
0
 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 dataReceived(self, data):
#        print data
        if len(data) == 1:
            state = int(data)
            assert 0 <= state 
            assert state <= 3
            Logger.debug(self.__class__.__name__ + ': in ' + whoAmI() + '. ' + 'State is: ' + state)
            self.mindCupolaArduinoController.setModeAutomatically(state)
 def on_heaterState(self, instance, value):
     #TODO 3 set the heater duty cycle and make sure the duty cycle timer is running
     #also schedule a safety timer to force the heater off from time to time
     #TODO also add to initialisation and shutdown to force heater off
     Logger.exception(self.__class__.__name__ + ': in [' + whoAmI() + '] heaterState is ' + str(self.heaterState) + ' but NOT IMPLEMENTED YET')
     popup = Popup(title='heaterState Not implemented yet',
                   content=Label(text='heaterState Not implemented yet'),
                   size_hint=(0.4, 0.2) )
     popup.open()
Exemple #47
0
 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
Exemple #48
0
 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!!")                      
Exemple #49
0
def generate_uuid(host=None):
    """
    Generate capsule UID for particular host.
    """

    uuid_str = str(uuid5(NAMESPACE_URL, host))[0:8]

    Logger.debug("UTILITIES: UUID({}) = {}".format(host, uuid_str))

    return uuid_str
Exemple #50
0
 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))
Exemple #51
0
 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
Exemple #52
0
def get_nat_ip():
    "Get IP of NAT."

    s = socket(AF_INET, SOCK_STREAM)
    host = "127.0.0.1"
    try:
        s.connect(("www.google.com", 80))
    except error:
        Logger.debug("UTILITIES: No active NAT connection.")
        return host
    else:
        host = s.getsockname()[0]
        s.close()
        return host
    def on_animation_step(self, widget, step):
        """animation_step changed.
        move control points to step with animation
        Set mesh_attached=False if on setup_step
        """
        Logger.debug('%s: on_animation_step %s', self.__class__.__name__, step)
        if not isinstance(step, basestring):
            raise ValueError('animation_step must be a string, given %s'%step, type(step))

        # Track all possible step keys
        if step != setup_step and step not in self.animation_steps_order:
            self.animation_steps_order.append(step)

        resume_animation = self.animating
        if self.animating:
            # Switched step while previewing animation
            self.preview_animation(False)

        if step == setup_step:
            self.image_opacity = self.faded_image_opacity

            # ControlPoints will detach mesh after animation in: move_control_points()
            self.mesh_attached = False

        else:
            # Not first animation step
            self.image_opacity = 0.0

            mesh = self.mesh

            if self._previous_step == setup_step:
                # Redo base vertices when moving from 0 to other
                Logger.debug('Recalculating vertices/indices during transition from step 0')
                self.calc_mesh_vertices(step=setup_step, preserve_uv=False)

            if not self.mesh_attached:
                # attach before moving to other animation steps
                for cp in self.control_points:
                    cp.attach_mesh(True)

                self.mesh_attached = True

        self.move_control_points(step, detach_mesh_after=step == setup_step)

        self._previous_step = step

        if resume_animation:
            self.preview_animation()
Exemple #54
0
 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.")
Exemple #55
0
 def _get(self, mimetype='text/plain'):
     clippy = PythonActivity._clipboard
     data = ''
     if sdk < 11:
         data = clippy.getText()
     else:
         ClipDescription = autoclass('android.content.ClipDescription')
         primary_clip = clippy.getPrimaryClip()
         if primary_clip:
             try:
                 data = primary_clip.getItemAt(0)
                 if data:
                     data = data.coerceToText(
                         PythonActivity.mActivity.getApplicationContext())
             except Exception:
                 Logger.exception('Clipboard: failed to paste')
     return data
    def onLoggerCheck(self, dt):
        Logger.trace(self.__class__.__name__ + ': Checking Log')
        
        newLogLastModifiedTime = getmtime(self.logFileName)
        logTimeSinceLastCheckedModification = newLogLastModifiedTime - self.logLastModificationTime
        self.logLastModificationTime = newLogLastModifiedTime

        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))
Exemple #57
0
def criptiklogo():
    """
    Read the logo and return it as string.
    """

    logofile = "{}/../data/logo.txt".format(dirname(realpath(__file__)))

    try:
        # Open and read logo file
        with open(logofile, "r") as f:
            logo = "".join(f.readlines())
    except IOError:
        # No logo present
        Logger.error("UTILITIES: Failed to read cryptikchaos logo.")
        return None
    else:
        # Return logo if success
        return logo.format(md5hash(str(getnode()))[0:8], __version__)
Exemple #58
0
def get_my_ip():
    "Get my public IP address or if offline get my NAT IP."

    try:
        # Get IP from curlmyip.com which gives the raw ip address
        my_pub_ip = urlopen("http://curlmyip.com").read().strip()

        # Check for portal redirects if offline
        if not ip_address_is_valid(my_pub_ip):
            my_pub_ip = None

    except URLError:
        Logger.debug("UTILITIES: No active internet connection.")
        my_pub_ip = None

    # Get local IP
    my_loc_ip = get_local_ip()

    return (my_loc_ip, my_pub_ip)
Exemple #59
-1
 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!")