Ejemplo n.º 1
0
def construct_connection(connection_string):
    """
    Constructs the connection object and returns it.

    The connection string takes the form of protocol@location:port_or_baud
    Examples: sf@localhost:9002
              serial@/dev/ttyUSB0

    :param str connection string: A string in the form of protocol@location:port_or_baud
    :rtype: moteconnection.connection.Connection
    """
    connection = Connection()
    connection.connect(
        connection_string,
        reconnect=10,
        connected=partial(print, "Connected to {}".format(connection_string)),
        disconnected=partial(print, "Disconnected from {}".format(connection_string))
    )

    dispatcher = MessageDispatcher()
    # This example uses a callback function (print in this case). The callback function
    # _must_ take exactly 1 positional argument. That argument will be an instance of
    # `moteconnection.message.Message`.
    # The alternatice method to using a callback function is to pass an instance of
    # `queue.Queue` (python3) or `Queue.Queue` (python2) to these methoods.
    dispatcher.register_default_snooper(print)
    dispatcher.register_default_receiver(print)
    connection.register_dispatcher(dispatcher)
    return connection