Exemplo n.º 1
0
    def __init__(self,
                 device_path,
                 device_number,
                 config,
                 persistence,
                 testing=False,
                 additional_interfaces=None,
                 additional_methods=[]):

        self.logger = logging.getLogger(
            'razer.device{0}'.format(device_number))
        self.logger.info("Initialising device.%d %s", device_number,
                         self.__class__.__name__)

        # Serial cache
        self._serial = None

        # Local storage key name
        self.storage_name = "UnknownDevice"

        self._observer_list = []
        self._effect_sync_propagate_up = False
        self._disable_notifications = False
        self.additional_interfaces = []
        if additional_interfaces is not None:
            self.additional_interfaces.extend(additional_interfaces)

        self.config = config
        self.persistence = persistence
        self._testing = testing
        self._parent = None
        self._device_path = device_path
        self._device_number = device_number
        self.serial = self.get_serial()

        if self.USB_PID == 0x0f07:
            self.storage_name = "ChromaMug"
        elif self.USB_PID == 0x0013:
            self.storage_name = "Orochi2011"
        elif self.USB_PID == 0x0016:
            self.storage_name = "DeathAdder35G"
        elif self.USB_PID == 0x0024 or self.USB_PID == 0x0025:
            self.storage_name = "Mamba2012"
        else:
            self.storage_name = self.serial

        self.zone = dict()

        for i in self.ZONES:
            self.zone[i] = {
                "present": False,
                "active": True,
                "brightness": 75.0,
                "effect": 'spectrum',
                "colors": [0, 255, 0, 0, 255, 255, 0, 0, 255],
                "speed": 1,
                "wave_dir": 1,
            }

        self.dpi = [1800, 1800]
        self.poll_rate = 500

        self._effect_sync = effect_sync.EffectSync(self, device_number)

        self._is_closed = False

        # device methods available in all devices
        self.methods_internal = [
            'get_firmware', 'get_matrix_dims', 'has_matrix', 'get_device_name'
        ]
        self.methods_internal.extend(additional_methods)

        # Find event files in /dev/input/by-id/ by matching against regex
        self.event_files = []

        if self._testing:
            search_dir = os.path.join(device_path, 'input')
        else:
            search_dir = '/dev/input/by-id/'

        if os.path.exists(search_dir):
            for event_file in os.listdir(search_dir):
                if self.EVENT_FILE_REGEX is not None and self.EVENT_FILE_REGEX.match(
                        event_file) is not None:
                    self.event_files.append(
                        os.path.join(search_dir, event_file))

        object_path = os.path.join(self.OBJECT_PATH, self.serial)
        DBusService.__init__(self, self.BUS_PATH, object_path)

        # Set up methods to suspend and restore device operation
        self.suspend_args = {}
        self.method_args = {}

        methods = {
            # interface, method, callback, in-args, out-args
            ('razer.device.misc', 'getSerial', self.get_serial, None, 's'),
            ('razer.device.misc', 'suspendDevice', self.suspend_device, None,
             None),
            ('razer.device.misc', 'getDeviceMode', self.get_device_mode, None,
             's'),
            ('razer.device.misc', 'getRazerUrls', self.get_image_json, None,
             's'),
            ('razer.device.misc', 'setDeviceMode', self.set_device_mode, 'yy',
             None),
            ('razer.device.misc', 'resumeDevice', self.resume_device, None,
             None),
            ('razer.device.misc', 'getVidPid', self.get_vid_pid, None, 'ai'),
            ('razer.device.misc', 'getDriverVersion',
             openrazer_daemon.dbus_services.dbus_methods.version, None, 's'),
            ('razer.device.misc', 'hasDedicatedMacroKeys',
             self.dedicated_macro_keys, None, 'b'),
            ('razer.device.lighting.chroma', 'restoreLastEffect',
             self.restore_effect, None, None),
        }

        effect_methods = {
            "backlight": {
                ('razer.device.lighting.chroma', 'getEffect',
                 self.get_current_effect, None, 's'),
                ('razer.device.lighting.chroma', 'getEffectColors',
                 self.get_current_effect_colors, None, 'ay'),
                ('razer.device.lighting.chroma', 'getEffectSpeed',
                 self.get_current_effect_speed, None, 'i'),
                ('razer.device.lighting.chroma', 'getWaveDir',
                 self.get_current_wave_dir, None, 'i'),
            },
            "logo": {
                ('razer.device.lighting.logo', 'getLogoEffect',
                 self.get_current_logo_effect, None, 's'),
                ('razer.device.lighting.logo', 'getLogoEffectColors',
                 self.get_current_logo_effect_colors, None, 'ay'),
                ('razer.device.lighting.logo', 'getLogoEffectSpeed',
                 self.get_current_logo_effect_speed, None, 'i'),
                ('razer.device.lighting.logo', 'getLogoWaveDir',
                 self.get_current_logo_wave_dir, None, 'i'),
            },
            "scroll": {
                ('razer.device.lighting.scroll', 'getScrollEffect',
                 self.get_current_scroll_effect, None, 's'),
                ('razer.device.lighting.scroll', 'getScrollEffectColors',
                 self.get_current_scroll_effect_colors, None, 'ay'),
                ('razer.device.lighting.scroll', 'getScrollEffectSpeed',
                 self.get_current_scroll_effect_speed, None, 'i'),
                ('razer.device.lighting.scroll', 'getScrollWaveDir',
                 self.get_current_scroll_wave_dir, None, 'i'),
            },
            "left": {
                ('razer.device.lighting.left', 'getLeftEffect',
                 self.get_current_left_effect, None, 's'),
                ('razer.device.lighting.left', 'getLeftEffectColors',
                 self.get_current_left_effect_colors, None, 'ay'),
                ('razer.device.lighting.left', 'getLeftEffectSpeed',
                 self.get_current_left_effect_speed, None, 'i'),
                ('razer.device.lighting.left', 'getLeftWaveDir',
                 self.get_current_left_wave_dir, None, 'i'),
            },
            "right": {
                ('razer.device.lighting.right', 'getRightEffect',
                 self.get_current_right_effect, None, 's'),
                ('razer.device.lighting.right', 'getRightEffectColors',
                 self.get_current_right_effect_colors, None, 'ay'),
                ('razer.device.lighting.right', 'getRightEffectSpeed',
                 self.get_current_right_effect_speed, None, 'i'),
                ('razer.device.lighting.right', 'getRightWaveDir',
                 self.get_current_right_wave_dir, None, 'i'),
            }
        }

        for m in methods:
            self.logger.debug("Adding {}.{} method to DBus".format(m[0], m[1]))
            self.add_dbus_method(m[0],
                                 m[1],
                                 m[2],
                                 in_signature=m[3],
                                 out_signature=m[4])

        # this check is separate from the rest because backlight effects don't have prefixes in their names
        if 'set_static_effect' in self.METHODS or 'bw_set_static' in self.METHODS:
            self.zone["backlight"]["present"] = True
            for m in effect_methods["backlight"]:
                self.logger.debug("Adding {}.{} method to DBus".format(
                    m[0], m[1]))
                self.add_dbus_method(m[0],
                                     m[1],
                                     m[2],
                                     in_signature=m[3],
                                     out_signature=m[4])

        for i in self.ZONES[1:]:
            if 'set_' + i + '_static' in self.METHODS or 'set_' + i + '_static_naga_hex_v2' in self.METHODS or '`set_' + i + 'active' in self.METHODS:
                self.zone[i]["present"] = True
                for m in effect_methods[i]:
                    self.logger.debug("Adding {}.{} method to DBus".format(
                        m[0], m[1]))
                    self.add_dbus_method(m[0],
                                         m[1],
                                         m[2],
                                         in_signature=m[3],
                                         out_signature=m[4])

        # Load additional DBus methods
        self.load_methods()

        # load last DPI/poll rate state
        if self.persistence.has_section(self.storage_name):
            if 'set_dpi_xy' in self.METHODS:
                try:
                    self.dpi[0] = int(
                        self.persistence[self.storage_name]['dpi_x'])
                    self.dpi[1] = int(
                        self.persistence[self.storage_name]['dpi_y'])
                except KeyError:
                    pass

            if 'set_poll_rate' in self.METHODS:
                try:
                    self.poll_rate = int(
                        self.persistence[self.storage_name]['poll_rate'])
                except KeyError:
                    pass

        dpi_func = getattr(self, "setDPI", None)
        if dpi_func is not None:
            dpi_func(self.dpi[0], self.dpi[1])

        poll_rate_func = getattr(self, "setPollRate", None)
        if poll_rate_func is not None:
            poll_rate_func(self.poll_rate)

        # load last effects
        for i in self.ZONES:
            if self.zone[i]["present"]:
                # check if we have the device in the persistence file
                if self.persistence.has_section(self.storage_name):
                    # try reading the effect name from the persistence
                    try:
                        self.zone[i]["effect"] = self.persistence[
                            self.storage_name][i + '_effect']
                    except KeyError:
                        pass

                    # zone active status
                    try:
                        self.zone[i]["active"] = bool(
                            self.persistence[self.storage_name][i + '_active'])
                    except KeyError:
                        pass

                    # brightness
                    try:
                        self.zone[i]["brightness"] = float(
                            self.persistence[self.storage_name][i +
                                                                '_brightness'])
                    except KeyError:
                        pass

                    # colors.
                    # these are stored as a string that must contain 9 numbers, separated with spaces.
                    try:
                        for index, item in enumerate(self.persistence[
                                self.storage_name][i + '_colors'].split(" ")):
                            self.zone[i]["colors"][index] = int(item)
                            # check if the color is in range
                            if not 0 <= self.zone[i]["colors"][index] <= 255:
                                raise ValueError('Color out of range')

                        # check if we have exactly 9 colors
                        if len(self.zone[i]["colors"]) != 9:
                            raise ValueError('There must be exactly 9 colors')

                    except ValueError:
                        # invalid colors. reinitialize
                        self.zone[i]["colors"] = [
                            0, 255, 0, 0, 255, 255, 0, 0, 255
                        ]
                        self.logger.info(
                            "%s: Invalid colors; restoring to defaults.",
                            self.__class__.__name__)
                        pass

                    except KeyError:
                        pass

                    # speed
                    try:
                        self.zone[i]["speed"] = int(
                            self.persistence[self.storage_name][i + '_speed'])

                    except KeyError:
                        pass

                    # wave direction
                    try:
                        self.zone[i]["wave_dir"] = int(
                            self.persistence[self.storage_name][i +
                                                                '_wave_dir'])

                    except KeyError:
                        pass

                if 'set_' + i + '_active' in self.METHODS:
                    active_func = getattr(
                        self, "set" + self.capitalize_first_char(i) + "Active",
                        None)
                    if active_func is not None:
                        active_func(self.zone[i]["active"])

                # load brightness level
                bright_func = None
                if i == "backlight":
                    bright_func = getattr(self, "setBrightness", None)
                elif 'set_' + i + '_brightness' in self.METHODS:
                    bright_func = getattr(
                        self,
                        "set" + self.capitalize_first_char(i) + "Brightness",
                        None)

                if bright_func is not None:
                    bright_func(self.zone[i]["brightness"])

        self.restore_effect()
Exemplo n.º 2
0
    def __init__(self,
                 device_path,
                 device_number,
                 config,
                 testing=False,
                 additional_interfaces=None):

        self.logger = logging.getLogger(
            'razer.device{0}'.format(device_number))
        self.logger.info("Initialising device.%d %s", device_number,
                         self.__class__.__name__)

        # Serial cache
        self._serial = None

        self._observer_list = []
        self._effect_sync_propagate_up = False
        self._disable_notifications = False
        self.additional_interfaces = []
        if additional_interfaces is not None:
            self.additional_interfaces.extend(additional_interfaces)

        self.config = config
        self._testing = testing
        self._parent = None
        self._device_path = device_path
        self._device_number = device_number
        self.serial = self.get_serial()

        self._effect_sync = effect_sync.EffectSync(self, device_number)

        self._is_closed = False

        # Find event files in /dev/input/by-id/ by matching against regex
        self.event_files = []

        if self._testing:
            search_dir = os.path.join(device_path, 'input')
        else:
            search_dir = '/dev/input/by-id/'

        if os.path.exists(search_dir):
            for event_file in os.listdir(search_dir):
                if self.EVENT_FILE_REGEX is not None and self.EVENT_FILE_REGEX.match(
                        event_file) is not None:
                    self.event_files.append(
                        os.path.join(search_dir, event_file))

        object_path = os.path.join(self.OBJECT_PATH, self.serial)
        DBusService.__init__(self, self.BUS_PATH, object_path)

        # Set up methods to suspend and restore device operation
        self.suspend_args = {}
        self.method_args = {}

        methods = {
            # interface, method, callback, in-args, out-args
            ('razer.device.misc', 'getSerial', self.get_serial, None, 's'),
            ('razer.device.misc', 'suspendDevice', self.suspend_device, None,
             None),
            ('razer.device.misc', 'getDeviceMode', self.get_device_mode, None,
             's'),
            ('razer.device.misc', 'getRazerUrls', self.get_image_json, None,
             's'),
            ('razer.device.misc', 'setDeviceMode', self.set_device_mode, 'yy',
             None),
            ('razer.device.misc', 'resumeDevice', self.resume_device, None,
             None),
            ('razer.device.misc', 'getVidPid', self.get_vid_pid, None, 'ai'),
            ('razer.device.misc', 'getDriverVersion',
             openrazer_daemon.dbus_services.dbus_methods.version, None, 's'),
            ('razer.device.misc', 'hasDedicatedMacroKeys',
             self.dedicated_macro_keys, None, 'b'),
        }

        for m in methods:
            self.logger.debug("Adding {}.{} method to DBus".format(m[0], m[1]))
            self.add_dbus_method(m[0],
                                 m[1],
                                 m[2],
                                 in_signature=m[3],
                                 out_signature=m[4])

        # Load additional DBus methods
        self.load_methods()