Your First zenoh app

Getting started with zenoh is quite straightforward. Below we will show you how to create a simple telemetry application. Let’s assume that we have some sensor, say a temperature sensor, and we want to store this temperature into a zenoh storage. Later on, we want to retrieve this temperature from the zenoh storage.

Before cranking some code, let’s define some terminology.

zenoh deals with keys/values where each key is a path and is associated to a value. A path looks like just a Unix file system path, such as /myhome/kitchen/temp. The value can be defined with different encodings (string, JSON, raw bytes buffer…).

To query the values stored by zenoh, we use selectors. As the name suggest, a selector can uses wildcards, such as * and ** to represent a set of paths, such as, /myhome/*/temp.

Let’s get started!

zenoh Programming in Python

By default, a zenoh router starts without any storage. In order to store the temperature, we need to add one. The code below create a storage in zenoh memory that will store any key starting with /myhome/:

from zenoh import Zenoh

if __name__ == "__main__":        
    z = Zenoh.login(None)
    z.admin().add_storage('mystorage', {'selector': '/myhome/**'})

Now let’s write an application that will produce temperature measurements at each second:

from zenoh import Zenoh, Encoding, Value
import random
import time

random.seed()

def read_temp():
    return random.randint(15, 30)    

def run_sensor_loop(w):
    # read and produce e temperature every second
    while True:
        t = read_temp()
        w.put('/myhome/kitcken/temp', Value(str(t), encoding=Encoding.STRING))
        time.sleep(1)

if __name__ == "__main__":        
    z = Zenoh.login(None)
    w = z.workspace('/')
    run_sensor_loop(w)

Below is the application that will retrieve the latest temperature value stored in zenoh:

from zenoh import Zenoh

if __name__ == "__main__":        
    z = Zenoh.login(None)
    w = z.workspace('/')
    results = w.get('/myhome/kitcken/temp')
    key, value = results[0].path, results[0].value
    print('  {} : {}'.format(key, value))

Finally, if ever we want to receive the temperatures in direct from the publisher, without querying the zenoh storage, we can use a subscriber:

from zenoh import Zenoh, ChangeKind
import time

def listener(changes):
    for change in changes:
        if change.get_kind() == ChangeKind.PUT:
            print('Publication received: "{}" = "{}"'
                  .format(change.get_path(), change.get_value()))

if __name__ == "__main__":        
    z = Zenoh.login(None)
    w = z.workspace('/')
    results = w.subscribe('/myhome/kitcken/temp', listener)
    time.sleep(60)

Other code examples

Now you can also have a look to the examples provided with each client API:

Next up: Abstractions