예제 #1
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()
예제 #2
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()
예제 #3
0
class BrokerEvents(object):
    def __init__(self, broker_uri, management_uri, log_level):
        self.log = Logger(name="BrokerEvents", level=log_level)

        self.log.debug("broker_uri='{}'", broker_uri)
        self.channel = Channel(broker_uri)
        self.subscription = Subscription(self.channel)
        self.subscription.subscribe(topic="binding.*")

        self.log.debug("management_uri='{}'", management_uri)
        self.consumers = self.query_consumers_http(management_uri)

    def run(self):
        while True:
            msg = self.channel.consume()
            self.log.debug("topic='{}' metadata={}", msg.topic, msg.metadata)

            if msg.metadata["destination_kind"] != "queue" or \
               msg.metadata["source_name"] != "is":
                continue

            event = msg.topic.split('.')[-1]
            topic = msg.metadata["routing_key"]
            queue = msg.metadata["destination_name"]

            if event == "created":
                self.consumers.info[topic].consumers.append(queue)
            elif event == "deleted":
                self.consumers.info[topic].consumers.remove(queue)
                if len(self.consumers.info[topic].consumers) == 0:
                    del self.consumers.info[topic]

            self.log.info("event='{}' topic='{}' queue='{}'", event, topic,
                          queue)

            self.channel.publish(
                Message(content=self.consumers),
                topic="BrokerEvents.Consumers",
            )

    @staticmethod
    def query_consumers_http(management_uri):
        reply = requests.get(management_uri + "/api/bindings")
        if reply.status_code != 200:
            why = "Failed to query management API, code={}".format(
                reply.status_code)
            raise RuntimeError(why)

        bindings = reply.json()
        bindings = [
            b for b in bindings
            if b["destination_type"] == "queue" and b["source"] == "is"
        ]

        consumers = ConsumerList()
        for b in bindings:
            consumers.info[b["routing_key"]].consumers.append(b["destination"])
        return consumers
예제 #4
0
 def __init__(self, *args, **kwargs):
     self.ICMP_ECHO_REQUEST = 8
     self.icmp_seq = 1
     self.packet_loss = 0
     self.loss_perc = 0
     self.last_seq = 0
     self.delay_list = []
     self.file = open("ping_result.txt", "w")
     self.connection = Channel(**kwargs)
     self.status = PingStatus()
예제 #5
0
    def __init__(self, broker_uri, management_uri, log_level):
        self.log = Logger(name="BrokerEvents", level=log_level)

        self.log.debug("broker_uri='{}'", broker_uri)
        self.channel = Channel(broker_uri)
        self.subscription = Subscription(self.channel)
        self.subscription.subscribe(topic="binding.*")

        self.log.debug("management_uri='{}'", management_uri)
        self.consumers = self.query_consumers_http(management_uri)
예제 #6
0
def test_multi_subscription():
    channel = Channel(uri=URI, exchange=EXCHANGE)
    message = Message()
    subscription1 = Subscription(channel)
    subscription2 = Subscription(channel)

    channel.publish(message, topic=subscription1.name)
    recv = channel.consume(timeout=1.0)
    assert recv.subscription_id == subscription1.name

    channel.publish(message, topic=subscription2.name)
    recv = channel.consume(timeout=1.0)
    assert recv.subscription_id == subscription2.name
    channel.close()
예제 #7
0
def test_negative_timeout():
    channel = Channel(uri=URI, exchange=EXCHANGE)
    with pytest.raises(AssertionError):
        channel.consume(timeout=-1e-10)
    with pytest.raises(socket.timeout):
        channel.consume(timeout=0)
    channel.close()
예제 #8
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()
예제 #9
0
class TransformationFetcher:
  def __init__(self, broker_uri=None):
    self.channel = Channel() if broker_uri is None else Channel(broker_uri)
    self.subscription = Subscription(self.channel)
    self.transformations = {}

  def get_transformation(self, _from, _to):
    if _from in self.transformations and _to in self.transformations[_from]:
        return self.transformations[_from][_to]
    if self._request_transformation(_from, _to):
      return self.transformations[_from][_to]
    return None

  def _request_transformation(self, _from, _to):
    topic = 'FrameTransformation.{}.{}'.format(_from, _to)
    self.subscription.subscribe(topic)
    try:
      msg = self.channel.consume(timeout=5.0)
      self.subscription.unsubscribe(topic)
    except:
      self.subscription.unsubscribe(topic)
      return False
    transformation = msg.unpack(FrameTransformation)
    if _from not in self.transformations:
      self.transformations[_from] = {}
    self.transformations[_from][_to] = to_np(transformation.tf)
    return True
예제 #10
0
def test_channel():
    channel = Channel(uri=URI, exchange=EXCHANGE)
    subscription = Subscription(channel)
    subscription.subscribe("MyTopic.Sub.Sub")

    struct = Struct()
    struct.fields["value"].number_value = 666.0

    sent = Message(struct)
    sent.reply_to = subscription
    sent.created_at = int(1000 * now()) / 1000.0
    sent.timeout = 1.0
    sent.topic = "MyTopic.Sub.Sub"

    channel.publish(message=sent)
    received = channel.consume(timeout=1.0)

    assert sent.reply_to == received.reply_to
    assert sent.subscription_id == received.subscription_id
    assert sent.content_type == received.content_type
    assert sent.body == received.body
    assert sent.status == received.status
    assert sent.topic == received.topic
    assert sent.correlation_id == received.correlation_id
    assert sent.timeout == received.timeout
    assert sent.metadata == received.metadata
    assert sent.created_at == received.created_at
    assert str(sent) == str(received)

    struct2 = received.unpack(Struct)
    assert str(struct) == str(struct2)
    assert struct == struct2

    channel.close()
예제 #11
0
def main(_argv):
    # Connect to the broker
    broker = "ampq://*****:*****@10.10.2.1:30000"
    channel = Channel(broker)

    # Subscribe to the desired topic
    subscription = Subscription(channel)
    camera_id = "CameraGateway." + FLAGS.camera + ".Frame"
    subscription.subscribe(topic=camera_id)

    if FLAGS.tiny:
        yolo = YoloV3Tiny()
    else:
        yolo = YoloV3()

    yolo.load_weights(FLAGS.weights)
    logging.info('weights loaded')

    class_names = [c.strip() for c in open(FLAGS.classes).readlines()]
    logging.info('classes loaded')

    msg = channel.consume()
    img = msg.unpack(Image)
    img = get_np_image(img)
    img_to_draw = img

    #img = tf.image.decode_image(img, channels=3)
    img = tf.expand_dims(img, 0)
    img = transform_images(img, FLAGS.size)

    t1 = time.time()
    boxes, scores, classes, nums = yolo(img)
    t2 = time.time()
    logging.info('time: {}'.format(t2 - t1))

    logging.info('detections:')
    for i in range(nums[0]):
        logging.info('\t{}, {}, {}'.format(class_names[int(classes[0][i])],
                                           np.array(scores[0][i]),
                                           np.array(boxes[0][i])))

    img_to_draw = draw_outputs(img_to_draw, (boxes, scores, classes, nums),
                               class_names)
    cv2.imwrite(FLAGS.output, img_to_draw)
    logging.info('output saved to: {}'.format(FLAGS.output))
예제 #12
0
def test_propagation():
    topic = "span_test"
    channel = Channel(uri=URI, exchange=EXCHANGE)
    subscription = Subscription(channel)
    subscription.subscribe(topic)

    tracer = Tracer()
    with tracer.span(name="span_name") as span:
        span_id = span.span_id
        message = Message()
        message.body = "body".encode('latin1')
        message.inject_tracing(span)
        channel.publish(topic=topic, message=message)

    message2 = channel.consume(timeout=1.0)
    span_context = message2.extract_tracing()

    assert span_context.span_id == span_id
    assert span_context.trace_id == tracer.tracer.span_context.trace_id
예제 #13
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()
예제 #14
0
def test_body(size):
    channel = Channel(uri=URI, exchange=EXCHANGE)

    subscription = Subscription(channel)
    subscription.subscribe("MyTopic.Sub.Sub")

    sent = Message()
    sent.reply_to = subscription
    sent.topic = "MyTopic.Sub.Sub"
    sent.body = bytes(bytearray(range(256)) * int(size))

    channel.publish(message=sent)
    received = channel.consume(timeout=1.0)

    assert repr(sent.body) == repr(received.body)
    assert sent.body == received.body

    channel.close()
예제 #15
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()
예제 #16
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
예제 #17
0
from is_wire.core import Channel, Subscription, Message
from is_msgs.robot_pb2 import RobotConfig
import json
import time

options = json.load(open("../etc/conf/options.json"))
channel = Channel(options["broker_uri"])
subscription = Subscription(channel)

rid = options["robot_parameters"]["id"]

for i in range(10):
    config = RobotConfig()
    config.speed.linear = -0.2
    set_req = Message(content=config, reply_to=subscription)
    channel.publish(topic="RobotGateway.{}.SetConfig".format(rid),
                    message=set_req)
    set_rep = channel.consume(timeout=0.05)
    print("set:", set_rep.status)

    get_req = Message(reply_to=subscription)
    channel.publish(topic="RobotGateway.{}.GetConfig".format(rid),
                    message=get_req)
    get_rep = channel.consume(timeout=0.05)
    print("get:", get_rep.status, get_rep.unpack(RobotConfig))

    time.sleep(0.1)

config = RobotConfig()
config.speed.linear = 0.0
set_config_req = Message(content=config, reply_to=subscription)
예제 #18
0
from is_wire.core import Channel, Subscription, Message
from is_msgs.robot_pb2 import RobotConfig
import os
from sys import argv

uri = os.environ[
    "BROKER_URI"] if "BROKER_URI" in os.environ else "amqp://10.10.2.20:30000"

channel = Channel(uri)
subscription = Subscription(channel)

config = RobotConfig()
config.speed.linear = float(argv[1] or 0.0)
config.speed.angular = float(argv[2] if len(argv) is 3 else 0.0)

channel.publish(message=Message(content=config, reply_to=subscription),
                topic="RobotGateway.0.SetConfig")

reply = channel.consume(timeout=1.0)
print reply.status

channel.publish(message=Message(reply_to=subscription),
                topic="RobotGateway.0.GetConfig")

reply = channel.consume(timeout=1.0)
print reply.unpack(RobotConfig)
예제 #19
0
    return op


# Carrega parametros do robo e endereco do broker do arquivo Json
op_config = load_options()

ATSPlog = Logger(name='unpack')

service_name = "RobotGateway.{}".format(op_config.robot_parameters.id)
sonar_topic = "RobotGateway.{}.SonarScan".format(op_config.robot_parameters.id)
pose_topic = "RobotGateway.{}.Pose".format(op_config.robot_parameters.id)

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

# Inscreve nos topicos que deseja receber mensagem
subscription = Subscription(channel)
subscription.subscribe(pose_topic)
subscription.subscribe(sonar_topic)
ATSPlog.info("SubscriptionsDone")

# Envia mensagem de getConfig
get_req = Message(reply_to=subscription)
# Salva correlation_id do request
cor_id = get_req.correlation_id
# print("cor_id: ", cor_id)
# Broadcast message to anyone interested (subscribed)
channel.publish(message=get_req, topic=service_name + ".GetConfig")
예제 #20
0
            annotations_data = json.load(f)
        n_annotations_on_file = len(annotations_data['annotations'])
        if n_annotations_on_file == n_frames:
            log.info(
                "Video '{}' already annotated at '{}' with {} annotations",
                video_file, annotations_data['created_at'],
                n_annotations_on_file)
            continue

    pending_videos.append(video_file)
    n_annotations[base_name] = n_frames
if len(pending_videos) == 0:
    log.info("Exiting...")
    sys.exit(-1)

channel = Channel(options.broker_uri)
subscription = Subscription(channel)

requests = {}
annotations_received = defaultdict(dict)
state = State.MAKE_REQUESTS
frame_fetcher = FrameVideoFetcher(video_files=pending_videos,
                                  base_folder=options.folder)

while True:
    if state == State.MAKE_REQUESTS:
        state = State.RECV_REPLIES
        if len(requests) < MIN_REQUESTS:
            while len(requests) <= MAX_REQUESTS:
                base_name, frame_id, frame = frame_fetcher.next()
                if frame is None:
def navigate(goalX, goalY, robotArUco, worldFrame, mapFile, step, robot_size,
             N_KNN, MAX_EDGE_LEN, show_path):

    exporter = ZipkinExporter(
        service_name="Robot.Controller",
        host_name="10.10.2.13",
        port="30200",
        transport=AsyncTransport,
    )

    # Create a channel to connect to the broker
    channel = Channel("amqp://10.10.2.13:30000")
    # Create a subscription
    subscription = Subscription(channel)

    # Subscribe to the following topics:
    # - To get the robot's current position in relation where it was turned on, i.e., dead reckoning odometry
    # - To get the position of the ArUco marker attached to the robot's back

    #robotArUco = 8  # ArUco marker ID attached to the robot's back
    #worldFrame = 1000    # Number of the world reference frame in the HPN Intelligent Space

    awarenessOff(channel)
    time.sleep(6)  # to wait some time to be sure the awareness if off

    topicGetRobotOdometry = "FrameTransformation.2000.2001"
    topicGetArUcoRobotBack = "FrameTransformation." + str(
        robotArUco + 100) + "." + str(worldFrame)

    subscription.subscribe(topicGetRobotOdometry)
    subscription.subscribe(topicGetArUcoRobotBack)

    # Initialise transformation matrices used for storing odometry and correction
    pepperPose = np.identity(4)
    robotOriginToWorld = np.identity(4)
    lastOdometry = np.identity(4)

    # Load the frame transformation between the ArUco marker on the robot's back and the robot's base frame.
    fileName = "frameArUcoRobot.dat"
    arUcoToRobot = read_frameTransformation(fileName)
    robotToArUco = inv(arUcoToRobot)

    print("Goal: ", goalX, "  ", goalY)

    # Localize the robot before start path planning

    robotLocalized = False
    notSeen = 0
    count = 0

    while not robotLocalized:
        # Source must be the current position of the robot in the world frame
        message = channel.consume()
        if (message.topic == topicGetRobotOdometry):
            print("reading odometry")
            # get the transformation matrix corresponding to the current rotation and position of the robot
            lastOdometry = unpackFrameTransformation(message)
            notSeen = notSeen + 1
            print(notSeen)

        if (message.topic == topicGetArUcoRobotBack):
            print("correcting odometry")
            # get the frame transformation betweeb the ArUco marker on the robot's back and the world
            arUcoToWorld = unpackFrameTransformation(message)
            # calculates the robot pose in the world frame
            pepperPose = arUcoToWorld * robotToArUco
            # calculate the frame transformation needed to correct robot's odometry while the ArUco marker is not seen by the intelligent space
            robotOriginToWorld = pepperPose * inv(lastOdometry)

            sourceX = pepperPose[0, 3]
            sourceY = pepperPose[1, 3]
            print("x= ", sourceX, " y= ", sourceY)
            robotLocalized = True
            notSeen = 0

        if notSeen > 30:
            notSeen = 0
            count = count + 1
            # unsubscribe to not accumulate messages
            subscription.unsubscribe(topicGetRobotOdometry)
            subscription.unsubscribe(topicGetArUcoRobotBack)

            if count > 4:
                print("I can't get localized by the Intelligent Space.")
                print(
                    "Please take me to a spot where the marker on my back can be seen by one of the cameras."
                )
                sys.exit(0)

            makeTurn(0, 0.3, channel)
            subscription.subscribe(topicGetRobotOdometry)
            subscription.subscribe(topicGetArUcoRobotBack)

    # unsubscribe to not accumulate messages
    subscription.unsubscribe(topicGetRobotOdometry)
    subscription.unsubscribe(topicGetArUcoRobotBack)

    #sys.exit(0)

    # Create obstacles
    ox, oy = create_virtualObstacles()

    # Call path planning
    # rx, ry contains the positions in the path
    rx, ry = PRM_planning(mapFile, sourceX, sourceY, goalX, goalY, ox, oy,
                          robot_size, step, N_KNN, MAX_EDGE_LEN)

    # Check if a path was found/home/raquel/ProgrammingIS/learningISBristol//
    #assert len(rx) != 0, 'Cannot found path'
    if len(rx) == 0:
        print('Cannot find path')
        raise SystemError

    #sys.exit(0)

    # Plot map points and obstacles
    if show_path:
        map_x, map_y = read_map(mapFile, step)
        plt.plot(ox, oy, ".k")
        plt.plot(sourceX, sourceY, "^r")
        plt.plot(goalX, goalY, "^c")
        plt.plot(map_x, map_y, ".b")
        plt.grid(True)
        plt.axis("equal")
        plt.plot(rx, ry, "-r")
        plt.plot(rx, ry, "og")
        plt.show()

    # Reverse the order of the path (list) returned by the path-planning algorithm
    # The original list contains the goal at the beginning and the source at the end. We need the reverse
    rx = rx[::-1]
    ry = ry[::-1]
    print(rx)
    print(ry)

    #sys.exit(0)

    # Subscribe to the previous topics
    subscription.subscribe(topicGetRobotOdometry)
    subscription.subscribe(topicGetArUcoRobotBack)

    i = 0
    k = 0
    stuck = 0
    dist = 100.0
    threshold = 0.2

    try:
        while True:

            try:

                # listen the channelprint(frameArUcoRobot)
                message = channel.consume(timeout=0.5)

                spanr = message.extract_tracing()
                tracer = Tracer(exporter, spanr)
                tracer.start_span(name="Navigate")
                # Check if the message received is the robot's odometry - FrameTransformation type
                if (message.topic == topicGetRobotOdometry):
                    # get the transformation matrix corresponding to the current rotation and position of the robot
                    lastOdometry = unpackFrameTransformation(message)
                    pepperPose = robotOriginToWorld * lastOdometry

                    #print(pepperPose)

                elif (message.topic == topicGetArUcoRobotBack):

                    print("Odometry Corrected")
                    # get the transformation matrix corresponding to the current pose of the robot corrected when
                    # it sees an ArUco marker
                    arUcoToWorld = unpackFrameTransformation(message)
                    pepperPose = arUcoToWorld * robotToArUco
                    robotOriginToWorld = pepperPose * inv(lastOdometry)
            except socket.timeout:

                print("Time out")

            # matrix Inverse
            toPepperFrame = inv(pepperPose)
            # transform the goal from the world frame to the robot frame
            posX, posY, posZ = changeRefFrame(rx[i], ry[i], 0, toPepperFrame)

            distPrevious = dist
            dist = math.sqrt(posX**2 + posY**2)
            #print(dist)
            # If distance to current goal is less than the threshold, pick the next point in the path to be the next goal
            if dist < threshold:
                i = i + 1
                stuck = 0
                print(dist)
                print("Path index: ", i, "  of ", len(rx))

                if i == (len(rx) - 1):
                    threshold = 0.5

                # If that was the last point in the path, finish navigation. Goal achieved.
                if i >= len(rx):

                    print("Goal achieved")
                    break
                # If not the last point in the path, get the next point and converte it to robot frame
                print("Next point in the path")
                posX, posY, posZ = changeRefFrame(rx[i], ry[i], 0,
                                                  toPepperFrame)
                # Command robot to move
                commandMoveTo(posX, posY, channel)
                #commandNavigateTo(posX,posY,channel)

            # If distance to current goal is greater than the threshold, check if robot is stopped
            # To check if robot is stopped, calculate the difference between current distance and previous one
            elif abs(dist - distPrevious
                     ) < 0.005:  # if difference is less than 0.5 cm
                k = k + 1  # accumulate
                if k == 20:  #see if situation remains for 20 times
                    # Robot is stuck. Let's send a move command again
                    print(dist)
                    k = 0
                    print(
                        "Ooops.... I got stuck.... I will try to move. Stuck = ",
                        stuck)
                    posX, posY, posZ = changeRefFrame(rx[i], ry[i], 0,
                                                      toPepperFrame)

                    stuck = stuck + 1
                    if stuck == 4:

                        goBack(-10, 0, channel)
                        stuck = 0
                        posX, posY, posZ = changeRefFrame(
                            rx[i], ry[i], 0, toPepperFrame)
                        # Command robot to move
                        commandMoveTo(posX, posY, channel)
                    else:
                        commandMoveTo(posX, posY, channel)
            tracer.end_span()

    except KeyboardInterrupt:

        commandMoveTo(0, 0, channel)

    #awarenessOff(channel)

    awarenessOn(channel)
    time.sleep(6)
예제 #22
0
from is_wire.core import Channel, Message, Subscription
from is_msgs.common_pb2 import Position, Pose
from is_msgs.camera_pb2 import FrameTransformation
import numpy as np  #
from numpy.linalg import inv
import math

# Create a channel to connect to the broker
channel = Channel("amqp://10.10.2.20:30000")
# Create a subscription
subscription = Subscription(channel)

# Subscribe to get the relation from the initial reference frame where the robot was
# turned on and its current reference frame (dead reckoning odometry)
##################subscription.subscribe("FrameTransformation.1000.2000")

subscription.subscribe("FrameTransformation.2000.2001")
subscription.subscribe("FrameTransformation.2001.1003")

# Goal in the World Frame
# Change the goals value to make the robot move to different coordinates.
goalX = 0
goalY = 0
#goalWorldFrame = math.reshape(math.matrix([goalX, goalY, 0, 1]), [4, 1])
goalWorldFrame = np.matrix([goalX, goalY, 0, 1]).T

# Initialize transformation matrices used for storing odometry and correction
pepperPose = np.identity(4)
robotToWorld = np.identity(4)

# Change this variable to test between NavigateTo and MoveTo
import cv2
import time
import numpy as np
from is_msgs.image_pb2 import Image, ObjectAnnotations
from is_wire.core import Channel, Subscription, Message, Logger
from is_wire.core import Tracer, ZipkinExporter, BackgroundThreadTransport

log = Logger(name='Publisher')

broker_uri = 'amqp://localhost:5672'
if len(sys.argv) > 2:
    log.critical('Invalid arguments. Try: python requester.py <BROKER_URI>')
if len(sys.argv) > 1:
    broker_uri = sys.argv[1]

channel = Channel(broker_uri)
subscription = Subscription(channel)
exporter = ZipkinExporter(
    service_name='SkeletonsDetectorRequester',
    host_name='localhost',
    port=9411,
    transport=BackgroundThreadTransport(max_batch_size=100),
)

image = cv2.imread('../image.png')

tracer = Tracer(exporter)
with tracer.span(name='image') as span:
    cimage = cv2.imencode(ext='.jpeg', img=image, params=[cv2.IMWRITE_JPEG_QUALITY, 80])
    data = cimage[1].tobytes()
    im = Image(data=data)
import sys
from is_wire.core import Channel, Subscription, Message, Logger
from is_wire.core.wire.status import StatusCode
from is_msgs.camera_pb2 import CameraConfig
from google.protobuf.json_format import Parse

# necessery to create a CameraConfig message
from google.protobuf.wrappers_pb2 import FloatValue
from is_msgs.common_pb2 import SamplingSettings
from is_msgs.image_pb2 import ImageSettings, Resolution, ColorSpace, ColorSpaces

uri = 'amqp://10.10.2.15:30000'
channel = Channel(uri)
subscription = Subscription(channel)
log = Logger(name='SetConfig')
camera_id = 0
""" 
    Loading CameraConfig protobuf from a json file
"""
with open('camera_config.json', 'r') as f:
    try:
        set_config = Parse(f.read(), CameraConfig())
        log.info('CameraConfig:\n{}', set_config)
    except Exception as ex:
        log.critical('Unable to camera settings. \n{}', ex)
"""
    Another way to create a CameraConfig message
"""
set_config = CameraConfig(
    sampling=SamplingSettings(frequency=FloatValue(value=5.0)),
    image=ImageSettings(
예제 #25
0
from __future__ import print_function
from is_wire.core import Channel, Subscription
from is_msgs.common_pb2 import Tensor
from is_msgs.camera_pb2 import FrameTransformations
import numpy as np

# Connect to the broker
channel = Channel("amqp://10.10.2.23:30000")

# Subscribe to the desired topic(s)
subscription = Subscription(channel)
topic02 = "ArUco.7.FrameTransformations"  # get relation between camera 7 and the ArUco detected
subscription.subscribe(topic02)

# Blocks forever waiting for message

diretArucoPose = np.matrix('0,0,0,0;0,0,0,0;0,0,0,0;0,0,0,0')
matrix = np.matrix('0,0,0,0;0,0,0,0;0,0,0,0;0,0,0,0')

# Compare the Frame Transforamtion obtained directly from the Aruco detecion service  when an Aruco Marker is seen
# with the calculated Frame Transforamtion when considering the camera extrinsic matrix and the Aruco Marker position in the world
while True:
    message = channel.consume()

    # Get the Frame Transformation that represents the pose of the Aruco mark in the camera 7 reference frame
    # Then multiply by the extrinsic matrix of camera 7 to obtain the Aruco pose in world reference frame
    if message.topic == topic02:
        # Message returns a list of Frame Transformations
        frameTransList = message.unpack(FrameTransformations)
        # Check if there is any element (Frame Transformation) in the list
        if frameTransList.tfs:
예제 #26
0
from is_wire.core import Channel, Subscription, Message, Logger
from is_msgs.common_pb2 import Position
import os
from sys import argv, exit

log = Logger(name="client")

uri = os.environ[
    "BROKER_URI"] if "BROKER_URI" in os.environ else "amqp://10.10.2.20:30000"
log.info("uri={}", uri)
if len(argv) != 3:
    log.error("Usage: python navigate.py <X> <Y>")
    exit(-1)

channel = Channel(uri)
subscription = Subscription(channel)

position = Position()
position.x = float(argv[1])
position.y = float(argv[2])

channel.publish(message=Message(content=position, reply_to=subscription),
                topic="RobotGateway.0.NavigateTo")

reply = channel.consume(timeout=1.0)
log.info("status={}", reply.status)
from __future__ import print_function
from is_wire.core import Channel, Subscription, Message
from np_pb import to_tensor, to_np
from is_msgs.common_pb2 import Tensor
import numpy as np 



# This program shows how to publish a message using 
# the Intelligent Space framework

# Connect to the broker
channel = Channel("amqp://10.10.2.23:30000")

# Create the message that is a matrix
message = Message()
test = np.array([[1, 2, 3, 4],[ 5, 6, 7, 8],[ 9, 10, 11, 12],[ 13, 14, 15, 16]])
# Convert to Tensor
test2 = to_tensor(test)
message.pack(test2)


# Define topic name
Topic= "Aula01"
message.topic = Topic  

# Publish message under the topic
channel.publish(message)


예제 #28
0
    log.warn(
        'Path to SUBJECT_ID={} LABEL={} ({}) already exists.\n \
      Would you like to proceed? All data will be deleted! [y/n]', subject_id,
        label_id, labels[label_id])
    key = input()
    if key == 'y':
        shutil.rmtree(sequence_folder)
    elif key == 'n':
        sys.exit(0)
    else:
        log.critical('Invalid command \'{}\', exiting.', key)
        sys.exit(-1)

os.makedirs(sequence_folder)

channel = Channel(op.broker_uri)
subscription = Subscription(channel)

if device == "webcam":
    # subscribe to one camera
    subscription.subscribe('CameraGateway.{}.Frame'.format(cam.id))

elif device == "cameras":
    # subscribe to multiple cameras
    for c in cam:
        subscription.subscribe('CameraGateway.{}.Frame'.format(c.id))

    # get display image size
    size = (2 * cam[0].config["image"]["resolution"]["height"],
            2 * cam[0].config["image"]["resolution"]["width"], 3)
    # create empty image do display
예제 #29
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
from is_wire.core import Channel, Logger
from src.utils.is_wire import RequestManager

from is_msgs.common_pb2 import Pose, Position

log = Logger(name='Client')

channel = Channel('amqp://localhost:5672')
request_manager = RequestManager(channel,
                                 min_requests=15,
                                 max_requests=30,
                                 log_level=Logger.INFO)

poses = [(Pose(position=Position(x=i, y=2 * i)), i) for i in range(100)]

while True:

    while request_manager.can_request() and len(poses) > 0:
        pose, pose_id = poses.pop()
        request_manager.request(content=pose,
                                topic="GetPosition",
                                timeout_ms=1000,
                                metadata=pose_id)
        log.info('{:>6s} msg_id={}', " >>", pose_id)

    received_msgs = request_manager.consume_ready(timeout=1.0)

    for msg, metadata in received_msgs:
        position = msg.unpack(Position)
        log.info('{:<6s} msg_id={}', "<< ", metadata)