Esempio n. 1
0
if __name__ == "__main__":
    if len(sys.argv) < 5:
        print(
            "Usage <address of zenohd router> <rostopic> <rostopic hz> <replay secs>"
        )
    address = sys.argv[1]
    rostopic = sys.argv[2]
    sample_rate = int(sys.argv[3])
    duration = int(sys.argv[4])

    conf = {
        'mode': 'client',
        'peer': '{}'.format(address),
    }

    print("Opening Zenoh session...")
    zenoh = Zenoh(conf)
    print(
        "Server connected to Zenoh router {}, publishing on rostopic {}, at rate {}"
        .format(address, rostopic, sample_rate))
    # Zenoh workspace creation
    print("New Zenoh workspace...")
    workspace = zenoh.workspace(storage_path)

    app = create_app(workspace, rostopic, sample_rate, duration)
    app.register_blueprint(route_blueprint)
    app.run(host='0.0.0.0', port=5000, debug=True)

    # Shutting down Zenoh
    zenoh.close()
        )  # be aware that this can overwrite a smarter model if this application is stopped and restarted
    else:
        global_model.load_state_dict(torch.load('global.pt'))
else:
    torch.save(
        global_model.state_dict(), 'global.pt'
    )  # be aware that this can overwrite a smarter model if this application is stopped and restarted

# initiate logging
zenoh.init_logger()

print("Opening session...")
z = Zenoh(conf)

print("New workspace...")
workspace = z.workspace()

# 0 - Put global model to a path where clients can get it
print("Put global model in /federated/nodes/global")
save_and_put_global_parameters(global_model.state_dict())

# 1 - Listen for notifications
notification_selector = selector + '/notifications'
print("Subscribed to '{}'...".format(notification_selector))
notification_subscriber = workspace.subscribe(notification_selector,
                                              notification_listener)

print("Press q to stop...")
c = '\0'
while c != 'q':
    c = sys.stdin.read(1)
Esempio n. 3
0
def main(stdscr):
    # --- Command line argument parsing --- --- --- --- --- ---
    parser = argparse.ArgumentParser(prog='zn_sub',
                                     description='zenoh-net sub example')
    parser.add_argument('--mode',
                        '-m',
                        dest='mode',
                        choices=['peer', 'client'],
                        type=str,
                        help='The zenoh session mode.')
    parser.add_argument(
        '--peer',
        '-e',
        dest='peer',
        metavar='LOCATOR',
        action='append',
        type=str,
        help='Peer locators used to initiate the zenoh session.')
    parser.add_argument('--listener',
                        '-l',
                        dest='listener',
                        metavar='LOCATOR',
                        action='append',
                        type=str,
                        help='Locators to listen on.')
    parser.add_argument('--config',
                        '-c',
                        dest='config',
                        metavar='FILE',
                        type=str,
                        help='A configuration file.')
    parser.add_argument('--cmd_vel',
                        dest='cmd_vel',
                        default='/rt/turtle1/cmd_vel',
                        type=str,
                        help='The "cmd_vel" ROS2 topic.')
    parser.add_argument('--rosout',
                        dest='rosout',
                        default='/rt/rosout',
                        type=str,
                        help='The "rosout" ROS2 topic.')
    parser.add_argument('--angular_scale',
                        '-a',
                        dest='angular_scale',
                        default='2.0',
                        type=float,
                        help='The angular scale.')
    parser.add_argument('--linear_scale',
                        '-x',
                        dest='linear_scale',
                        default='2.0',
                        type=float,
                        help='The linear scale.')

    args = parser.parse_args()
    conf = zenoh.config_from_file(
        args.config) if args.config is not None else {}
    if args.mode is not None:
        conf["mode"] = args.mode
    if args.peer is not None:
        conf["peer"] = ",".join(args.peer)
    if args.listener is not None:
        conf["listener"] = ",".join(args.listener)
    cmd_vel = args.cmd_vel
    rosout = args.rosout
    angular_scale = args.angular_scale
    linear_scale = args.linear_scale

    # zenoh-net code  --- --- --- --- --- --- --- --- --- --- ---

    # initiate logging
    zenoh.init_logger()

    print("Openning session...")
    z = Zenoh(conf)
    workspace = z.workspace()

    def rosout_callback(change):
        if change.value is not None:
            log = Log.deserialize(change.value.get_content())
            print('[{}.{}] [{}]: {}'.format(log.stamp.sec, log.stamp.nanosec,
                                            log.name, log.msg))

    print("Subscriber on '{}'...".format(rosout))
    sub = workspace.subscribe(rosout, rosout_callback)

    def pub_twist(linear, angular):
        print("Pub twist: {} - {}".format(linear, angular))
        t = Twist(linear=Vector3(x=linear, y=0.0, z=0.0),
                  angular=Vector3(x=0.0, y=0.0, z=angular))
        workspace.put(cmd_vel, t.serialize())

    while True:
        c = stdscr.getch()
        if c == curses.KEY_UP:
            pub_twist(1.0 * linear_scale, 0.0)
        elif c == curses.KEY_DOWN:
            pub_twist(-1.0 * linear_scale, 0.0)
        elif c == curses.KEY_LEFT:
            pub_twist(0.0, 1.0 * angular_scale)
        elif c == curses.KEY_RIGHT:
            pub_twist(0.0, -1.0 * angular_scale)
        elif c == 27 or c == ord('q'):
            break

    sub.close()
    zenoh.close()
Esempio n. 4
0
from zenoh import Zenoh

if __name__ == "__main__":
    z = Zenoh({})
    w = z.workspace('/')
    results = w.get('/myhome/kitcken/temp')
    key, value = results[0].path, results[0].value
    print('  {} : {}'.format(key, value))
class ZenohNative(ServiceABC):
    """
	A higher level API providing the same abstractions as the zenoh-net API in a simpler and more data-centric oriented
	manner as well as providing all the building blocks to create a distributed storage. The zenoh layer is aware of
	the data content and can apply content-based filtering and transcoding.
	(source: http://zenoh.io/docs/getting-started/key-concepts/)

	Available functionalities:
		[1] put         : push live data to the matching subscribers and storages. (equivalent of zenoh-net write)
		[2] subscribe   : subscriber to live data. (equivalent of zenoh-net subscribe)
		[3] get         : get data from the matching storages and evals. (equivalent of zenoh-net query)
		[4] storage     : the combination of a zenoh-net subscriber to listen for live data to store and a zenoh-net
						  queryable to reply to matching get requests.
		[5] eval        : an entity able to reply to get requests. Typically used to provide data on demand or
						  build a RPC system. (equivalent of zenoh-net queryable)

	Implemented scenarios:
	1. Zenoh SUBSCRIBER
		Sample input: listener=None, mode='peer', peer=None, selector='/demo2/**'
	2. Zenoh PUT
		Sample input: listener=None, mode='peer', path='/demo2/example/test', peer=None, value='Hello World'
	3. Zenoh GET
		Sample input: listener=None, mode='peer', peer=None, selector='/demo/example/**'
	"""
    class ZenohMode(Enum):
        PEER = "peer"
        CLIENT = "client"

    class SessionType(Enum):
        SUBSCRIBER = "SUBSCRIBER"
        PUT = "PUT"
        GET = "GET"

    def __init__(self,
                 _listener=None,
                 _mode="peer",
                 _peer=None,
                 _selector=None,
                 _path=None,
                 _session_type=None):
        super().__init__()
        self.listener = _listener  # Locators to listen on.
        self.mode = _mode  # The zenoh session mode.
        self.peer = _peer  # Peer locators used to initiate the zenoh session.
        self.selector = _selector  # The selection of resources to subscribe.
        self.path = _path  # The name of the resource to put.
        self.session_type = self._get_session_type(
            _session_type)  # Type of Zenoh connection

        # setup configuration
        self.conf = {"mode": self.mode}
        if self.peer is not None:
            self.conf["peer"] = self.peer
        if self.listener is not None:
            self.conf["listener"] = self.listener

        self.workspace = None
        self.z_session = None

        self.pub = None
        self.sub = None

    def _get_session_type(self, _type):
        if _type.upper() == self.SessionType.PUT.value:
            return self.SessionType.PUT.value
        elif _type.upper() == self.SessionType.SUBSCRIBER.value:
            return self.SessionType.SUBSCRIBER.value
        elif _type.upper() == self.SessionType.GET.value:
            return self.SessionType.GET.value
        else:
            return None

    def init_connection(self):
        # initiate logging
        # zenoh.init_logger()

        L.warning("[ZENOH] Openning session...")
        self.z_session = Zenoh(self.conf)

        L.warning("[ZENOH] Create New workspace...")
        self.workspace = self.z_session.workspace()

    def close_connection(self, _subscriber=None):
        self.z_session.close()
        L.warning("[ZENOH] `{}` session has been closed".format(
            self.session_type))

    def register_subscriber(self, listener):
        L.warning("[ZENOH] Registering new consumer")
        self.sub = self.workspace.subscribe(self.selector, listener)

    def register_publisher(self):
        pass  # nothing to do here

    def publish_data(self, val):
        L.warning("[ZENOH] Publish data")
        self.workspace.put(self.path, val)