How to use the pyuavcan.dsdl.get_model function in pyuavcan

To help you get started, we’ve selected a few pyuavcan examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github UAVCAN / pyuavcan / tests / dsdl / _constants.py View on Github external
def _unittest_slow_constants(generated_packages: typing.List[pyuavcan.dsdl.GeneratedPackageInfo]) -> None:
    for info in generated_packages:
        for model in _util.expand_service_types(info.models, keep_services=True):
            dtype = pyuavcan.dsdl.get_class(model)
            for c in model.constants:
                if isinstance(c.data_type, pydsdl.PrimitiveType):  # pragma: no branch
                    reference = c.value
                    generated = pyuavcan.dsdl.get_attribute(dtype, c.name)
                    assert isinstance(reference, pydsdl.Primitive)
                    assert reference.native_value == pytest.approx(generated), \
                        'The generated constant does not compare equal against the DSDL source'
            if issubclass(dtype, pyuavcan.dsdl.FixedPortObject):
                assert issubclass(dtype, pyuavcan.dsdl.CompositeObject) \
                    and issubclass(dtype, pyuavcan.dsdl.FixedPortObject)
                assert pyuavcan.dsdl.get_fixed_port_id(dtype) == pyuavcan.dsdl.get_model(dtype).fixed_port_id
github UAVCAN / pyuavcan / tests / dsdl / _random.py View on Github external
ts = time.process_time()
    chunks = list(pyuavcan.dsdl.serialize(obj))         # GC must be disabled while we're in the timed context
    ser_sample = time.process_time() - ts

    ts = time.process_time()
    d = pyuavcan.dsdl.deserialize(type(obj), chunks)    # GC must be disabled while we're in the timed context
    des_sample = time.process_time() - ts

    gc.enable()

    assert d is not None
    assert type(obj) is type(d)
    assert pyuavcan.dsdl.get_model(obj) == pyuavcan.dsdl.get_model(d)

    if not _util.are_close(pyuavcan.dsdl.get_model(obj), obj, d):  # pragma: no cover
        assert False, f'{obj} != {d}; sr: {bytes().join(chunks).hex()}'  # Branched for performance reasons

    # Similar floats may produce drastically different string representations, so if there is at least one float inside,
    # we skip the string representation equality check.
    if pydsdl.FloatType.__name__ not in repr(pyuavcan.dsdl.get_model(d)):
        assert str(obj) == str(d)
        assert repr(obj) == repr(d)

    return ser_sample, des_sample
github UAVCAN / pyuavcan / tests / dsdl / _util.py View on Github external
def are_close(model: pydsdl.SerializableType, a: typing.Any, b: typing.Any) -> bool:
    """
    If you ever decided to copy-paste this test function into a production application,
    beware that it evaluates (NaN == NaN) as True. This is what we want when testing,
    but this is not what most real systems expect.
    """
    if a is None or b is None:  # These occur, for example, in unions
        return (a is None) == (b is None)

    elif isinstance(model, pydsdl.CompositeType):
        if type(a) != type(b):  # pragma: no cover
            return False
        for f in pyuavcan.dsdl.get_model(a).fields_except_padding:  # pragma: no cover
            if not are_close(f.data_type,
                             pyuavcan.dsdl.get_attribute(a, f.name),
                             pyuavcan.dsdl.get_attribute(b, f.name)):
                return False
        return True                 # Empty objects of same type compare equal

    elif isinstance(model, pydsdl.ArrayType):
        if len(a) != len(b) or a.dtype != b.dtype:  # pragma: no cover
            return False
        if isinstance(model.element_type, pydsdl.PrimitiveType):
            return bool(numpy.allclose(a, b, equal_nan=True))  # Speedup for large arrays like images or point clouds
        else:
            return all(itertools.starmap(functools.partial(are_close, model.element_type), zip(a, b)))

    elif isinstance(model, pydsdl.FloatType):
        t = {
github UAVCAN / pyuavcan / pyuavcan / application / plug_and_play.py View on Github external
import abc
import typing
import random
import asyncio
import pathlib
import logging
import sqlite3
from uavcan.pnp import NodeIDAllocationData_1_0 as NodeIDAllocationData_1
from uavcan.pnp import NodeIDAllocationData_2_0 as NodeIDAllocationData_2
from uavcan.node import ID_1_0 as ID
import pyuavcan


_PSEUDO_UNIQUE_ID_MASK = \
    2 ** list(pyuavcan.dsdl.get_model(NodeIDAllocationData_1)['unique_id_hash'].data_type.bit_length_set)[0] - 1

_NODE_ID_MASK = 2 ** max(pyuavcan.dsdl.get_model(ID)['value'].data_type.bit_length_set) - 1

_UNIQUE_ID_SIZE_BYTES = 16

_NUM_RESERVED_TOP_NODE_IDS = 2

_DB_DEFAULT_LOCATION = ':memory:'
_DB_TIMEOUT = 0.1


_logger = logging.getLogger(__name__)


class Allocatee:
    """
github UAVCAN / pyuavcan / pyuavcan / application / heartbeat_publisher.py View on Github external
class Mode(enum.IntEnum):
    """
    Mirrors the mode enumeration defined in ``uavcan.node.Heartbeat``.
    When enumerations are natively supported in DSDL, this will be replaced with an alias.
    """
    OPERATIONAL     = Heartbeat.MODE_OPERATIONAL
    INITIALIZATION  = Heartbeat.MODE_INITIALIZATION
    MAINTENANCE     = Heartbeat.MODE_MAINTENANCE
    SOFTWARE_UPDATE = Heartbeat.MODE_SOFTWARE_UPDATE
    OFFLINE         = Heartbeat.MODE_OFFLINE


VENDOR_SPECIFIC_STATUS_CODE_MASK = \
    2 ** list(pyuavcan.dsdl.get_model(Heartbeat)['vendor_specific_status_code'].data_type.bit_length_set)[0] - 1


_logger = logging.getLogger(__name__)


class HeartbeatPublisher:
    """
    This class manages periodic publication of the node heartbeat message.
    Also it subscribes to heartbeat messages from other nodes and logs cautionary messages
    if a node-ID conflict is detected on the bus.

    Instances must be manually started when initialization is finished by invoking :meth:`start`.

    The default states are as follows:

    - Health is NOMINAL.
github UAVCAN / pyuavcan / pyuavcan / _cli / commands / _util.py View on Github external
name = (mod.__name__ + '.' + comp) if mod else comp  # type: ignore
            try:
                mod = importlib.import_module(name)
            except ImportError:  # We seem to have hit a reserved word; try with an underscore.
                mod = importlib.import_module(name + '_')
    except ImportError:
        raise ValueError(f'The data spec string specifies a non-existent namespace: {spec!r}. '
                         f'{DSDLGeneratePackagesCommand.make_usage_suggestion_text(namespace_components[0])}') from None

    try:
        dtype = getattr(mod, f'{short_name}_{major}_{minor}')
    except AttributeError:
        raise ValueError(f'The data spec string specifies a non-existent short type name: {spec!r}') from None

    if issubclass(dtype, pyuavcan.dsdl.CompositeObject):
        model = pyuavcan.dsdl.get_model(dtype)
        port_id = port_id if port_id is not None else model.fixed_port_id
        if port_id is None:
            raise ValueError(f'The data spec does not specify a port ID, '
                             f'and a fixed port ID is not defined for the specified data type: {spec!r}')
        return port_id, dtype
    else:
        raise ValueError(f'The data spec does not specify a valid type: {spec!r}')
github UAVCAN / pyuavcan / pyuavcan / presentation / _port / _publisher.py View on Github external
def __repr__(self) -> str:
        return pyuavcan.util.repr_attributes_noexcept(self,
                                                      dtype=str(pyuavcan.dsdl.get_model(self.dtype)),
                                                      transport_session=self.transport_session,
                                                      proxy_count=self._proxy_count)
github UAVCAN / pyuavcan / pyuavcan / presentation / _port / _client.py View on Github external
def __repr__(self) -> str:
        return pyuavcan.util.repr_attributes_noexcept(self,
                                                      dtype=str(pyuavcan.dsdl.get_model(self.dtype)),
                                                      input_transport_session=self.input_transport_session,
                                                      output_transport_session=self.output_transport_session,
                                                      proxy_count=self._proxy_count)