Beispiel #1
0
    def __init__(
        self,
        ws_connection_str: str = "ws://0.0.0.0:6789",
        timeout: float = 3.0,
        event_mapping: Optional[Dict[str, Type[events.Event]]] = None,
    ):

        self._ws = websocket.WebSocket()
        self._logger = get_logger(__name__)
        self._event_queue: Queue[events.Event] = Queue()
        if event_mapping is None:
            event_mapping = {}

        self.event_mapping = event_mapping

        start_time = time.monotonic()
        while time.monotonic() < start_time + timeout:
            try:
                self._ws.connect(ws_connection_str)
                break
            except ConnectionRefusedError:
                time.sleep(0.25)

        if not self._ws.connected:
            raise ARServerClientException(
                f"Failed to connect to '{ws_connection_str}'.")

        self._ws.settimeout(timeout)

        system_info = self._call_rpc(srpc.c.SystemInfo.Request(uid()),
                                     srpc.c.SystemInfo.Response).data

        if system_info is None:
            raise ARServerClientException("Failed to get SystemInfo.")

        self._logger.info(
            f"Connected to server version {system_info.version}.")

        self._supported_rpcs = system_info.supported_rpc_requests
Beispiel #2
0
from arcor2.logging import get_logger
from arcor2.object_types.abstract import Generic
from arcor2.object_types.utils import base_from_source, built_in_types_names, prepare_object_types_dir
from arcor2.parameter_plugins.base import TypesDict
from arcor2.source import SourceException
from arcor2.source.utils import parse
from arcor2_build.source.logic import program_src
from arcor2_build.source.utils import global_action_points_class
from arcor2_build_data import SERVICE_NAME, URL, ImportResult

OBJECT_TYPE_MODULE = "arcor2_object_types"

original_sys_path = list(sys.path)
original_sys_modules = dict(sys.modules)

logger = get_logger("Build")

app = create_app(__name__)


def get_base_from_project_service(
    types_dict: TypesDict,
    tmp_dir: str,
    scene_object_types: set[str],
    obj_type: ObjectType,
    zf: zipfile.ZipFile,
    ot_path: str,
    ast: ast.AST,
) -> None:

    for idx, base in enumerate(base_from_source(ast, obj_type.id)):
Beispiel #3
0
import os
from functools import wraps
from typing import Dict, Optional, Type

from arcor2_dobot import version
from arcor2_dobot.dobot import Dobot, MoveType
from arcor2_dobot.m1 import DobotM1
from arcor2_dobot.magician import DobotMagician
from flask import jsonify, request

from arcor2.data.common import Joint, Pose
from arcor2.flask import RespT, create_app, run_app
from arcor2.helpers import port_from_url
from arcor2.logging import get_logger

logger = get_logger(__name__)

URL = os.getenv("ARCOR2_DOBOT_URL", "http://localhost:5018")
SERVICE_NAME = "Dobot Service"

app = create_app(__name__)

_dobot: Optional[Dobot] = None
_mock = False


def started() -> bool:

    return _dobot is not None

Beispiel #4
0
from arcor2 import env
from arcor2.cached import CachedProject as CProject
from arcor2.cached import CachedScene as CScene
from arcor2.data.common import Action, ActionParameter, FlowTypes
from arcor2.exceptions import Arcor2Exception
from arcor2.logging import get_logger
from arcor2.parameter_plugins.base import TypesDict
from arcor2.parameter_plugins.utils import plugin_from_type_name
from arcor2.source import SCRIPT_HEADER, SourceException
from arcor2.source.utils import add_import, add_method_call, tree_to_str
from arcor2_build.source.object_types import object_instance_from_res
from arcor2_build.source.utils import empty_script_tree, find_function, find_last_assign, main_loop

logger = get_logger(
    __name__, logging.DEBUG
    if env.get_bool("ARCOR2_LOGIC_DEBUG", False) else logging.INFO)


def program_src(type_defs: TypesDict,
                project: CProject,
                scene: CScene,
                add_logic: bool = True) -> str:

    tree = empty_script_tree(project.id, add_main_loop=add_logic)

    # get object instances from resources object
    main = find_function("main", tree)
    last_assign = find_last_assign(main)
    for obj in scene.objects:
        add_import(tree,
Beispiel #5
0
    req: str
    timeout: float
    return_res: bool


METERS_TO_MM = 1000.0
MM_TO_METERS = 1.0 / METERS_TO_MM

MOTION_BUFFER_SIZE = 512
MAX_TCP_SPEED = 1.5  # YuMi has max TCP speed 1.5m/s

MAX_GRIPPER_WIDTH = 0.02
MAX_GRIPPER_FORCE = 20

logger = get_logger("YuMi")


@dataclass
class YumiSettings(Settings):

    ip: str
    max_tcp_speed: float = MAX_TCP_SPEED

    def __post_init__(self) -> None:

        if not 0 < self.max_tcp_speed <= MAX_TCP_SPEED:
            raise YumiException("Invalid speed.")


class CmdCodes(IntEnum):
Beispiel #6
0
    the time before the server sends the first byte).

    Source: https://requests.readthedocs.io/en/master/user/advanced/#timeouts
    """

    connect: float = 3.05
    read: float = 20.0


OptTimeout = Optional[Timeout]

# module-level variables
debug = env.get_bool("ARCOR2_REST_DEBUG", False)
headers = {"accept": "application/json", "content-type": "application/json"}
session = requests.session()
logger = get_logger(__name__, logging.DEBUG if debug else logging.INFO)


def dataclass_from_json(resp_json: Dict[str, Any],
                        return_type: Type[DataClass]) -> DataClass:

    try:
        return return_type.from_dict(resp_json)
    except ValidationError as e:
        logger.debug(
            f'{return_type.__name__}: validation error "{e}" while parsing "{resp_json}".'
        )
        raise RestException("Invalid data.", str(e)) from e


def primitive_from_json(resp_json: Primitive,
Beispiel #7
0
from arcor2 import rest
from arcor2.data.common import Asset, IdDesc, Project, ProjectParameter, ProjectSources, Scene, SceneObjectOverride
from arcor2.data.object_type import MODEL_MAPPING, Mesh, MeshList, MetaModel3d, Model, Model3dType, ObjectType
from arcor2.exceptions import Arcor2Exception
from arcor2.exceptions.helpers import handle
from arcor2.logging import get_logger

URL = os.getenv("ARCOR2_PROJECT_SERVICE_URL", "http://0.0.0.0:10000")
"""
Collection of functions to work with the Project service (0.10.0).

All functions raise ProjectServiceException when any failure happens.

"""

logger = get_logger("Project")


class ProjectServiceException(Arcor2Exception):
    pass


# ----------------------------------------------------------------------------------------------------------------------
# Assets
# ----------------------------------------------------------------------------------------------------------------------


@handle(ProjectServiceException, logger, message="Failed to list assets.")
def assets_ids() -> set[str]:
    """Gets IDs of stored assets."""
Beispiel #8
0
from dataclasses import dataclass
from typing import Optional

from dataclasses_jsonschema import JsonSchemaMixin

from arcor2 import rest
from arcor2.data.common import Pose
from arcor2.data.object_type import Model3dType, Models
from arcor2.data.scene import LineCheck, LineCheckResult, MeshFocusAction
from arcor2.exceptions import Arcor2Exception
from arcor2.exceptions.helpers import handle
from arcor2.logging import get_logger

URL = os.getenv("ARCOR2_SCENE_SERVICE_URL", "http://0.0.0.0:5013")

logger = get_logger("Scene")


class SceneServiceException(Arcor2Exception):
    pass


@dataclass
class MeshParameters(JsonSchemaMixin):

    mesh_scale_x: float = 1.0
    mesh_scale_y: float = 1.0
    mesh_scale_z: float = 1.0
    transform_id: str = "world"