def test_event_sending(client_server):
    """Make sure we can send and receive events."""

    loop, client, server = client_server

    shared = [0]

    async def _send_event(payload, context):
        server = context.server
        con = context.connection

        await server.send_event(con, payload, 5)

    def event_callback(payload):
        shared[0] += payload

    server.register_command('send_event', _send_event, StringVerifier())

    client.register_event('event1', event_callback, IntVerifier())

    loop.run_coroutine(client.send_command('send_event', 'event1', Verifier()))
    assert shared[0] == 5

    loop.run_coroutine(client.send_command('send_event', 'event1', Verifier()))
    assert shared[0] == 10

    loop.run_coroutine(client.send_command('send_event', 'event2', Verifier()))
    assert shared[0] == 10
Beispiel #2
0
def test_options_verifier():
    """Check and make sure that OptionsVerifier works
    """

    value = 'abc'

    verifier = OptionsVerifier(IntVerifier('int'), StringVerifier('string'))
    verifier.verify(value)

    verifier = OptionsVerifier(LiteralVerifier('abc'))
    verifier.verify(value)

    with pytest.raises(ValidationError):
        verifier.verify('ab')

    with pytest.raises(ValidationError):
        verifier.verify(1)
from iotile.core.utilities.schema_verify import DictionaryVerifier, OptionsVerifier, StringVerifier, IntVerifier
from iotile.core.hw import HardwareManager
from iotile.core.exceptions import HardwareError
from .shared_resource import SharedResource

RESOURCE_ARG_SCHEMA = DictionaryVerifier(desc="hardware_manager arguments")
RESOURCE_ARG_SCHEMA.add_optional(
    "port", StringVerifier("the port string to use to connect to devices"))
RESOURCE_ARG_SCHEMA.add_optional(
    "connect",
    OptionsVerifier(StringVerifier(),
                    IntVerifier(),
                    desc="the uuid of the device to connect to"))
RESOURCE_ARG_SCHEMA.add_optional(
    "connect_direct",
    OptionsVerifier(StringVerifier(),
                    desc="the connection string of the device to connect to"))


class HardwareManagerResource(SharedResource):
    """A shared HardwareManager instance.

    Arguments:
        port (str): Optional port argument that should
            be used to connect to a DeviceAdapter.  If not
            specified, the virtual environment default is used.
        connect: (str or int): The UUID of a device to connect to
            when this resource is created and disconnect from when
            it is destroyed.  This is an optional parameter.  If
            it is not specified the HardwareManager is not connected
            upon creation.
Beispiel #4
0
"""Schemas for all of the messages types that we support into the status server."""

from iotile.core.utilities.schema_verify import DictionaryVerifier, NoneVerifier, BytesVerifier, IntVerifier, StringVerifier, LiteralVerifier, OptionsVerifier, BooleanVerifier, FloatVerifier, ListVerifier

# Payloads that are shared among multiple messages
ServiceInfoPayload = DictionaryVerifier()
ServiceInfoPayload.add_required('short_name', StringVerifier())
ServiceInfoPayload.add_required('long_name', StringVerifier())
ServiceInfoPayload.add_required('preregistered', BooleanVerifier())

MessagePayload = DictionaryVerifier()
MessagePayload.add_required('level', IntVerifier())
MessagePayload.add_required('message', StringVerifier())
MessagePayload.add_required('created_time', FloatVerifier())
MessagePayload.add_required('now_time', FloatVerifier())
MessagePayload.add_optional('count', IntVerifier())
MessagePayload.add_optional('id', IntVerifier())

RPCCommandPayload = DictionaryVerifier()
RPCCommandPayload.add_required('rpc_id', IntVerifier())
RPCCommandPayload.add_required('payload', BytesVerifier())
RPCCommandPayload.add_required('response_uuid', StringVerifier())

# Commands that we support
HeartbeatCommand = DictionaryVerifier()
HeartbeatCommand.add_required('name', StringVerifier())
HeartbeatResponse = NoneVerifier()

SetAgentCommand = DictionaryVerifier()
SetAgentCommand.add_required('name', StringVerifier())
SetAgentResponse = NoneVerifier()
from __future__ import absolute_import, unicode_literals

from builtins import int
from iotile.core.utilities.schema_verify import DictionaryVerifier, OptionsVerifier, StringVerifier, IntVerifier
from iotile.core.hw import HardwareManager
from iotile.core.exceptions import HardwareError
from .shared_resource import SharedResource


RESOURCE_ARG_SCHEMA = DictionaryVerifier(desc="hardware_manager arguments")
RESOURCE_ARG_SCHEMA.add_optional("port", StringVerifier("the port string to use to connect to devices"))
RESOURCE_ARG_SCHEMA.add_optional("connect", OptionsVerifier(StringVerifier(), IntVerifier(), desc="the uuid of the device to connect to"))
RESOURCE_ARG_SCHEMA.add_optional("connect_direct", OptionsVerifier(StringVerifier(), desc="the connection string of the device to connect to"))

class HardwareManagerResource(SharedResource):
    """A shared HardwareManager instance.

    Arguments:
        port (str): Optional port argument that should
            be used to connect to a DeviceAdapter.  If not
            specified, the virtual environment default is used.
        connect: (str or int): The UUID of a device to connect to
            when this resource is created and disconnect from when
            it is destroyed.  This is an optional parameter.  If
            it is not specified the HardwareManager is not connected
            upon creation.
        connect_direct: (str or int): The connection string of a device to connect 
            directly to when this resource is created and disconnect from 
            when it is destroyed.  This is an optional parameter.  If
            it is not specified the HardwareManager is not connected
            upon creation.
Beispiel #6
0
import logging
import uuid
from iotile.core.exceptions import IOTileException, InternalError, ValidationError, TimeoutExpiredError
from iotile.core.utilities.schema_verify import Verifier, DictionaryVerifier, StringVerifier, LiteralVerifier, OptionsVerifier

# The prescribed schema of command response messages
# Messages with this format are automatically processed inside the ValidatingWSClient
SuccessfulResponseSchema = DictionaryVerifier()
SuccessfulResponseSchema.add_required('type', LiteralVerifier('response'))
SuccessfulResponseSchema.add_required('success', LiteralVerifier(True))
SuccessfulResponseSchema.add_optional('payload', Verifier())

FailureResponseSchema = DictionaryVerifier()
FailureResponseSchema.add_required('type', LiteralVerifier('response'))
FailureResponseSchema.add_required('success', LiteralVerifier(False))
FailureResponseSchema.add_required('reason', StringVerifier())

ResponseSchema = OptionsVerifier(SuccessfulResponseSchema, FailureResponseSchema)


class ValidatingWSClient(WebSocketClient):
    """A threaded websocket client that validates messages received.

    Messages are assumed to be packed using msgpack in a binary format
    and are decoded and validated against message type schema.  Matching
    messages are dispatched to the appropriate handler and messages that
    match no attached schema are logged and dropped.
    """

    def __init__(self, url, logger_name=__name__):
        """Constructor.
Beispiel #7
0
"""This file contains the schema verifier for verifying a recipe file."""

from iotile.core.utilities.schema_verify import (DictionaryVerifier, Verifier,
                                                 StringVerifier, IntVerifier,
                                                 ListVerifier, OptionsVerifier,
                                                 BooleanVerifier)

ActionItem = DictionaryVerifier(
    desc="A description of a single action that should be run")
ActionItem.add_required(
    "name",
    StringVerifier("The name of the action type that should be executed"))
ActionItem.add_optional(
    "description",
    StringVerifier("A short description for what the action is doing"))
ActionItem.add_optional(
    "use",
    ListVerifier(StringVerifier("The name of a resource"),
                 desc="A list of used resources"))
ActionItem.add_optional(
    "open_before",
    ListVerifier(StringVerifier("The name of a resource"),
                 desc="A list of resources to open before this step"))
ActionItem.add_optional(
    "close_after",
    ListVerifier(StringVerifier("The name of a resource"),
                 desc="A list of resources to close after this step"))
ActionItem.key_rule(None,
                    Verifier("A parameter passed into the underlying action")
                    )  # Allow any additional values
import pathlib

from iotile.core.utilities.schema_verify import DictionaryVerifier
from iotile.core.utilities.schema_verify import StringVerifier
from .shared_resource import SharedResource

RESOURCE_ARG_SCHEMA = DictionaryVerifier(desc="filesystem_manager arguments")
RESOURCE_ARG_SCHEMA.add_required(
    "path", StringVerifier("path to filesystem to work with"))


class FilesystemManagerResource(SharedResource):
    """ A Resource for operating on a Filesystem

    All Steps using this Resource will use self.root as the root directory to find other files

    Root directory is a pathlib.Path

    Arguments:
        path (str): Path to filesystem to work with
    """

    ARG_SCHEMA = RESOURCE_ARG_SCHEMA
    _allowed_types = ["file", "block"]

    def __init__(self, args):
        super(FilesystemManagerResource, self).__init__()

        self._path = args.get('path')
        self.root = None
Beispiel #9
0
"""List of known command and response payloads."""

from iotile.core.utilities.schema_verify import BytesVerifier, DictionaryVerifier, \
    EnumVerifier, FloatVerifier, IntVerifier, StringVerifier, NoneVerifier, Verifier, \
    OptionsVerifier

# Connect Command
ConnectCommand = DictionaryVerifier()
ConnectCommand.add_required('connection_string', StringVerifier())

ConnectResponse = NoneVerifier()

# Disconnect Command
DisconnectCommand = DictionaryVerifier()
DisconnectCommand.add_required('connection_string', StringVerifier())

DisconnectResponse = NoneVerifier()


_InterfaceEnum = EnumVerifier(['rpc', 'streaming', 'tracing', 'script', 'debug'])

# OpenInterface Command

OpenInterfaceCommand = DictionaryVerifier()
OpenInterfaceCommand.add_required('interface', _InterfaceEnum)
OpenInterfaceCommand.add_required('connection_string', StringVerifier())

OpenInterfaceResponse = NoneVerifier()
# CloseInterface Command

CloseInterfaceCommand = DictionaryVerifier()
Beispiel #10
0
"""All known and accepted messages that can be sent over AWS IOT."""

from iotile.core.utilities.schema_verify import Verifier, OptionsVerifier, EnumVerifier, ListVerifier, BytesVerifier, IntVerifier, LiteralVerifier, FloatVerifier, DictionaryVerifier, StringVerifier


# All control messages that we support
OpenInterfaceCommand = DictionaryVerifier()  # pylint: disable=C0103
OpenInterfaceCommand.add_required('type', LiteralVerifier('command'))
OpenInterfaceCommand.add_required('operation', LiteralVerifier('open_interface'))
OpenInterfaceCommand.add_required('key', StringVerifier())
OpenInterfaceCommand.add_required('client', StringVerifier())
OpenInterfaceCommand.add_required('interface', EnumVerifier(['rpc', 'streaming', 'tracing', 'script']))

CloseInterfaceCommand = DictionaryVerifier()  # pylint: disable=C0103
CloseInterfaceCommand.add_required('type', LiteralVerifier('command'))
CloseInterfaceCommand.add_required('operation', LiteralVerifier('close_interface'))
CloseInterfaceCommand.add_required('key', StringVerifier())
CloseInterfaceCommand.add_required('client', StringVerifier())
CloseInterfaceCommand.add_required('interface', EnumVerifier(['rpc', 'streaming', 'tracing', 'script']))

ConnectCommand = DictionaryVerifier()  # pylint: disable=C0103
ConnectCommand.add_required('type', LiteralVerifier('command'))
ConnectCommand.add_required('operation', LiteralVerifier('connect'))
ConnectCommand.add_required('key', StringVerifier())
ConnectCommand.add_required('client', StringVerifier())

ScriptCommand = DictionaryVerifier()  # pylint: disable=C0103
ScriptCommand.add_required('type', LiteralVerifier('command'))
ScriptCommand.add_required('operation', LiteralVerifier('send_script'))
ScriptCommand.add_required('fragment_count', IntVerifier())
ScriptCommand.add_required('fragment_index', IntVerifier())
Beispiel #11
0
    LiteralVerifier, StringVerifier
from . import operations

Basic = DictionaryVerifier()
Basic.add_required('type', LiteralVerifier('notification'))

# Device found while scanning
DeviceFound = Basic.clone()
DeviceFound.add_required('operation',
                         LiteralVerifier(operations.NOTIFY_DEVICE_FOUND))
DeviceFound.add_required('device', Verifier())

# Report
Report = Basic.clone()
Report.add_required('operation', LiteralVerifier(operations.NOTIFY_REPORT))
Report.add_required('connection_string', StringVerifier())
Report.add_required('payload', BytesVerifier(encoding="base64"))

# Trace
Trace = Basic.clone()
Trace.add_required('operation', LiteralVerifier(operations.NOTIFY_TRACE))
Trace.add_required('connection_string', StringVerifier())
Trace.add_required('payload', BytesVerifier(encoding="base64"))

# Script progress
Progress = Basic.clone()
Progress.add_required('operation', LiteralVerifier(operations.NOTIFY_PROGRESS))
Progress.add_required('connection_string', StringVerifier())
Progress.add_required('done_count', IntVerifier())
Progress.add_required('total_count', IntVerifier())
from iotile.core.utilities.schema_verify import BytesVerifier, DictionaryVerifier, Verifier, BooleanVerifier, IntVerifier,\
    StringVerifier

# Device found while scanning
ScanEvent = Verifier()

# Report
SerializedReport = DictionaryVerifier()
SerializedReport.add_required('encoded_report',
                              BytesVerifier(encoding="base64"))
SerializedReport.add_required('received_time', Verifier())
SerializedReport.add_required('report_format', IntVerifier())
SerializedReport.add_required('origin', IntVerifier())

ReportEvent = DictionaryVerifier()
ReportEvent.add_required('connection_string', StringVerifier())
ReportEvent.add_required('serialized_report', SerializedReport)

DisconnectionEvent = DictionaryVerifier()
DisconnectionEvent.add_required('connection_string', StringVerifier())
DisconnectionEvent.add_required('reason', StringVerifier())
DisconnectionEvent.add_required('expected', BooleanVerifier())

# Trace
TraceEvent = DictionaryVerifier()
TraceEvent.add_required('connection_string', StringVerifier())
TraceEvent.add_required('payload', BytesVerifier(encoding="base64"))

# Script and debug progress
ProgressEvent = DictionaryVerifier()
ProgressEvent.add_required('connection_string', StringVerifier())
Beispiel #13
0
"""List of commands handled by the WebSocket plugin."""

from iotile.core.utilities.schema_verify import BytesVerifier, DictionaryVerifier, Verifier, \
    EnumVerifier, FloatVerifier, IntVerifier, LiteralVerifier, StringVerifier
from . import operations

Basic = DictionaryVerifier()
Basic.add_required('type', LiteralVerifier('command'))
Basic.add_required('connection_string', StringVerifier())

# Connect
Connect = Basic.clone()
Connect.add_required('operation', LiteralVerifier(operations.CONNECT))

# Close interface
CloseInterface = Basic.clone()
CloseInterface.add_required('operation',
                            LiteralVerifier(operations.CLOSE_INTERFACE))
CloseInterface.add_required(
    'interface',
    EnumVerifier(['rpc', 'streaming', 'tracing', 'script', 'debug']))

# Disconnect
Disconnect = Basic.clone()
Disconnect.add_required('operation', LiteralVerifier(operations.DISCONNECT))

# Open interface
OpenInterface = Basic.clone()
OpenInterface.add_required('operation',
                           LiteralVerifier(operations.OPEN_INTERFACE))
OpenInterface.add_required(
Beispiel #14
0
def verifier1():
    ver = DictionaryVerifier('test verifier')
    ver.add_required('req_key', DictionaryVerifier())
    ver.add_optional('opt_key', ListVerifier(StringVerifier('a string')))
    ver.add_optional('opt2_key', BooleanVerifier(desc='a boolean'))
    return ver
Beispiel #15
0
"""The classes of messages supported by this socket impementation."""

from iotile.core.utilities.schema_verify import Verifier, NoneVerifier, DictionaryVerifier, StringVerifier
from iotile.core.utilities.schema_verify import LiteralVerifier, OptionsVerifier

# The prescribed schema of command response messages
# Messages with this format are automatically processed inside the Client
COMMAND = DictionaryVerifier()
COMMAND.add_required('type', LiteralVerifier('command'))
COMMAND.add_required('operation', StringVerifier())
COMMAND.add_required('uuid', StringVerifier())
COMMAND.add_optional('payload', Verifier())

SUCCESSFUL_RESPONSE = DictionaryVerifier()
SUCCESSFUL_RESPONSE.add_required('uuid', StringVerifier())
SUCCESSFUL_RESPONSE.add_required('type', LiteralVerifier('response'))
SUCCESSFUL_RESPONSE.add_required('success', LiteralVerifier(True))
SUCCESSFUL_RESPONSE.add_optional('payload', Verifier())

FAILURE_RESPONSE = DictionaryVerifier()
FAILURE_RESPONSE.add_required('type', LiteralVerifier('response'))
FAILURE_RESPONSE.add_required('uuid', StringVerifier())
FAILURE_RESPONSE.add_required('success', LiteralVerifier(False))
FAILURE_RESPONSE.add_required('reason', StringVerifier())
FAILURE_RESPONSE.add_required(
    'exception_class', OptionsVerifier(StringVerifier(), NoneVerifier()))

RESPONSE = OptionsVerifier(SUCCESSFUL_RESPONSE, FAILURE_RESPONSE)

EVENT = DictionaryVerifier()
EVENT.add_required('type', LiteralVerifier('event'))