diff --git a/README.md b/README.md index bca52f7..7e0fc89 100644 --- a/README.md +++ b/README.md @@ -701,18 +701,24 @@ from nats_bridge import smartreceive, smartsend # Configuration SUBJECT = "/device/command" -REPLY_SUBJECT = "/device/response" NATS_URL = "nats://localhost:4222" async def main(): nc = await nats.connect(NATS_URL) async def message_handler(msg): + # Receive and parse the incoming message envelope env = smartreceive(msg.data) + + # Extract reply_to from the envelope metadata + reply_to = env["reply_to"] + for dataname, data, type in env["payloads"]: if data.get("action") == "read_sensor": response = {"sensor_id": "sensor-001", "value": 42.5} - smartsend(REPLY_SUBJECT, [("data", response, "dictionary")]) + # Send response to the reply_to subject from the request + if reply_to: + smartsend(reply_to, [("data", response, "dictionary")]) sid = await nc.subscribe(SUBJECT, cb=message_handler) await asyncio.sleep(120) @@ -740,7 +746,6 @@ const { connect } = require('nats'); // Configuration const SUBJECT = "/device/command"; -const REPLY_SUBJECT = "/device/response"; const NATS_URL = "nats://localhost:4222"; async function main() { @@ -750,12 +755,19 @@ async function main() { for await (const msg of sub) { const env = await smartreceive(msg); + + // Extract reply_to from the envelope metadata + const replyTo = env["reply_to"]; + for (const payload of env.payloads) { if (payload.dataname === "command" && payload.data.action === "read_sensor") { const response = { sensor_id: "sensor-001", value: 42.5 }; - await smartsend(REPLY_SUBJECT, [ - { dataname: "data", data: response, type: "dictionary" } - ]); + // Send response to the reply_to subject from the request + if (replyTo) { + await smartsend(replyTo, [ + { dataname: "data", data: response, type: "dictionary" } + ]); + } } } } @@ -782,17 +794,23 @@ using NATS, NATSBridge # Configuration const SUBJECT = "/device/command" -const REPLY_SUBJECT = "/device/response" const NATS_URL = "nats://localhost:4222" function test_responder() conn = NATS.connect(NATS_URL) NATS.subscribe(conn, SUBJECT) do msg env = NATSBridge.smartreceive(msg, fileserver_download_handler=_fetch_with_backoff) + + # Extract reply_to from the envelope metadata + reply_to = env["reply_to"] + for (dataname, data, type) in env["payloads"] if dataname == "command" && data["action"] == "read_sensor" response = Dict("sensor_id" => "sensor-001", "value" => 42.5) - smartsend(REPLY_SUBJECT, [("data", response, "dictionary")]) + # Send response to the reply_to subject from the request + if !isempty(reply_to) + smartsend(reply_to, [("data", response, "dictionary")]) + end end end end