Ejemplo n.º 1
0
def test_serve():
    channel = Channel(uri=URI, exchange=EXCHANGE)
    service = ServiceProvider(channel)
    topic = "MyService"
    service.delegate(topic, my_service, Struct, Int64Value)

    subscription = Subscription(channel)

    sent = Message(content="body".encode('latin'))
    channel.publish(sent, topic=subscription.name)

    recv = channel.consume(timeout=1.0)
    assert recv.subscription_id == subscription.id

    # Trying to serve a message from another subscription should fail
    assert service.should_serve(recv) is False
    with pytest.raises(RuntimeError):
        service.serve(recv)

    sent.topic = topic
    channel.publish(message=sent)
    recv = channel.consume(timeout=1.0)

    assert service.should_serve(recv) is True
    service.serve(recv)

    channel.close()
Ejemplo n.º 2
0
def main():
    service_name = 'SkeletonsDetector.Detect'

    op = load_options()
    sd = RPCSkeletonsDetector(op)

    log = Logger(name=service_name)
    channel = Channel(op.broker_uri)
    log.info('Connected to broker {}', op.broker_uri)
    provider = ServiceProvider(channel)
    provider.add_interceptor(LogInterceptor())

    max_batch_size = max(100, op.zipkin_batch_size)
    exporter = ZipkinExporter(
        service_name=service_name,
        host_name=op.zipkin_host,
        port=op.zipkin_port,
        transport=BackgroundThreadTransport(max_batch_size=max_batch_size),
    )
    tracing = TracingInterceptor(exporter=exporter)

    provider.delegate(topic='SkeletonsDetector.Detect',
                      function=partial(RPCSkeletonsDetector.detect, sd),
                      request_type=Image,
                      reply_type=ObjectAnnotations)

    provider.run()
Ejemplo n.º 3
0
def test_delegate():
    channel = Channel(uri=URI, exchange=EXCHANGE)
    service = ServiceProvider(channel)
    service.delegate("MyService", my_service, Struct, Int64Value)
    with pytest.raises(RuntimeError):
        service.delegate("MyService", my_service, Struct, Int64Value)
    channel.close()
Ejemplo n.º 4
0
def main():
    service_name = 'FaceDetector.Detect'
    log = Logger(name=service_name)

    op = load_options()
    detector = RPCFaceDetector(op.model)

    channel = Channel(op.broker_uri)
    log.info('Connected to broker {}', op.broker_uri)

    provider = ServiceProvider(channel)
    provider.add_interceptor(LogInterceptor())

    exporter = create_exporter(service_name=service_name, uri=op.zipkin_uri)
    tracing = TracingInterceptor(exporter=exporter)
    provider.add_interceptor(tracing)

    provider.delegate(topic='FaceDetector.Detect',
                      function=detector.detect,
                      request_type=Image,
                      reply_type=ObjectAnnotations)

    provider.run()
Ejemplo n.º 5
0
def test_rpc():
    channel = Channel(uri=URI, exchange=EXCHANGE)
    service = ServiceProvider(channel)
    service.add_interceptor(LogInterceptor())
    service.delegate("MyService", my_service, Struct, Int64Value)

    subscription = Subscription(channel)

    def request_serve_consume(number):
        struct = Struct()
        struct.fields["value"].number_value = number
        message = Message(struct)
        message.reply_to = subscription
        message.pack(struct)
        channel.publish(topic="MyService", message=message)

        request = channel.consume(timeout=1.0)
        assert request.body == message.body
        service.serve(request)
        assert request.unpack(Struct) == struct

        return channel.consume(timeout=1.0)

    reply = request_serve_consume(90.0)
    int64 = reply.unpack(Int64Value)
    assert int64.value == 90
    assert reply.status.ok() is True

    reply = request_serve_consume(666.0)
    assert reply.status.ok() is False
    assert reply.status.code == StatusCode.FAILED_PRECONDITION

    reply = request_serve_consume(10.0)
    assert reply.status.ok() is False
    assert reply.status.code == StatusCode.INTERNAL_ERROR

    channel.close()
Ejemplo n.º 6
0
def main():

    service_name = "CameraGateway"
    log = Logger(service_name)
    options = load_options()
    camera = CameraGateway(fps=options["fps"])

    publish_channel = Channel(options['broker_uri'])
    rpc_channel = Channel(options['broker_uri'])
    server = ServiceProvider(rpc_channel)
    logging = LogInterceptor()
    server.add_interceptor(logging)

    server.delegate(topic=service_name + ".*.GetConfig",
                    request_type=FieldSelector,
                    reply_type=CameraConfig,
                    function=camera.get_config)

    server.delegate(topic=service_name + ".*.SetConfig",
                    request_type=CameraConfig,
                    reply_type=Empty,
                    function=camera.set_config)

    exporter = create_exporter(service_name=service_name,
                               uri=options["zipkin_uri"])

    while True:

        # iterate through videos listed
        for video in options['videos']:

            # id of the first sequence of videos
            person_id = video['person_id']
            gesture_id = video['gesture_id']

            # getting the path of the 4 videos
            video_files = {
                cam_id: os.path.join(
                    options['folder'],
                    'p{:03d}g{:02d}c{:02d}.mp4'.format(person_id, gesture_id,
                                                       cam_id))
                for cam_id in options["cameras_id"]
            }

            for iteration in range(video['iterations']):

                info = {
                    "person": person_id,
                    "gesture": gesture_id,
                    "iteration": iteration
                }
                log.info('{}', str(info).replace("'", '"'))

                # object that let get images from multiples videos files
                video_loader = FramesLoader(video_files)

                # iterate through all samples on video
                while True:

                    time_initial = time.time()

                    # listen server for messages about change
                    try:
                        message = rpc_channel.consume(timeout=0)
                        if server.should_serve(message):
                            server.serve(message)
                    except socket.timeout:
                        pass

                    frame_id, frames = video_loader.read()

                    for cam in sorted(frames.keys()):
                        tracer = Tracer(exporter)
                        span = tracer.start_span(name='frame')
                        pb_image = to_pb_image(frames[cam])
                        msg = Message(content=pb_image)
                        msg.inject_tracing(span)
                        topic = 'CameraGateway.{}.Frame'.format(cam)
                        publish_channel.publish(msg, topic=topic)
                        tracer.end_span()

                    took_ms = (time.time() - time_initial) * 1000

                    dt = (1 / camera.fps) - (took_ms / 1000)
                    if dt > 0:
                        time.sleep(dt)
                        info = {
                            "sample": frame_id,
                            "took_ms": took_ms,
                            "wait_ms": dt * 1000
                        }
                        log.info('{}', str(info).replace("'", '"'))

                    if frame_id >= (video_loader.num_samples - 1):
                        video_loader.release()
                        del video_loader
                        gc.collect()
                        break

        if options['loop'] is False:
            break
Ejemplo n.º 7
0
    def run(self, id, broker_uri):
        service_name = "CameraGateway.{}".format(id)

        channel = Channel(broker_uri)
        server = ServiceProvider(channel)

        logging = LogInterceptor()
        server.add_interceptor(logging)

        server.delegate(topic=service_name + ".GetConfig",
                        request_type=FieldSelector,
                        reply_type=CameraConfig,
                        function=self.get_config)

        server.delegate(topic=service_name + ".SetConfig",
                        request_type=CameraConfig,
                        reply_type=Empty,
                        function=self.set_config)

        self.driver.start_capture()
        self.logger.info("Listening for requests")

        while True:
            image = self.driver.grab_image()
            channel.publish(Message(content=image),
                            topic=service_name + ".Frame")

            pose = self.driver.get_pose()
            frameTransList = FrameTransformations()
            frameTransList.tfs.extend([pose])
            channel.publish(Message(content=frameTransList),
                            topic=service_name + ".FrameTransformations")

            try:
                message = channel.consume(timeout=0)
                if server.should_serve(message):
                    server.serve(message)
            except socket.timeout:
                pass
Ejemplo n.º 8
0
    def run(self, id, broker_uri):
        service_name = "RobotGateway.{}".format(id)

        channel = Channel(broker_uri)
        server = ServiceProvider(channel)
        logging = LogInterceptor()
        server.add_interceptor(logging)

        server.delegate(topic=service_name + ".GetConfig",
                        request_type=FieldSelector,
                        reply_type=RobotConfig,
                        function=self.get_config)

        server.delegate(topic=service_name + ".SetConfig",
                        request_type=RobotConfig,
                        reply_type=Empty,
                        function=self.set_config)

        server.delegate(topic=service_name + ".NavigateTo",
                        request_type=Position,
                        reply_type=Empty,
                        function=self.navigate_to)

        server.delegate(topic=service_name + ".MoveTo",
                        request_type=Pose,
                        reply_type=Empty,
                        function=self.move_to)

        server.delegate(topic=service_name + ".PauseAwareness",
                        request_type=Empty,
                        reply_type=Empty,
                        function=self.pause_awareness)

        server.delegate(topic=service_name + ".ResumeAwareness",
                        request_type=Empty,
                        reply_type=Empty,
                        function=self.resume_awareness)

        server.delegate(topic=service_name + ".SetAwareness",
                        request_type=Struct,
                        reply_type=Empty,
                        function=self.set_awareness)

        #server.delegate(
        #    topic=service_name + ".SetAwarenessOff",
        #    request_type=Empty,
        #    reply_type=Empty,
        #    function=self.set_awareness_off)

        self.logger.info("Listening for requests")
        while True:
            pose = self.driver.get_base_pose()
            frameTransList = FrameTransformations()
            frameTransList.tfs.extend([pose])
            self.logger.debug("Publishing pose")

            channel.publish(Message(content=frameTransList),
                            topic=service_name + ".FrameTransformations")

            try:
                message = channel.consume(timeout=0)
                if server.should_serve(message):
                    server.serve(message)
            except socket.timeout:
                pass
Ejemplo n.º 9
0
from is_wire.core import Channel, Message, Logger
from is_wire.rpc import ServiceProvider, LogInterceptor
from is_msgs.image_pb2 import Image, ObjectAnnotations, ObjectAnnotation
from utils import load_options
import time
from random import randint

mean_time = 100  # milliseconds
var_time = 20


def detect(image, ctx):
    # simulate error
    time.sleep(randint(mean_time - var_time, mean_time + var_time) / 1000.0)
    reply = ObjectAnnotations(frame_id=randint(0, 4),
                              objects=[ObjectAnnotation()] * randint(1, 3))
    return reply


options = load_options(print_options=False)

channel = Channel(options.broker_uri)
provider = ServiceProvider(channel)
provider.add_interceptor(LogInterceptor())

provider.delegate(topic='Skeletons.Detect',
                  function=detect,
                  request_type=Image,
                  reply_type=ObjectAnnotations)

provider.run()
Ejemplo n.º 10
0
from random import randint

from is_wire.core import Channel
from is_wire.rpc import ServiceProvider
from is_wire.rpc.log_interceptor import LogInterceptor

from is_msgs.common_pb2 import Pose, Position

mean_svc_time_ms = 100
var_src_time_ms = 20

min_svc_time_ms = mean_svc_time_ms - var_src_time_ms
max_svc_time_ms = mean_svc_time_ms + var_src_time_ms

channel = Channel('amqp://localhost:5672')
service_provider = ServiceProvider(channel)
service_provider.add_interceptor(LogInterceptor())


def service(pose, ctx):
    delay = randint(min_svc_time_ms, max_svc_time_ms) / 1000.0
    time.sleep(delay)
    return pose.position


service_provider.delegate(topic="GetPosition",
                          function=service,
                          request_type=Pose,
                          reply_type=Position)

service_provider.run()
Ejemplo n.º 11
0
service_name = "RobotGateway.{}".format(op_config.robot_parameters.id)

# instancia driver passando a porta serial
driver = ATSPdriver(op_config.robot_parameters.robot_uri)
ATSPlog.info("event=RobotInitDone")

# instania channel passando endereco do broker
# estabelece conexao com o broker
channel = Channel(op_config.broker_uri)
ATSPlog.info("event=ChannelInitDone")

# instancia gateway passando o channel e o driver criados, alem dos parametros do robo
gateway = ATSPgateway(channel=channel, driver=driver, robot_par=op_config.robot_parameters)

# Cria o ServiceProvider passando o channel
server = ServiceProvider(channel)

logs = LogInterceptor()  # Log requests to console
server.add_interceptor(logs)

# Linka cada tipo de mensagem recebida a um metodo do gateway
server.delegate(topic=service_name + ".GetConfig", request_type=Empty, reply_type=RobotConfig, function=gateway.get_configuration)
server.delegate(topic=service_name + ".SetConfig", request_type=RobotConfig, reply_type=Empty, function=gateway.set_configuration)

ATSPlog.info("event=InitAllDone")


while(1):
    try:
        # Espera receber uma mensagem no canal dentro de um timeout
        message = channel.consume(timeout=max(gateway.next_deadline()-time(),0))