Skip to content

Commit

Permalink
Merge pull request #93 from YuanYuYuan/fix/python-example
Browse files Browse the repository at this point in the history
fix: wrap zenoh-python sessions in context manager
  • Loading branch information
wyfo authored Jan 21, 2025
2 parents c2f9c8e + f7c034d commit 0c6089e
Showing 1 changed file with 28 additions and 29 deletions.
57 changes: 28 additions & 29 deletions content/docs/getting-started/first-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ Let us take a step-by-step approach in putting together your first Zenoh applica
As the first step, let us see how we get some data from a temperature sensor in our kitchen.
Then we see how we can route this data to store and perform some analytics.

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

<b>Zenoh</b> deals with <i>keys/values</i> where each key is a <i>path</i> and is associated to a <i>value</i>. A key 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...).
encodings (string, JSON, raw bytes buffer...).
<!-- To query the values stored by Zenoh, we use <i>selectors</i>. As the name suggest, a <i>selector</i> can use wildcards, such as <b>*</b> and <b>**</b> to represent a set of paths, such as, ```myhome/*/temp```. -->

Let's get started!
Expand All @@ -37,15 +37,15 @@ def read_temp():
return random.randint(15, 30)

if __name__ == "__main__":
session = zenoh.open(zenoh.Config())
key = 'myhome/kitchen/temp'
pub = session.declare_publisher(key)
while True:
t = read_temp()
buf = f"{t}"
print(f"Putting Data ('{key}': '{buf}')...")
pub.put(buf)
time.sleep(1)
with zenoh.open(zenoh.Config()) as session:
key = 'myhome/kitchen/temp'
pub = session.declare_publisher(key)
while True:
t = read_temp()
buf = f"{t}"
print(f"Putting Data ('{key}': '{buf}')...")
pub.put(buf)
time.sleep(1)
```

Now we need a subscriber, `z_subscriber.py` that can receive the measurements:
Expand All @@ -55,19 +55,19 @@ import zenoh, time

def listener(sample):
print(f"Received {sample.kind} ('{sample.key_expr}': '{sample.payload.to_string()}')")

if __name__ == "__main__":
session = zenoh.open(zenoh.Config())
sub = session.declare_subscriber('myhome/kitchen/temp', listener)
time.sleep(60)
with zenoh.open(zenoh.Config()) as session:
sub = session.declare_subscriber('myhome/kitchen/temp', listener)
time.sleep(60)
```

Start the subscriber:
```bash
python3 z_subscriber.py
```
The subscriber waits for an update on `myhome/kitchen/temp`.

Now start `z_sensor.py` as follows
```bash
python3 z_sensor.py
Expand All @@ -78,7 +78,7 @@ You can see the values produced by the sensor being consumed by the subscriber.
## Store and Query in Zenoh

As the next step, let's see how the value generated by a publisher can be stored in Zenoh.
For this, we use [Zenoh router](../installation) (`zenohd`).
For this, we use [Zenoh router](../installation) (`zenohd`).
By default, a Zenoh router starts without any storage. In order to store the temperature, we need to configure one.
Create a `zenoh-myhome.json5` configuration file for Zenoh with this content:
```json5
Expand Down Expand Up @@ -107,24 +107,23 @@ Create a `zenoh-myhome.json5` configuration file for Zenoh with this content:
zenohd -c zenoh-myhome.json5
```

Now the data generated by our temperature sensor is stored in memory.
Now the data generated by our temperature sensor is stored in memory.
We can retrieve the latest temperature value stored in Zenoh:

```python
import zenoh

if __name__ == "__main__":
session = zenoh.open()
replies = session.get('myhome/kitchen/temp')
for reply in replies:
try:
print("Received ('{}': '{}')"
.format(reply.ok.key_expr, reply.ok.payload.to_string()))
except:
print("Received (ERROR: '{}')"
.format(reply.err.payload.to_string()))

session.close()
with zenoh.open(zenoh.Config()) as session:
replies = session.get('myhome/kitchen/temp')
for reply in replies:
try:
print("Received ('{}': '{}')"
.format(reply.ok.key_expr, reply.ok.payload.to_string()))
except:
print("Received (ERROR: '{}')"
.format(reply.err.payload.to_string()))

```
## Other examples

Expand Down

0 comments on commit 0c6089e

Please sign in to comment.