index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
29,647
cocotb
start_soon
Schedule a coroutine to be run concurrently. Note that this is not an async function, and the new task will not execute until the calling task yields control. .. versionadded:: 1.6.0
def start_soon(coro: Union[Task, Coroutine]) -> Task: """ Schedule a coroutine to be run concurrently. Note that this is not an async function, and the new task will not execute until the calling task yields control. .. versionadded:: 1.6.0 """ return scheduler.start_soon(coro)
(coro: Union[cocotb.task.Task, collections.abc.Coroutine]) -> cocotb.task.Task
29,650
cocotb.decorators
test
Decorator to mark a Callable which returns a Coroutine as a test. The test decorator provides a test timeout, and allows us to mark tests as skipped or expecting errors or failures. Tests are evaluated in the order they are defined in a test module. Used as ``@cocotb.test(...)``. Args: timeout_time (numbers.Real or decimal.Decimal, optional): Simulation time duration before timeout occurs. .. versionadded:: 1.3 .. note:: Test timeout is intended for protection against deadlock. Users should use :class:`~cocotb.triggers.with_timeout` if they require a more general-purpose timeout mechanism. timeout_unit (str, optional): Units of timeout_time, accepts any units that :class:`~cocotb.triggers.Timer` does. .. versionadded:: 1.3 .. deprecated:: 1.5 Using ``None`` as the *timeout_unit* argument is deprecated, use ``'step'`` instead. expect_fail (bool, optional): If ``True`` and the test fails a functional check via an ``assert`` statement, :class:`pytest.raises`, :class:`pytest.warns`, or :class:`pytest.deprecated_call` the test is considered to have passed. If ``True`` and the test passes successfully, the test is considered to have failed. expect_error (exception type or tuple of exception types, optional): Mark the result as a pass only if one of the exception types is raised in the test. This is primarily for cocotb internal regression use for when a simulator error is expected. Users are encouraged to use the following idiom instead:: @cocotb.test() async def my_test(dut): try: await thing_that_should_fail() except ExceptionIExpect: pass else: assert False, "Exception did not occur" .. versionchanged:: 1.3 Specific exception types can be expected .. deprecated:: 1.5 Passing a :class:`bool` value is now deprecated. Pass a specific :class:`Exception` or a tuple of Exceptions instead. skip (bool, optional): Don't execute this test as part of the regression. Test can still be run manually by setting :make:var:`TESTCASE`. stage (int) Order tests logically into stages, where multiple tests can share a stage. Defaults to 0.
class test(coroutine, metaclass=_decorator_helper): """ Decorator to mark a Callable which returns a Coroutine as a test. The test decorator provides a test timeout, and allows us to mark tests as skipped or expecting errors or failures. Tests are evaluated in the order they are defined in a test module. Used as ``@cocotb.test(...)``. Args: timeout_time (numbers.Real or decimal.Decimal, optional): Simulation time duration before timeout occurs. .. versionadded:: 1.3 .. note:: Test timeout is intended for protection against deadlock. Users should use :class:`~cocotb.triggers.with_timeout` if they require a more general-purpose timeout mechanism. timeout_unit (str, optional): Units of timeout_time, accepts any units that :class:`~cocotb.triggers.Timer` does. .. versionadded:: 1.3 .. deprecated:: 1.5 Using ``None`` as the *timeout_unit* argument is deprecated, use ``'step'`` instead. expect_fail (bool, optional): If ``True`` and the test fails a functional check via an ``assert`` statement, :class:`pytest.raises`, :class:`pytest.warns`, or :class:`pytest.deprecated_call` the test is considered to have passed. If ``True`` and the test passes successfully, the test is considered to have failed. expect_error (exception type or tuple of exception types, optional): Mark the result as a pass only if one of the exception types is raised in the test. This is primarily for cocotb internal regression use for when a simulator error is expected. Users are encouraged to use the following idiom instead:: @cocotb.test() async def my_test(dut): try: await thing_that_should_fail() except ExceptionIExpect: pass else: assert False, "Exception did not occur" .. versionchanged:: 1.3 Specific exception types can be expected .. deprecated:: 1.5 Passing a :class:`bool` value is now deprecated. Pass a specific :class:`Exception` or a tuple of Exceptions instead. skip (bool, optional): Don't execute this test as part of the regression. Test can still be run manually by setting :make:var:`TESTCASE`. stage (int) Order tests logically into stages, where multiple tests can share a stage. Defaults to 0. """ _id_count = 0 # used by the RegressionManager to sort tests in definition order def __init__( self, f, timeout_time=None, timeout_unit="step", expect_fail=False, expect_error=(), skip=False, stage=0, ): if timeout_unit is None: warnings.warn( 'Using timeout_unit=None is deprecated, use timeout_unit="step" instead.', DeprecationWarning, stacklevel=2, ) timeout_unit = "step" # don't propagate deprecated value self._id = self._id_count type(self)._id_count += 1 if timeout_time is not None: co = coroutine(f) @functools.wraps(f) async def f(*args, **kwargs): running_co = co(*args, **kwargs) try: res = await cocotb.triggers.with_timeout( running_co, self.timeout_time, self.timeout_unit ) except cocotb.result.SimTimeoutError: running_co.kill() raise else: return res super().__init__(f) self.timeout_time = timeout_time self.timeout_unit = timeout_unit self.expect_fail = expect_fail if isinstance(expect_error, bool): warnings.warn( "Passing bool values to `except_error` option of `cocotb.test` is deprecated. " "Pass a specific Exception type instead", DeprecationWarning, stacklevel=2, ) if expect_error is True: expect_error = (BaseException,) elif expect_error is False: expect_error = () self.expect_error = expect_error self.skip = skip self.stage = stage self.im_test = True # For auto-regressions self.name = self._func.__name__ def __call__(self, *args, **kwargs): inst = self._func(*args, **kwargs) coro = _RunningTest(inst, self) return coro
(*args, **kwargs)
29,651
cocotb.decorators
__call__
null
def __call__(self, *args, **kwargs): inst = self._func(*args, **kwargs) coro = _RunningTest(inst, self) return coro
(self, *args, **kwargs)
29,653
cocotb.decorators
__init__
null
def __init__( self, f, timeout_time=None, timeout_unit="step", expect_fail=False, expect_error=(), skip=False, stage=0, ): if timeout_unit is None: warnings.warn( 'Using timeout_unit=None is deprecated, use timeout_unit="step" instead.', DeprecationWarning, stacklevel=2, ) timeout_unit = "step" # don't propagate deprecated value self._id = self._id_count type(self)._id_count += 1 if timeout_time is not None: co = coroutine(f) @functools.wraps(f) async def f(*args, **kwargs): running_co = co(*args, **kwargs) try: res = await cocotb.triggers.with_timeout( running_co, self.timeout_time, self.timeout_unit ) except cocotb.result.SimTimeoutError: running_co.kill() raise else: return res super().__init__(f) self.timeout_time = timeout_time self.timeout_unit = timeout_unit self.expect_fail = expect_fail if isinstance(expect_error, bool): warnings.warn( "Passing bool values to `except_error` option of `cocotb.test` is deprecated. " "Pass a specific Exception type instead", DeprecationWarning, stacklevel=2, ) if expect_error is True: expect_error = (BaseException,) elif expect_error is False: expect_error = () self.expect_error = expect_error self.skip = skip self.stage = stage self.im_test = True # For auto-regressions self.name = self._func.__name__
(self, f, timeout_time=None, timeout_unit='step', expect_fail=False, expect_error=(), skip=False, stage=0)
29,663
sunix_ledstrip_controller_client.controller
Controller
Device class that represents a single controller
class Controller: """ Device class that represents a single controller """ import datetime # workaround for cyclic dependencies introduced by typing from typing import TYPE_CHECKING if TYPE_CHECKING: from .client import LEDStripControllerClient from .functions import FunctionId from .packets import TransitionType POWER_STATE_ON = 0x23 POWER_STATE_OFF = 0x24 DEFAULT_PORT = 5577 def __init__(self, api: 'LEDStripControllerClient', host: str, port: int = DEFAULT_PORT, hardware_id: str = None, model: str = None): """ Creates a new controller device object :param host: host address of the controller device :param port: the port on which the controller device is listening """ self._api = api self._host = host if not port: self._port = self.DEFAULT_PORT else: self._port = port self._device_name = None self._hardware_id = hardware_id self._model = model self._power_state = None self._rgbww = None self._function = None self._function_speed = 255 self.update_state() def __hash__(self): return hash((self._host, self._port, self._device_name, self._hardware_id)) def __eq__(self, other): return other is not None and self._host == other.get_host() and self._port == other._port and self._device_name == other._device_name and self._hardware_id == other._hardware_id def __str__(self): return ("Host: %s\n" % (self.get_host()) + "Port: %s\n" % (self.get_port()) + "Device name: %s\n" % (self.get_device_name()) + "Hardware ID: %s\n" % (self.get_hardware_id()) + "Model: %s" % (self.get_model())) def get_host(self) -> str or None: """ :return: The IP/Host address of this device """ return self._host def get_port(self) -> int: """ :return: The port of this device """ return self._port def get_device_name(self) -> str or None: """ :return: The device name of this controller """ return self._device_name def get_hardware_id(self) -> str or None: """ :return: The hardware ID of this device (f.ex. 'F0FE6B2333C6') """ return self._hardware_id def get_model(self) -> str or None: """ :return: The model of this device """ return self._model def get_time(self) -> datetime: """ :return: the current time of this controller """ response = self._api.get_time(self._host, self._port) if (response["year"] == 0 and response["month"] == 0 and response["day"] == 0 and response["hour"] == 0 and response["minute"] == 0 and response["second"] == 0): return None else: dt = datetime.datetime( response["year"] + 2000, response["month"], response["day"], response["hour"], response["minute"], response["second"] ) return dt def set_time(self, date_time: datetime) -> None: """ Sets the internal time of this controller :param date_time: the time to set """ self._api.set_time(self._host, self._port, date_time) def is_on(self) -> bool: """ :return: True if the controller is turned on, false otherwise """ return self._power_state is self.POWER_STATE_ON def turn_on(self) -> None: """ Turn on this controller """ self._api.turn_on(self._host, self._port) self.update_state() def turn_off(self) -> None: """ Turn on this controller """ self._api.turn_off(self._host, self._port) self.update_state() def get_rgbww(self) -> (int, int, int, int, int) or None: """ :return: the RGB color values """ return self._rgbww def set_rgbww(self, red: int, green: int, blue: int, warm_white: int, cold_white: int) -> None: """ Sets rgbww values for this controller. :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255) :param warm_white: warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255) """ self._api.set_rgbww(self._host, self._port, red, green, blue, warm_white, cold_white) self.update_state() def set_rgb(self, red: int, green: int, blue: int) -> None: """ Sets rgbw values for this controller. :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255) """ self._api.set_rgb(self._host, self._port, red, green, blue) self.update_state() def set_ww(self, warm_white: int, cold_white: int) -> None: """ Sets warm white and cold white values for this controller. :param warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255) """ self._api.set_ww(self._host, self._port, cold_white, warm_white) self.update_state() def get_brightness(self) -> int or None: """ Note: this value is calculated in the library and not on the device :return: the brightness of the controller [0..255] or None if no value is set """ if not self._rgbww: return None brightness = 0 for color in self._rgbww: brightness += color return int(brightness / len(self._rgbww)) def set_brightness(self, brightness: int) -> None: """ Sets a specific brightness without changing the color. :param brightness: (0..255) """ new_rgbww = [] for color in self._rgbww: new_rgbww.append(color * (brightness / 255)) self.set_rgbww(new_rgbww[0], new_rgbww[1], new_rgbww[2], new_rgbww[3], new_rgbww[4]) def set_function(self, function_id: FunctionId, speed: int): """ Sets a function on the specified controller :param function_id: Function ID :param speed: function speed [0..255] 0 is slow, 255 is fast """ self._api.set_function(self._host, self._port, function_id, speed) self.update_state() def set_custom_function(self, color_values: [(int, int, int, int)], speed: int, transition_type: TransitionType = TransitionType.Gradual): """ Sets a custom function on this controller :param color_values: a list of up to 16 color tuples of the form (red, green, blue) or (red, green, blue, unknown). I couldn't figure out what the last parameter is used for so the rgb is a shortcut. :param transition_type: the transition type between colors :param speed: function speed [0..255] 0 is slow, 255 is fast """ self._api.set_custom_function(self._host, self._port, color_values, speed, transition_type) self.update_state() def get_timers(self) -> [Timer]: """ Gets the defined timers of this controller :return: list of timers """ def extract_timer_time(data: dict, idx: int) -> datetime: # combination of constants dayofweek = data["dayofweek_%d" % idx] if dayofweek != 0: return None year = data["year_%d" % idx] + 2000 month = data["month_%d" % idx] day = data["day_%d" % idx] hour = data["hour_%d" % idx] minute = data["minute_%d" % idx] second = data["second_%d" % idx] execution_time = datetime.datetime.now().replace(day=day, month=month, year=year, hour=hour, minute=minute, second=second) return execution_time def extract_timer_pattern(data: dict, idx: int) -> datetime: mode = data["action_code_%d" % idx] if (mode == 0x61): pass # TODO return mode timers_data = self._api.get_timers(self._host, self._port) timers = [] for idx in range(1, 7): enabled = Timer.STATE_ENABLED == timers_data["is_active_%d" % idx] time = extract_timer_time(timers_data, idx) pattern = extract_timer_pattern(timers_data, idx) red = timers_data["red_%d" % idx] green = timers_data["green_%d" % idx] blue = timers_data["blue_%d" % idx] timer = Timer( enabled=enabled, execution_time=time, pattern=pattern, red=red, green=green, blue=blue, ) timers.append(timer) return timers def update_state(self): """ Updates the state of this controller """ state = self._api.get_state(self._host, self._port) # update the controller values from the response self._device_name = state["device_name"] self._power_state = state["power_status"] self._function = state["mode"] self._function_speed = state["speed"] self._rgbww = ( state["red"], state["green"], state["blue"], state["warm_white"], state["cold_white"] )
(api: 'LEDStripControllerClient', host: str, port: int = 5577, hardware_id: str = None, model: str = None)
29,664
sunix_ledstrip_controller_client.controller
__eq__
null
def __eq__(self, other): return other is not None and self._host == other.get_host() and self._port == other._port and self._device_name == other._device_name and self._hardware_id == other._hardware_id
(self, other)
29,665
sunix_ledstrip_controller_client.controller
__hash__
null
def __hash__(self): return hash((self._host, self._port, self._device_name, self._hardware_id))
(self)
29,666
sunix_ledstrip_controller_client.controller
__init__
Creates a new controller device object :param host: host address of the controller device :param port: the port on which the controller device is listening
def __init__(self, api: 'LEDStripControllerClient', host: str, port: int = DEFAULT_PORT, hardware_id: str = None, model: str = None): """ Creates a new controller device object :param host: host address of the controller device :param port: the port on which the controller device is listening """ self._api = api self._host = host if not port: self._port = self.DEFAULT_PORT else: self._port = port self._device_name = None self._hardware_id = hardware_id self._model = model self._power_state = None self._rgbww = None self._function = None self._function_speed = 255 self.update_state()
(self, api: 'LEDStripControllerClient', host: str, port: int = 5577, hardware_id: str = None, model: str = None)
29,667
sunix_ledstrip_controller_client.controller
__str__
null
def __str__(self): return ("Host: %s\n" % (self.get_host()) + "Port: %s\n" % (self.get_port()) + "Device name: %s\n" % (self.get_device_name()) + "Hardware ID: %s\n" % (self.get_hardware_id()) + "Model: %s" % (self.get_model()))
(self)
29,668
sunix_ledstrip_controller_client.controller
get_brightness
Note: this value is calculated in the library and not on the device :return: the brightness of the controller [0..255] or None if no value is set
def get_brightness(self) -> int or None: """ Note: this value is calculated in the library and not on the device :return: the brightness of the controller [0..255] or None if no value is set """ if not self._rgbww: return None brightness = 0 for color in self._rgbww: brightness += color return int(brightness / len(self._rgbww))
(self) -> int
29,669
sunix_ledstrip_controller_client.controller
get_device_name
:return: The device name of this controller
def get_device_name(self) -> str or None: """ :return: The device name of this controller """ return self._device_name
(self) -> str
29,670
sunix_ledstrip_controller_client.controller
get_hardware_id
:return: The hardware ID of this device (f.ex. 'F0FE6B2333C6')
def get_hardware_id(self) -> str or None: """ :return: The hardware ID of this device (f.ex. 'F0FE6B2333C6') """ return self._hardware_id
(self) -> str
29,671
sunix_ledstrip_controller_client.controller
get_host
:return: The IP/Host address of this device
def get_host(self) -> str or None: """ :return: The IP/Host address of this device """ return self._host
(self) -> str
29,672
sunix_ledstrip_controller_client.controller
get_model
:return: The model of this device
def get_model(self) -> str or None: """ :return: The model of this device """ return self._model
(self) -> str
29,673
sunix_ledstrip_controller_client.controller
get_port
:return: The port of this device
def get_port(self) -> int: """ :return: The port of this device """ return self._port
(self) -> int
29,674
sunix_ledstrip_controller_client.controller
get_rgbww
:return: the RGB color values
def get_rgbww(self) -> (int, int, int, int, int) or None: """ :return: the RGB color values """ return self._rgbww
(self) -> (<class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>)
29,675
sunix_ledstrip_controller_client.controller
get_time
:return: the current time of this controller
def get_time(self) -> datetime: """ :return: the current time of this controller """ response = self._api.get_time(self._host, self._port) if (response["year"] == 0 and response["month"] == 0 and response["day"] == 0 and response["hour"] == 0 and response["minute"] == 0 and response["second"] == 0): return None else: dt = datetime.datetime( response["year"] + 2000, response["month"], response["day"], response["hour"], response["minute"], response["second"] ) return dt
(self) -> <module 'datetime' from '/usr/local/lib/python3.10/datetime.py'>
29,676
sunix_ledstrip_controller_client.controller
get_timers
Gets the defined timers of this controller :return: list of timers
def get_timers(self) -> [Timer]: """ Gets the defined timers of this controller :return: list of timers """ def extract_timer_time(data: dict, idx: int) -> datetime: # combination of constants dayofweek = data["dayofweek_%d" % idx] if dayofweek != 0: return None year = data["year_%d" % idx] + 2000 month = data["month_%d" % idx] day = data["day_%d" % idx] hour = data["hour_%d" % idx] minute = data["minute_%d" % idx] second = data["second_%d" % idx] execution_time = datetime.datetime.now().replace(day=day, month=month, year=year, hour=hour, minute=minute, second=second) return execution_time def extract_timer_pattern(data: dict, idx: int) -> datetime: mode = data["action_code_%d" % idx] if (mode == 0x61): pass # TODO return mode timers_data = self._api.get_timers(self._host, self._port) timers = [] for idx in range(1, 7): enabled = Timer.STATE_ENABLED == timers_data["is_active_%d" % idx] time = extract_timer_time(timers_data, idx) pattern = extract_timer_pattern(timers_data, idx) red = timers_data["red_%d" % idx] green = timers_data["green_%d" % idx] blue = timers_data["blue_%d" % idx] timer = Timer( enabled=enabled, execution_time=time, pattern=pattern, red=red, green=green, blue=blue, ) timers.append(timer) return timers
(self) -> [<class 'sunix_ledstrip_controller_client.timer.Timer'>]
29,677
sunix_ledstrip_controller_client.controller
is_on
:return: True if the controller is turned on, false otherwise
def is_on(self) -> bool: """ :return: True if the controller is turned on, false otherwise """ return self._power_state is self.POWER_STATE_ON
(self) -> bool
29,678
sunix_ledstrip_controller_client.controller
set_brightness
Sets a specific brightness without changing the color. :param brightness: (0..255)
def set_brightness(self, brightness: int) -> None: """ Sets a specific brightness without changing the color. :param brightness: (0..255) """ new_rgbww = [] for color in self._rgbww: new_rgbww.append(color * (brightness / 255)) self.set_rgbww(new_rgbww[0], new_rgbww[1], new_rgbww[2], new_rgbww[3], new_rgbww[4])
(self, brightness: int) -> NoneType
29,679
sunix_ledstrip_controller_client.controller
set_custom_function
Sets a custom function on this controller :param color_values: a list of up to 16 color tuples of the form (red, green, blue) or (red, green, blue, unknown). I couldn't figure out what the last parameter is used for so the rgb is a shortcut. :param transition_type: the transition type between colors :param speed: function speed [0..255] 0 is slow, 255 is fast
def set_custom_function(self, color_values: [(int, int, int, int)], speed: int, transition_type: TransitionType = TransitionType.Gradual): """ Sets a custom function on this controller :param color_values: a list of up to 16 color tuples of the form (red, green, blue) or (red, green, blue, unknown). I couldn't figure out what the last parameter is used for so the rgb is a shortcut. :param transition_type: the transition type between colors :param speed: function speed [0..255] 0 is slow, 255 is fast """ self._api.set_custom_function(self._host, self._port, color_values, speed, transition_type) self.update_state()
(self, color_values: [(<class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>)], speed: int, transition_type: sunix_ledstrip_controller_client.packets.TransitionType = <TransitionType.Gradual: 58>)
29,680
sunix_ledstrip_controller_client.controller
set_function
Sets a function on the specified controller :param function_id: Function ID :param speed: function speed [0..255] 0 is slow, 255 is fast
def set_function(self, function_id: FunctionId, speed: int): """ Sets a function on the specified controller :param function_id: Function ID :param speed: function speed [0..255] 0 is slow, 255 is fast """ self._api.set_function(self._host, self._port, function_id, speed) self.update_state()
(self, function_id: sunix_ledstrip_controller_client.functions.FunctionId, speed: int)
29,681
sunix_ledstrip_controller_client.controller
set_rgb
Sets rgbw values for this controller. :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255)
def set_rgb(self, red: int, green: int, blue: int) -> None: """ Sets rgbw values for this controller. :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255) """ self._api.set_rgb(self._host, self._port, red, green, blue) self.update_state()
(self, red: int, green: int, blue: int) -> NoneType
29,682
sunix_ledstrip_controller_client.controller
set_rgbww
Sets rgbww values for this controller. :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255) :param warm_white: warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255)
def set_rgbww(self, red: int, green: int, blue: int, warm_white: int, cold_white: int) -> None: """ Sets rgbww values for this controller. :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255) :param warm_white: warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255) """ self._api.set_rgbww(self._host, self._port, red, green, blue, warm_white, cold_white) self.update_state()
(self, red: int, green: int, blue: int, warm_white: int, cold_white: int) -> NoneType
29,683
sunix_ledstrip_controller_client.controller
set_time
Sets the internal time of this controller :param date_time: the time to set
def set_time(self, date_time: datetime) -> None: """ Sets the internal time of this controller :param date_time: the time to set """ self._api.set_time(self._host, self._port, date_time)
(self, date_time: <module 'datetime' from '/usr/local/lib/python3.10/datetime.py'>) -> NoneType
29,684
sunix_ledstrip_controller_client.controller
set_ww
Sets warm white and cold white values for this controller. :param warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255)
def set_ww(self, warm_white: int, cold_white: int) -> None: """ Sets warm white and cold white values for this controller. :param warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255) """ self._api.set_ww(self._host, self._port, cold_white, warm_white) self.update_state()
(self, warm_white: int, cold_white: int) -> NoneType
29,685
sunix_ledstrip_controller_client.controller
turn_off
Turn on this controller
def turn_off(self) -> None: """ Turn on this controller """ self._api.turn_off(self._host, self._port) self.update_state()
(self) -> NoneType
29,686
sunix_ledstrip_controller_client.controller
turn_on
Turn on this controller
def turn_on(self) -> None: """ Turn on this controller """ self._api.turn_on(self._host, self._port) self.update_state()
(self) -> NoneType
29,687
sunix_ledstrip_controller_client.controller
update_state
Updates the state of this controller
def update_state(self): """ Updates the state of this controller """ state = self._api.get_state(self._host, self._port) # update the controller values from the response self._device_name = state["device_name"] self._power_state = state["power_status"] self._function = state["mode"] self._function_speed = state["speed"] self._rgbww = ( state["red"], state["green"], state["blue"], state["warm_white"], state["cold_white"] )
(self)
29,688
sunix_ledstrip_controller_client.functions
FunctionId
An enumeration.
class FunctionId(Enum): SEVEN_COLOR_CROSS_FADE = 0x25 RED_GRADUAL_CHANGE = 0x26 GREEN_GRADUAL_CHANGE = 0x27 BLUE_GRADUAL_CHANGE = 0x28 YELLOW_GRADUAL_CHANGE = 0x29 CYAN_GRADUAL_CHANGE = 0x2A PURPLE_GRADUAL_CHANGE = 0x2B WHITE_GRADUAL_CHANGE = 0x2C RED_GREEN_CROSS_FADE = 0x2D RED_BLUE_CROSS_FADE = 0x2E GREEN_BLUE_CROSS_FADE = 0x2F SEVEN_COLOR_STROBE_FLASH = 0x30 RED_STROBE_FLASH = 0x31 GREEN_STROBE_FLASH = 0x32 BLUE_STROBE_FLASH = 0x33 YELLOW_STROBE_FLASH = 0x34 CYAN_STROBE_FLASH = 0x35 PURPLE_STROBE_FLASH = 0x36 WHITE_STROBE_FLASH = 0x37 SEVEN_COLOR_JUMPING_CHANGE = 0x38 NO_FUNCTION = 0x61
(value, names=None, *, module=None, qualname=None, type=None, start=1)
29,689
sunix_ledstrip_controller_client.client
LEDStripControllerClient
This class is the main interface for controlling devices
class LEDStripControllerClient: """ This class is the main interface for controlling devices """ _discovery_port = 48899 _discovery_message = b'HF-A11ASSISTHREAD' def __init__(self): """ Creates a new client object """ def discover_controllers(self) -> [Controller]: """ Sends a broadcast message to the local network. Listening devices will respond to this broadcast with their self description :return: a list of devices """ discovered_controllers = [] # use discovery multiple times as controllers sometimes just don't respond for i in range(3): discovered_controllers = self.__merge_controllers( self._discover_controllers(), discovered_controllers) return discovered_controllers @staticmethod def __merge_controllers(new, old) -> [Controller]: merged = set(new) merged.update(old) return list(merged) def _discover_controllers(self) -> [Controller]: """ Internally used discovery method :return: list of discovered devices """ discovered_controllers = [] with socket.socket(AF_INET, SOCK_DGRAM) as cs: cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) # send a local broadcast via udp with a "magic packet" cs.sendto(self._discovery_message, ('255.255.255.255', self._discovery_port)) cs.setblocking(True) cs.settimeout(1) received_messages = [] try: while True: data, address = cs.recvfrom(4096) received_messages.append(data.decode()) except socket.timeout: if len(received_messages) <= 0: return [] for message in received_messages: try: controller = self._parse_discovery_response(message) discovered_controllers.append(controller) except: print("Error parsing discovery message: %s" % message) return None return discovered_controllers def _parse_discovery_response(self, message: str) -> Controller or None: # parse received message data = str.split(message, ",") # check validity if len(data) == 3: # extract data ip = data[0] hw_id = data[1] model = data[2] # create a Controller object representation return Controller(self, ip, Controller.DEFAULT_PORT, hw_id, model) def get_time(self, host: str, port: int) -> datetime: """ Receives the current time of the specified controller :param host: controller host address :param port: controller port :return: the current time of the controller """ from .packets.requests import GetTimeRequest from .packets.responses import GetTimeResponse request = GetTimeRequest() data = request.get_data() response_data = self._send_data(host, port, data, True) # parse and check validity of response data response = GetTimeResponse(response_data).get_response() return response def set_time(self, host: str, port: int, date_time: datetime) -> None: """ Sets the internal time of the controller :param host: controller host address :param port: controller port :param date_time: the time to set """ from .packets.requests import SetTimeRequest request = SetTimeRequest() data = request.get_data(date_time) self._send_data(host, port, data) def get_state(self, host: str, port: int) -> dict: """ Updates the state of the passed in controller :param host: controller host address :param port: controller port """ from .packets.requests import StatusRequest from .packets.responses import StatusResponse request = StatusRequest() data = request.get_data() response_data = self._send_data(host, port, data, True) # parse and check validity of response data response = StatusResponse(response_data).get_response() return response def turn_on(self, host: str, port: int) -> None: """ Turns on a controller :param host: controller host address :param port: controller port """ from .packets.requests import SetPowerRequest request = SetPowerRequest() data = request.get_data(True) self._send_data(host, port, data) def turn_off(self, host: str, port: int) -> None: """ Turns on a controller :param host: controller host address :param port: controller port """ from .packets.requests import SetPowerRequest request = SetPowerRequest() data = request.get_data(False) self._send_data(host, port, data) def set_rgbww(self, host: str, port: int, red: int, green: int, blue: int, warm_white: int, cold_white: int) -> None: """ Sets rgbww values for the specified controller. :param host: controller host address :param port: controller port :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255) :param warm_white: warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255) """ self._validate_color((red, green, blue, warm_white, cold_white), 5) from .packets.requests import UpdateColorRequest request = UpdateColorRequest() data = request.get_rgbww_data(red, green, blue, warm_white, cold_white) self._send_data(host, port, data) def set_rgb(self, host: str, port: int, red: int, green: int, blue: int) -> None: """ Sets rgbw values for the specified controller. :param host: controller host address :param port: controller port :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255) """ self._validate_color((red, green, blue), 3) from .packets.requests import UpdateColorRequest request = UpdateColorRequest() data = request.get_rgb_data(red, green, blue) self._send_data(host, port, data) def set_ww(self, host: str, port: int, warm_white: int, cold_white: int) -> None: """ Sets warm white and cold white values for the specified controller. :param host: controller host address :param port: controller port :param warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255) """ self._validate_color((warm_white, cold_white), 2) from .packets.requests import UpdateColorRequest request = UpdateColorRequest() data = request.get_ww_data(warm_white, cold_white) self._send_data(host, port, data) def get_function_list(self) -> [FunctionId]: """ :return: a list of all supported functions """ return list(FunctionId) def set_function(self, host: str, port: int, function_id: FunctionId, speed: int): """ Sets a function on the specified controller :param host: controller host address :param port: controller port :param function_id: Function ID :param speed: function speed [0..255] 0 is slow, 255 is fast """ from .packets.requests import SetFunctionRequest request = SetFunctionRequest() data = request.get_data(function_id, speed) self._send_data(host, port, data) def set_custom_function(self, host: str, port: int, color_values: [(int, int, int, int)], speed: int, transition_type: TransitionType = TransitionType.Gradual): """ Sets a custom function on the specified controller :param host: controller host address :param port: controller port :param color_values: a list of up to 16 color tuples of the form (red, green, blue) or (red, green, blue, unknown). I couldn't figure out what the last parameter is used for so the rgb is a shortcut. :param transition_type: the transition type between colors :param speed: function speed [0..255] 0 is slow, 255 is fast """ for color in color_values: self._validate_color(color, len(color)) from .packets.requests import SetCustomFunctionRequest request = SetCustomFunctionRequest() data = request.get_data(color_values, speed, transition_type) self._send_data(host, port, data) def get_timers(self, host: str, port: int) -> dict: """ Receives the current timer configurations of the specified controller :param host: controller host address :param port: controller port :return: the current timer configuration of the controller """ from .packets.requests import GetTimerRequest from .packets.responses import GetTimerResponse request = GetTimerRequest() data = request.get_data() response_data = self._send_data(host, port, data, True) # parse and check validity of response data response = GetTimerResponse(response_data).get_response() return response @staticmethod def _send_data(host: str, port: int, data, wait_for_response: bool = False) -> bytearray or None: """ Sends a binary data request to the specified host and port. :param host: destination host :param port: destination port :param data: the binary(!) data to send """ with socket.socket() as s: s.settimeout(1) s.connect((host, port)) s.send(data) if wait_for_response: s.setblocking(True) data = s.recv(2048) return data else: return None @staticmethod def _validate_color(color: (int, int, int), color_channels: int) -> None: """ Validates an int tuple that is meant to represent a color. If the color is valid this method will not do anything. There is no return value to check, the method will raise an Exception if necessary. :param color: the color tuple to validate :param color_channels: the expected amount of color channels in this color """ if len(color) != color_channels: raise ValueError( "Invalid amount of colors in color tuple. Expected " + str(color_channels) + ", got: " + str( len(color))) for color_channel in color: if color_channel < 0 or color_channel > 255: raise ValueError("Invalid color range! Expected 0-255, got: " + str(color_channel))
()
29,690
sunix_ledstrip_controller_client.client
__merge_controllers
null
@staticmethod def __merge_controllers(new, old) -> [Controller]: merged = set(new) merged.update(old) return list(merged)
(new, old) -> [<class 'sunix_ledstrip_controller_client.controller.Controller'>]
29,691
sunix_ledstrip_controller_client.client
__init__
Creates a new client object
def __init__(self): """ Creates a new client object """
(self)
29,692
sunix_ledstrip_controller_client.client
_discover_controllers
Internally used discovery method :return: list of discovered devices
def _discover_controllers(self) -> [Controller]: """ Internally used discovery method :return: list of discovered devices """ discovered_controllers = [] with socket.socket(AF_INET, SOCK_DGRAM) as cs: cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) # send a local broadcast via udp with a "magic packet" cs.sendto(self._discovery_message, ('255.255.255.255', self._discovery_port)) cs.setblocking(True) cs.settimeout(1) received_messages = [] try: while True: data, address = cs.recvfrom(4096) received_messages.append(data.decode()) except socket.timeout: if len(received_messages) <= 0: return [] for message in received_messages: try: controller = self._parse_discovery_response(message) discovered_controllers.append(controller) except: print("Error parsing discovery message: %s" % message) return None return discovered_controllers
(self) -> [<class 'sunix_ledstrip_controller_client.controller.Controller'>]
29,693
sunix_ledstrip_controller_client.client
_parse_discovery_response
null
def _parse_discovery_response(self, message: str) -> Controller or None: # parse received message data = str.split(message, ",") # check validity if len(data) == 3: # extract data ip = data[0] hw_id = data[1] model = data[2] # create a Controller object representation return Controller(self, ip, Controller.DEFAULT_PORT, hw_id, model)
(self, message: str) -> sunix_ledstrip_controller_client.controller.Controller
29,694
sunix_ledstrip_controller_client.client
_send_data
Sends a binary data request to the specified host and port. :param host: destination host :param port: destination port :param data: the binary(!) data to send
@staticmethod def _send_data(host: str, port: int, data, wait_for_response: bool = False) -> bytearray or None: """ Sends a binary data request to the specified host and port. :param host: destination host :param port: destination port :param data: the binary(!) data to send """ with socket.socket() as s: s.settimeout(1) s.connect((host, port)) s.send(data) if wait_for_response: s.setblocking(True) data = s.recv(2048) return data else: return None
(host: str, port: int, data, wait_for_response: bool = False) -> bytearray
29,695
sunix_ledstrip_controller_client.client
_validate_color
Validates an int tuple that is meant to represent a color. If the color is valid this method will not do anything. There is no return value to check, the method will raise an Exception if necessary. :param color: the color tuple to validate :param color_channels: the expected amount of color channels in this color
@staticmethod def _validate_color(color: (int, int, int), color_channels: int) -> None: """ Validates an int tuple that is meant to represent a color. If the color is valid this method will not do anything. There is no return value to check, the method will raise an Exception if necessary. :param color: the color tuple to validate :param color_channels: the expected amount of color channels in this color """ if len(color) != color_channels: raise ValueError( "Invalid amount of colors in color tuple. Expected " + str(color_channels) + ", got: " + str( len(color))) for color_channel in color: if color_channel < 0 or color_channel > 255: raise ValueError("Invalid color range! Expected 0-255, got: " + str(color_channel))
(color: (<class 'int'>, <class 'int'>, <class 'int'>), color_channels: int) -> NoneType
29,696
sunix_ledstrip_controller_client.client
discover_controllers
Sends a broadcast message to the local network. Listening devices will respond to this broadcast with their self description :return: a list of devices
def discover_controllers(self) -> [Controller]: """ Sends a broadcast message to the local network. Listening devices will respond to this broadcast with their self description :return: a list of devices """ discovered_controllers = [] # use discovery multiple times as controllers sometimes just don't respond for i in range(3): discovered_controllers = self.__merge_controllers( self._discover_controllers(), discovered_controllers) return discovered_controllers
(self) -> [<class 'sunix_ledstrip_controller_client.controller.Controller'>]
29,697
sunix_ledstrip_controller_client.client
get_function_list
:return: a list of all supported functions
def get_function_list(self) -> [FunctionId]: """ :return: a list of all supported functions """ return list(FunctionId)
(self) -> [<enum 'FunctionId'>]
29,698
sunix_ledstrip_controller_client.client
get_state
Updates the state of the passed in controller :param host: controller host address :param port: controller port
def get_state(self, host: str, port: int) -> dict: """ Updates the state of the passed in controller :param host: controller host address :param port: controller port """ from .packets.requests import StatusRequest from .packets.responses import StatusResponse request = StatusRequest() data = request.get_data() response_data = self._send_data(host, port, data, True) # parse and check validity of response data response = StatusResponse(response_data).get_response() return response
(self, host: str, port: int) -> dict
29,699
sunix_ledstrip_controller_client.client
get_time
Receives the current time of the specified controller :param host: controller host address :param port: controller port :return: the current time of the controller
def get_time(self, host: str, port: int) -> datetime: """ Receives the current time of the specified controller :param host: controller host address :param port: controller port :return: the current time of the controller """ from .packets.requests import GetTimeRequest from .packets.responses import GetTimeResponse request = GetTimeRequest() data = request.get_data() response_data = self._send_data(host, port, data, True) # parse and check validity of response data response = GetTimeResponse(response_data).get_response() return response
(self, host: str, port: int) -> <module 'datetime' from '/usr/local/lib/python3.10/datetime.py'>
29,700
sunix_ledstrip_controller_client.client
get_timers
Receives the current timer configurations of the specified controller :param host: controller host address :param port: controller port :return: the current timer configuration of the controller
def get_timers(self, host: str, port: int) -> dict: """ Receives the current timer configurations of the specified controller :param host: controller host address :param port: controller port :return: the current timer configuration of the controller """ from .packets.requests import GetTimerRequest from .packets.responses import GetTimerResponse request = GetTimerRequest() data = request.get_data() response_data = self._send_data(host, port, data, True) # parse and check validity of response data response = GetTimerResponse(response_data).get_response() return response
(self, host: str, port: int) -> dict
29,701
sunix_ledstrip_controller_client.client
set_custom_function
Sets a custom function on the specified controller :param host: controller host address :param port: controller port :param color_values: a list of up to 16 color tuples of the form (red, green, blue) or (red, green, blue, unknown). I couldn't figure out what the last parameter is used for so the rgb is a shortcut. :param transition_type: the transition type between colors :param speed: function speed [0..255] 0 is slow, 255 is fast
def set_custom_function(self, host: str, port: int, color_values: [(int, int, int, int)], speed: int, transition_type: TransitionType = TransitionType.Gradual): """ Sets a custom function on the specified controller :param host: controller host address :param port: controller port :param color_values: a list of up to 16 color tuples of the form (red, green, blue) or (red, green, blue, unknown). I couldn't figure out what the last parameter is used for so the rgb is a shortcut. :param transition_type: the transition type between colors :param speed: function speed [0..255] 0 is slow, 255 is fast """ for color in color_values: self._validate_color(color, len(color)) from .packets.requests import SetCustomFunctionRequest request = SetCustomFunctionRequest() data = request.get_data(color_values, speed, transition_type) self._send_data(host, port, data)
(self, host: str, port: int, color_values: [(<class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>)], speed: int, transition_type: sunix_ledstrip_controller_client.packets.TransitionType = <TransitionType.Gradual: 58>)
29,702
sunix_ledstrip_controller_client.client
set_function
Sets a function on the specified controller :param host: controller host address :param port: controller port :param function_id: Function ID :param speed: function speed [0..255] 0 is slow, 255 is fast
def set_function(self, host: str, port: int, function_id: FunctionId, speed: int): """ Sets a function on the specified controller :param host: controller host address :param port: controller port :param function_id: Function ID :param speed: function speed [0..255] 0 is slow, 255 is fast """ from .packets.requests import SetFunctionRequest request = SetFunctionRequest() data = request.get_data(function_id, speed) self._send_data(host, port, data)
(self, host: str, port: int, function_id: sunix_ledstrip_controller_client.functions.FunctionId, speed: int)
29,703
sunix_ledstrip_controller_client.client
set_rgb
Sets rgbw values for the specified controller. :param host: controller host address :param port: controller port :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255)
def set_rgb(self, host: str, port: int, red: int, green: int, blue: int) -> None: """ Sets rgbw values for the specified controller. :param host: controller host address :param port: controller port :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255) """ self._validate_color((red, green, blue), 3) from .packets.requests import UpdateColorRequest request = UpdateColorRequest() data = request.get_rgb_data(red, green, blue) self._send_data(host, port, data)
(self, host: str, port: int, red: int, green: int, blue: int) -> NoneType
29,704
sunix_ledstrip_controller_client.client
set_rgbww
Sets rgbww values for the specified controller. :param host: controller host address :param port: controller port :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255) :param warm_white: warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255)
def set_rgbww(self, host: str, port: int, red: int, green: int, blue: int, warm_white: int, cold_white: int) -> None: """ Sets rgbww values for the specified controller. :param host: controller host address :param port: controller port :param red: red intensity (0..255) :param green: green intensity (0..255) :param blue: blue intensity (0..255) :param warm_white: warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255) """ self._validate_color((red, green, blue, warm_white, cold_white), 5) from .packets.requests import UpdateColorRequest request = UpdateColorRequest() data = request.get_rgbww_data(red, green, blue, warm_white, cold_white) self._send_data(host, port, data)
(self, host: str, port: int, red: int, green: int, blue: int, warm_white: int, cold_white: int) -> NoneType
29,705
sunix_ledstrip_controller_client.client
set_time
Sets the internal time of the controller :param host: controller host address :param port: controller port :param date_time: the time to set
def set_time(self, host: str, port: int, date_time: datetime) -> None: """ Sets the internal time of the controller :param host: controller host address :param port: controller port :param date_time: the time to set """ from .packets.requests import SetTimeRequest request = SetTimeRequest() data = request.get_data(date_time) self._send_data(host, port, data)
(self, host: str, port: int, date_time: <module 'datetime' from '/usr/local/lib/python3.10/datetime.py'>) -> NoneType
29,706
sunix_ledstrip_controller_client.client
set_ww
Sets warm white and cold white values for the specified controller. :param host: controller host address :param port: controller port :param warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255)
def set_ww(self, host: str, port: int, warm_white: int, cold_white: int) -> None: """ Sets warm white and cold white values for the specified controller. :param host: controller host address :param port: controller port :param warm_white: warm white intensity (0..255) :param cold_white: cold white intensity (0..255) """ self._validate_color((warm_white, cold_white), 2) from .packets.requests import UpdateColorRequest request = UpdateColorRequest() data = request.get_ww_data(warm_white, cold_white) self._send_data(host, port, data)
(self, host: str, port: int, warm_white: int, cold_white: int) -> NoneType
29,707
sunix_ledstrip_controller_client.client
turn_off
Turns on a controller :param host: controller host address :param port: controller port
def turn_off(self, host: str, port: int) -> None: """ Turns on a controller :param host: controller host address :param port: controller port """ from .packets.requests import SetPowerRequest request = SetPowerRequest() data = request.get_data(False) self._send_data(host, port, data)
(self, host: str, port: int) -> NoneType
29,708
sunix_ledstrip_controller_client.client
turn_on
Turns on a controller :param host: controller host address :param port: controller port
def turn_on(self, host: str, port: int) -> None: """ Turns on a controller :param host: controller host address :param port: controller port """ from .packets.requests import SetPowerRequest request = SetPowerRequest() data = request.get_data(True) self._send_data(host, port, data)
(self, host: str, port: int) -> NoneType
29,709
sunix_ledstrip_controller_client.packets
TransitionType
The transition type between colors of a custom function
class TransitionType(Enum): """ The transition type between colors of a custom function """ Gradual = 0x3A Jumping = 0x3B Strobe = 0x3C
(value, names=None, *, module=None, qualname=None, type=None, start=1)
29,717
alarmageddon.run
construct_publishers
Construct the built-in publishers. :param config: Config object to construct the publishers from.
def construct_publishers(config): """Construct the built-in publishers. :param config: Config object to construct the publishers from. """ environment = config.environment_name() env_config = config.environment_config publishers = [] try: publishers.append( hipchat.HipChatPublisher( api_end_point = env_config["hipchat_host"], api_token = env_config["hipchat_token"], environment = environment, room_name = env_config["hipchat_room"], priority_threshold = Priority.NORMAL)) except KeyError: pass try: publishers.append(pagerduty.PagerDutyPublisher( api_end_point = env_config["pagerduty_host"], api_key = env_config["pagerduty_token"], environment = environment, priority_threshold = Priority.CRITICAL)) except KeyError: pass try: publishers.append(graphite.GraphitePublisher( host = env_config["graphite_host"], port = env_config["graphite_port"], environment = environment, priority_threshold = Priority.LOW)) except KeyError: pass return publishers
(config)
29,718
alarmageddon.run
load_config
Helper method for loading a :py:class:`~alarmageddon.config.Config` :param config_path: Path to the JSON configuration file. :param environment_name: The config environment to run Alarmageddon in.
def load_config(config_path, environment_name): """Helper method for loading a :py:class:`~alarmageddon.config.Config` :param config_path: Path to the JSON configuration file. :param environment_name: The config environment to run Alarmageddon in. """ return Config.from_file(config_path, environment_name)
(config_path, environment_name)
29,723
alarmageddon.run
run_tests
Main entry point into Alarmageddon. Run the given validations and report them to given publishers. Either both `config_path` and `environment_name` should not be None, or `config` should not be None. :param validations: List of :py:class:`~.validation.Validation` objects that Alarmageddon will perform. :param publishers: List of :py:class:`~.publisher.Publisher` objects that Alarmageddon will publish validation results to. :param dry_run: When True, will prevent Alarmageddon from performing validations or publishing results, and instead will print which validations will be published by which publishers upon failure. :param processes: The number of worker processes to spawn. :param print_banner: When True, print the Alarmageddon banner. :timeout: If a validation runs for longer than this number of seconds, Alarmageddon will kill the process running it. .. deprecated:: 1.0.0 These parameters are no longer used: *config_path*, *environment_name*, *config*. Configuration happens when constructing publishers instead.
def run_tests(validations, publishers=None, config_path=None, environment_name=None, config=None, dry_run=False, processes=1, print_banner=True, timeout=60, timeout_retries=2): """Main entry point into Alarmageddon. Run the given validations and report them to given publishers. Either both `config_path` and `environment_name` should not be None, or `config` should not be None. :param validations: List of :py:class:`~.validation.Validation` objects that Alarmageddon will perform. :param publishers: List of :py:class:`~.publisher.Publisher` objects that Alarmageddon will publish validation results to. :param dry_run: When True, will prevent Alarmageddon from performing validations or publishing results, and instead will print which validations will be published by which publishers upon failure. :param processes: The number of worker processes to spawn. :param print_banner: When True, print the Alarmageddon banner. :timeout: If a validation runs for longer than this number of seconds, Alarmageddon will kill the process running it. .. deprecated:: 1.0.0 These parameters are no longer used: *config_path*, *environment_name*, *config*. Configuration happens when constructing publishers instead. """ if config is not None: warnings.warn("config keyword argument in run_tests is deprecated" + " and has no effect.", DeprecationWarning) if config_path is not None: warnings.warn("config_path keyword argument in run_tests is" + " deprecated and has no effect.", DeprecationWarning) if environment_name is not None: warnings.warn("environment_name keyword argument in run_tests is " + "deprecated and has no effect.", DeprecationWarning) publishers = publishers or [] publishers.append(junit.JUnitPublisher("results.xml")) # We assume that if one is calling run_tests one actually wanted # to run some tests, not just fail silently if not validations: raise ValueError("run_tests expected non-empty list of validations," + "got {} instead".format(validations)) if print_banner: banner.print_banner(True) #always dry run. this will catch weird issues with enrichment do_dry_run(validations, publishers) if not dry_run: # run all of the tests _run_validations(validations, Reporter(publishers), processes, timeout, timeout_retries)
(validations, publishers=None, config_path=None, environment_name=None, config=None, dry_run=False, processes=1, print_banner=True, timeout=60, timeout_retries=2)
29,736
allstar.star
Star
__all__ list manager Examples: >>> from allstar import Stard Attributes: _exports: Current __all__ names list _module: Module reference
class Star: """__all__ list manager Examples: >>> from allstar import Stard Attributes: _exports: Current __all__ names list _module: Module reference """ def __init__(self, module_name: 'str'): """ Args: module_name: Name of the module to manage Raises: AssertionError: if the arguments are not of the correct type ModuleNotFoundError: if the module is not found in sys.modules """ assert isinstance(module_name, str), 'module_name must be a string' # set defaults self._exports = [] self._module = modules.get(module_name) if not self._module: raise ModuleNotFoundError(f'{module_name} module not found') # merge current names and set the list reference if hasattr(self._module, '__all__') and \ is_iterable(self._module.__all__): names = self._clean_names_iterable(self._module.__all__) self._exports.extend(names) # use the manager reference self._module.__all__ = self._exports def __contains__(self, item): if not isinstance(item, str): return False return item in self._exports def __iter__(self): return iter(self._exports) def __len__(self): return len(self._exports) def __repr__(self): return repr(self._exports) def __str__(self): return str(self._exports) def _store(self, name: 'str'): """Save a module's member name to the __all__ list Args: name: Name of the member to add to the __all__ list """ assert isinstance(name, str), 'name must be a string' if name not in self._exports: self._exports.append(name) def _clean_name(self, item: 'Any') -> 'str': """Validate and clean the name of an item Args: item: Item to validate and clean Returns: The name of the item Raises: TypeError: if the item is not a string or an object with a __name__ attribute AttributeError: if the item is not an attribute of the module """ if isinstance(item, str): name = item elif hasattr(item, '__name__'): name = item.__name__ else: raise TypeError( 'item must be a string or an object with a __name__ attribute') if not hasattr(self._module, name): raise AttributeError( f'{item} is not an attribute of {self._module.__name__}') return name def _clean_names_iterable(self, iterable: 'Iterable') -> 'set': """Merge a list of names to the __all__ list Args: iterable: Iterable of names to merge Raises: AssertionError: if the argument is not an Iterable """ assert is_iterable(iterable), 'iterable must be an Iterable' names_set = set() for item in iterable: names_set.add(self._clean_name(item)) return names_set def _check_reference(self): """Check if the __all__ reference is the manager's reference. If not, merge the data and set the manager's reference. """ if self._module.__all__ is not self._exports: self._module.__all__ = self._exports def _merge(self, iterable: 'Iterable'): """Merge a list of names to the __all__ list Args: iterable: Iterable of names to merge """ names = self._clean_names_iterable(iterable) for name in names: self._store(name) def sign(self, item: 'Callable'): """Decorator to add an object to the __all__ list Examples: # with a class >>> star = Star() >>> @star.sign ... class Example: ... pass >>> __all__ ['Example'] # With a function >>> star = Star() >>> @star.sign ... def example(): ... pass >>> __all__ ['example'] Args: item: Object to add to the exports list Returns: The same object passed as argument Raises: TypeError: if item is not callable AttributeError: if item has no __name__ attribute """ if not callable(item): raise TypeError('item must be callable') if not hasattr(self._module, item.__name__): raise AttributeError( f'{item} is not an attribute of {self._module.__name__}') self._store(item.__name__) self._check_reference() return item def include(self, item: 'Union[str, Callable]'): """Add an object to the __all__ list Examples: >>> star = Star() >>> star.include('Example1') # Example1 is a string >>> star.include(example2) # example2 is a reference >>> __all__ ['Example1', 'example2'] Args: item: Object to add to the exports list """ self._store(self._clean_name(item)) self._check_reference() def include_all(self, iterable: 'Iterable'): """Merge the names contained in an iterable to the __all__ list Examples: >>> star = Star() >>> star.include_all(['Example1', 'example2']) >>> __all__ ['Example1', 'example2'] Args: iterable: Iterable of names to merge Raises: TypeError: if the argument is not an Iterable """ if not is_iterable(iterable): raise TypeError( f'iterable must be an Iterable, not {type(iterable)}') self._merge(iterable) self._check_reference() def freeze(self): """Transform the __all__ list into a tuple Examples: >>> exports = Exports() >>> exports.freeze() >>> __all__ () """ self._module.__all__ = tuple(self._exports) def empty(self): """Create an empty exports list Examples: >>> exports = Exports() >>> exports.empty() >>> __all__ [] """ self._exports.clear() self._module.__all__ = self._exports def commit(self): """Commit the changes to the __all__ list if it's necessary """ self._check_reference()
(module_name: 'str')
29,737
allstar.star
__contains__
null
def __contains__(self, item): if not isinstance(item, str): return False return item in self._exports
(self, item)
29,738
allstar.star
__init__
Args: module_name: Name of the module to manage Raises: AssertionError: if the arguments are not of the correct type ModuleNotFoundError: if the module is not found in sys.modules
def __init__(self, module_name: 'str'): """ Args: module_name: Name of the module to manage Raises: AssertionError: if the arguments are not of the correct type ModuleNotFoundError: if the module is not found in sys.modules """ assert isinstance(module_name, str), 'module_name must be a string' # set defaults self._exports = [] self._module = modules.get(module_name) if not self._module: raise ModuleNotFoundError(f'{module_name} module not found') # merge current names and set the list reference if hasattr(self._module, '__all__') and \ is_iterable(self._module.__all__): names = self._clean_names_iterable(self._module.__all__) self._exports.extend(names) # use the manager reference self._module.__all__ = self._exports
(self, module_name: str)
29,739
allstar.star
__iter__
null
def __iter__(self): return iter(self._exports)
(self)
29,740
allstar.star
__len__
null
def __len__(self): return len(self._exports)
(self)
29,741
allstar.star
__repr__
null
def __repr__(self): return repr(self._exports)
(self)
29,742
allstar.star
__str__
null
def __str__(self): return str(self._exports)
(self)
29,743
allstar.star
_check_reference
Check if the __all__ reference is the manager's reference. If not, merge the data and set the manager's reference.
def _check_reference(self): """Check if the __all__ reference is the manager's reference. If not, merge the data and set the manager's reference. """ if self._module.__all__ is not self._exports: self._module.__all__ = self._exports
(self)
29,744
allstar.star
_clean_name
Validate and clean the name of an item Args: item: Item to validate and clean Returns: The name of the item Raises: TypeError: if the item is not a string or an object with a __name__ attribute AttributeError: if the item is not an attribute of the module
def _clean_name(self, item: 'Any') -> 'str': """Validate and clean the name of an item Args: item: Item to validate and clean Returns: The name of the item Raises: TypeError: if the item is not a string or an object with a __name__ attribute AttributeError: if the item is not an attribute of the module """ if isinstance(item, str): name = item elif hasattr(item, '__name__'): name = item.__name__ else: raise TypeError( 'item must be a string or an object with a __name__ attribute') if not hasattr(self._module, name): raise AttributeError( f'{item} is not an attribute of {self._module.__name__}') return name
(self, item: 'Any') -> 'str'
29,745
allstar.star
_clean_names_iterable
Merge a list of names to the __all__ list Args: iterable: Iterable of names to merge Raises: AssertionError: if the argument is not an Iterable
def _clean_names_iterable(self, iterable: 'Iterable') -> 'set': """Merge a list of names to the __all__ list Args: iterable: Iterable of names to merge Raises: AssertionError: if the argument is not an Iterable """ assert is_iterable(iterable), 'iterable must be an Iterable' names_set = set() for item in iterable: names_set.add(self._clean_name(item)) return names_set
(self, iterable: 'Iterable') -> 'set'
29,746
allstar.star
_merge
Merge a list of names to the __all__ list Args: iterable: Iterable of names to merge
def _merge(self, iterable: 'Iterable'): """Merge a list of names to the __all__ list Args: iterable: Iterable of names to merge """ names = self._clean_names_iterable(iterable) for name in names: self._store(name)
(self, iterable: 'Iterable')
29,747
allstar.star
_store
Save a module's member name to the __all__ list Args: name: Name of the member to add to the __all__ list
def _store(self, name: 'str'): """Save a module's member name to the __all__ list Args: name: Name of the member to add to the __all__ list """ assert isinstance(name, str), 'name must be a string' if name not in self._exports: self._exports.append(name)
(self, name: str)
29,748
allstar.star
commit
Commit the changes to the __all__ list if it's necessary
def commit(self): """Commit the changes to the __all__ list if it's necessary """ self._check_reference()
(self)
29,749
allstar.star
empty
Create an empty exports list Examples: >>> exports = Exports() >>> exports.empty() >>> __all__ []
def empty(self): """Create an empty exports list Examples: >>> exports = Exports() >>> exports.empty() >>> __all__ [] """ self._exports.clear() self._module.__all__ = self._exports
(self)
29,750
allstar.star
freeze
Transform the __all__ list into a tuple Examples: >>> exports = Exports() >>> exports.freeze() >>> __all__ ()
def freeze(self): """Transform the __all__ list into a tuple Examples: >>> exports = Exports() >>> exports.freeze() >>> __all__ () """ self._module.__all__ = tuple(self._exports)
(self)
29,751
allstar.star
include
Add an object to the __all__ list Examples: >>> star = Star() >>> star.include('Example1') # Example1 is a string >>> star.include(example2) # example2 is a reference >>> __all__ ['Example1', 'example2'] Args: item: Object to add to the exports list
def include(self, item: 'Union[str, Callable]'): """Add an object to the __all__ list Examples: >>> star = Star() >>> star.include('Example1') # Example1 is a string >>> star.include(example2) # example2 is a reference >>> __all__ ['Example1', 'example2'] Args: item: Object to add to the exports list """ self._store(self._clean_name(item)) self._check_reference()
(self, item: 'Union[str, Callable]')
29,752
allstar.star
include_all
Merge the names contained in an iterable to the __all__ list Examples: >>> star = Star() >>> star.include_all(['Example1', 'example2']) >>> __all__ ['Example1', 'example2'] Args: iterable: Iterable of names to merge Raises: TypeError: if the argument is not an Iterable
def include_all(self, iterable: 'Iterable'): """Merge the names contained in an iterable to the __all__ list Examples: >>> star = Star() >>> star.include_all(['Example1', 'example2']) >>> __all__ ['Example1', 'example2'] Args: iterable: Iterable of names to merge Raises: TypeError: if the argument is not an Iterable """ if not is_iterable(iterable): raise TypeError( f'iterable must be an Iterable, not {type(iterable)}') self._merge(iterable) self._check_reference()
(self, iterable: 'Iterable')
29,753
allstar.star
sign
Decorator to add an object to the __all__ list Examples: # with a class >>> star = Star() >>> @star.sign ... class Example: ... pass >>> __all__ ['Example'] # With a function >>> star = Star() >>> @star.sign ... def example(): ... pass >>> __all__ ['example'] Args: item: Object to add to the exports list Returns: The same object passed as argument Raises: TypeError: if item is not callable AttributeError: if item has no __name__ attribute
def sign(self, item: 'Callable'): """Decorator to add an object to the __all__ list Examples: # with a class >>> star = Star() >>> @star.sign ... class Example: ... pass >>> __all__ ['Example'] # With a function >>> star = Star() >>> @star.sign ... def example(): ... pass >>> __all__ ['example'] Args: item: Object to add to the exports list Returns: The same object passed as argument Raises: TypeError: if item is not callable AttributeError: if item has no __name__ attribute """ if not callable(item): raise TypeError('item must be callable') if not hasattr(self._module, item.__name__): raise AttributeError( f'{item} is not an attribute of {self._module.__name__}') self._store(item.__name__) self._check_reference() return item
(self, item: 'Callable')
29,755
isbnlib._core
ean13
Transform an `isbnlike` string in an EAN number (canonical ISBN-13).
def ean13(isbnlike): """Transform an `isbnlike` string in an EAN number (canonical ISBN-13).""" ib = canonical(isbnlike) if len(ib) == 13: return ib if is_isbn13(ib) else '' if len(ib) == 10: return to_isbn13(ib) if is_isbn10(ib) else '' return ''
(isbnlike)
29,758
isbnlib._exceptions
ISBNLibException
Base class for isbnlib exceptions. This exception should not be raised directly, only subclasses of this exception should be used!
class ISBNLibException(Exception): """Base class for isbnlib exceptions. This exception should not be raised directly, only subclasses of this exception should be used! """ def __str__(self): """Print message.""" return getattr(self, 'message', '') # pragma: no cover
null
29,759
isbnlib._exceptions
__str__
Print message.
def __str__(self): """Print message.""" return getattr(self, 'message', '') # pragma: no cover
(self)
29,760
isbnlib._isbn
Isbn
Class for ISBN objects.
class Isbn(object): """Class for ISBN objects.""" def __init__(self, isbnlike): self.ean13 = EAN13(isbnlike) if not self.ean13: LOGGER.debug('error: %s is not a valid ISBN', isbnlike) raise NotValidISBNError(isbnlike) self.canonical = canonical(isbnlike) self.isbn13 = mask(self.ean13) or self.ean13 self.isbn10 = mask(to_isbn10(self.ean13)) or to_isbn10(self.ean13) self.doi = doi(self.ean13) self.info = info(self.ean13) self.issued = '-' in self.isbn13 def __str__(self): return str(vars(self)) def __repr__(self): return self.__str__()
(isbnlike)
29,761
isbnlib._isbn
__init__
null
def __init__(self, isbnlike): self.ean13 = EAN13(isbnlike) if not self.ean13: LOGGER.debug('error: %s is not a valid ISBN', isbnlike) raise NotValidISBNError(isbnlike) self.canonical = canonical(isbnlike) self.isbn13 = mask(self.ean13) or self.ean13 self.isbn10 = mask(to_isbn10(self.ean13)) or to_isbn10(self.ean13) self.doi = doi(self.ean13) self.info = info(self.ean13) self.issued = '-' in self.isbn13
(self, isbnlike)
29,762
isbnlib._isbn
__repr__
null
def __repr__(self): return self.__str__()
(self)
29,763
isbnlib._isbn
__str__
null
def __str__(self): return str(vars(self))
(self)
29,764
isbnlib._exceptions
NotRecognizedServiceError
Exception raised when the service is not in config.py.
class NotRecognizedServiceError(ISBNLibException): """Exception raised when the service is not in config.py.""" def __init__(self, service): """Define message.""" self.message = '(%s) is not a recognized service' % service
(service)
29,765
isbnlib._exceptions
__init__
Define message.
def __init__(self, service): """Define message.""" self.message = '(%s) is not a recognized service' % service
(self, service)
29,767
isbnlib._exceptions
NotValidDefaultFormatterError
Exception raised when the formatter is not valid for default.
class NotValidDefaultFormatterError(ISBNLibException): """Exception raised when the formatter is not valid for default.""" def __init__(self, formatter): """Define message.""" self.message = '(%s) is not a valid default formatter' % formatter
(formatter)
29,768
isbnlib._exceptions
__init__
Define message.
def __init__(self, formatter): """Define message.""" self.message = '(%s) is not a valid default formatter' % formatter
(self, formatter)
29,770
isbnlib._exceptions
NotValidDefaultServiceError
Exception raised when the service is not valid for default.
class NotValidDefaultServiceError(ISBNLibException): """Exception raised when the service is not valid for default.""" def __init__(self, service): """Define message.""" self.message = '(%s) is not a valid default service' % service
(service)
29,771
isbnlib._exceptions
__init__
Define message.
def __init__(self, service): """Define message.""" self.message = '(%s) is not a valid default service' % service
(self, service)
29,773
isbnlib._exceptions
NotValidISBNError
Exception raised when the ISBN is not valid.
class NotValidISBNError(ISBNLibException): """Exception raised when the ISBN is not valid.""" def __init__(self, isbnlike): """Define message.""" self.message = '(%s) is not a valid ISBN' % isbnlike
(isbnlike)
29,774
isbnlib._exceptions
__init__
Define message.
def __init__(self, isbnlike): """Define message.""" self.message = '(%s) is not a valid ISBN' % isbnlike
(self, isbnlike)
29,776
isbnlib._exceptions
PluginNotLoadedError
Exception raised when the plugin's loader doesn't load the plugin. TODO: Delete this in version 4?
class PluginNotLoadedError(ISBNLibException): # pragma: no cover """Exception raised when the plugin's loader doesn't load the plugin. TODO: Delete this in version 4? """ def __init__(self, path): """Define message.""" self.message = "plugin (%s) wasn't loaded" % path
(path)
29,777
isbnlib._exceptions
__init__
Define message.
def __init__(self, path): """Define message.""" self.message = "plugin (%s) wasn't loaded" % path
(self, path)
29,799
isbnlib._core
canonical
Keep only numbers and X.
def canonical(isbnlike): """Keep only numbers and X.""" numb = [c for c in isbnlike if c in '0123456789Xx'] if numb and numb[-1] == 'x': numb[-1] = 'X' isbn = ''.join(numb) # Filter some special cases if (isbn and len(isbn) not in (10, 13) or isbn in ('0000000000', '0000000000000', '000000000X') or isbn.find('X') not in (9, -1) or isbn.find('x') != -1): return '' return isbn
(isbnlike)
29,800
isbnlib._core
check_digit10
Check sum ISBN-10.
def check_digit10(firstninedigits): """Check sum ISBN-10.""" # minimum checks if len(firstninedigits) != 9: return '' try: int(firstninedigits) except ValueError: # pragma: no cover return '' # checksum val = sum( (i + 2) * int(x) for i, x in enumerate(reversed(firstninedigits))) remainder = int(val % 11) if remainder == 0: tenthdigit = 0 else: tenthdigit = 11 - remainder if tenthdigit == 10: tenthdigit = 'X' return str(tenthdigit)
(firstninedigits)
29,801
isbnlib._core
check_digit13
Check sum ISBN-13.
def check_digit13(firsttwelvedigits): """Check sum ISBN-13.""" # minimum checks if len(firsttwelvedigits) != 12: return '' try: int(firsttwelvedigits) except ValueError: # pragma: no cover return '' # checksum val = sum( (i % 2 * 2 + 1) * int(x) for i, x in enumerate(firsttwelvedigits)) thirteenthdigit = 10 - int(val % 10) if thirteenthdigit == 10: thirteenthdigit = '0' return str(thirteenthdigit)
(firsttwelvedigits)
29,802
isbnlib._oclc
query_classify
Query the classify.oclc service for classifiers.
# -*- coding: utf-8 -*- """Query the 'classify.oclc.org' service for classifiers.""" import logging import re from .dev import cache from .dev._bouth23 import u from .dev.webquery import query as wquery UA = 'isbnlib (gzip)' SERVICE_URL = 'http://classify.oclc.org/classify2/Classify?isbn={isbn}&maxRecs=1' LOGGER = logging.getLogger(__name__) RE_OWI = re.compile(r'owi="(.*?)"', re.I | re.M | re.S) RE_OCLC = re.compile(r'oclc="(.*?)"', re.I | re.M | re.S) RE_DDC = re.compile(r'<ddc>(.*?)</ddc>', re.I | re.M | re.S) RE_LCC = re.compile(r'<lcc>(.*?)</lcc>', re.I | re.M | re.S) RE_NSFA = re.compile(r'nsfa="(.*?)"', re.I | re.M | re.S) RE_SFA = re.compile(r' sfa="(.*?)"', re.I | re.M | re.S) RE_HEADINGS = re.compile(r'<headings>(.*?)</headings>', re.I | re.M | re.S) RE_FLDS = re.compile(r' ident="(.*?)"', re.I | re.M | re.S) RE_VALS = re.compile(r'fast">(.*?)</heading>', re.I | re.M | re.S) def data_checker(xml): """Check the response from the service.""" if not xml: LOGGER.debug("The service 'oclc' is temporarily down!") return False if 'response code="102"' in xml: LOGGER.debug("The service 'oclc' is temporarily very slow!") return False return True
(isbn)
29,803
isbnlib._core
clean
Clean ISBN (only legal characters).
def clean(isbnlike): """Clean ISBN (only legal characters).""" cisbn = [c for c in isbnlike if c in LEGAL] buf = re.sub(r'\s*-\s*', '-', ''.join(cisbn)) return re.sub(r'\s+', ' ', buf).strip()
(isbnlike)
29,805
isbnlib._ext
cover
Get the img urls of the cover of the ISBN.
def cover(isbn): """Get the img urls of the cover of the ISBN.""" isbn = EAN13(isbn) return gcover(isbn) if isbn else {}
(isbn)
29,806
isbnlib._ext
desc
Return a descripion of the ISBN.
def desc(isbn): """Return a descripion of the ISBN.""" isbn = EAN13(isbn) return goo_desc(isbn) if isbn else ''
(isbn)
29,808
isbnlib._ext
doi
Return a DOI's ISBN-A from a ISBN-13.
def doi(isbn): """Return a DOI's ISBN-A from a ISBN-13.""" try: value = '10.%s.%s%s/%s%s' % tuple(msk(EAN13(isbn), '-').split('-')) except TypeError: return '' return value
(isbn)
29,809
isbnlib._doitotex
doi2tex
Get the bibtex ref for doi.
# -*- coding: utf-8 -*- """Return metadata, of a given DOI, formatted as BibTeX.""" import logging from .dev import cache from .dev.webservice import query LOGGER = logging.getLogger(__name__) URL = 'http://dx.doi.org/{DOI}' UA = 'isbnlib (gzip)' @cache def doi2tex(doi): """Get the bibtex ref for doi.""" data = query( URL.format(DOI=doi), user_agent=UA, appheaders={ 'Accept': 'application/x-bibtex; charset=utf-8', }, ) # noqa pragma: no cover if not data: # pragma: no cover LOGGER.warning('no data return for doi: %s', doi) return data if data else None # pragma: no cover
(doi)
29,811
isbnlib._ext
editions
Return the list of ISBNs of editions related with this ISBN. 'service' can have the values: 'any', 'merge' (default), 'openl' and 'thingl'
def editions(isbn, service='merge'): """Return the list of ISBNs of editions related with this ISBN. 'service' can have the values: 'any', 'merge' (default), 'openl' and 'thingl' """ return eds(isbn, service)
(isbn, service='merge')
29,812
isbnlib._core
get_canonical_isbn
Extract ISBNs and transform them to the canonical form. output: isbn10 isbn13 bouth (default)
def get_canonical_isbn(isbnlike, output='bouth'): """Extract ISBNs and transform them to the canonical form. output: isbn10 isbn13 bouth (default) """ if output not in ('bouth', 'isbn10', 'isbn13'): # pragma: no cover LOGGER.error('output as no option %s', output) return '' regex = RE_NORMAL match = regex.search(isbnlike) if match: # Get only canonical characters cisbn = canonical(match.group()) if not cisbn: return '' # Split into a list chars = list(cisbn) # Remove the last digit from `chars` and assign it to `last` last = chars.pop() buf = ''.join(chars) if len(chars) == 9: # Compute the ISBN-10 checksum digit check = check_digit10(buf) else: # Compute the ISBN-13 checksum digit check = check_digit13(buf) # If checksum OK return a `canonical` ISBN if str(check) == last: if output == 'bouth': return cisbn if output == 'isbn10': return cisbn if len(cisbn) == 10 else to_isbn10(cisbn) return to_isbn13(cisbn) if len(cisbn) == 10 else cisbn return ''
(isbnlike, output='bouth')