This commit is contained in:
2026-02-25 08:54:04 +07:00
parent 647cadf497
commit f8235e1a59
2 changed files with 48 additions and 44 deletions

View File

@@ -109,11 +109,11 @@ from nats_bridge import smartsend
# Send a text message (is_publish=True by default)
data = [("message", "Hello World", "text")]
env, env_json_str = smartsend("/chat/room1", data, nats_url="nats://localhost:4222")
env, env_json_str = smartsend("/chat/room1", data, broker_url="nats://localhost:4222")
print("Message sent!")
# Or use is_publish=False to get envelope and JSON without publishing
env, env_json_str = smartsend("/chat/room1", data, nats_url="nats://localhost:4222", is_publish=False)
env, env_json_str = smartsend("/chat/room1", data, broker_url="nats://localhost:4222", is_publish=False)
# env: MessageEnvelope object
# env_json_str: JSON string for publishing to NATS
```
@@ -126,14 +126,14 @@ const { smartsend } = require('./src/NATSBridge');
// Send a text message (isPublish=true by default)
await smartsend("/chat/room1", [
{ dataname: "message", data: "Hello World", type: "text" }
], { natsUrl: "nats://localhost:4222" });
], { brokerUrl: "nats://localhost:4222" });
console.log("Message sent!");
// Or use isPublish=false to get envelope and JSON without publishing
const { env, env_json_str } = await smartsend("/chat/room1", [
{ dataname: "message", data: "Hello World", type: "text" }
], { natsUrl: "nats://localhost:4222", isPublish: false });
], { brokerUrl: "nats://localhost:4222", isPublish: false });
// env: MessageEnvelope object
// env_json_str: JSON string for publishing to NATS
```
@@ -145,8 +145,8 @@ using NATSBridge
# Send a text message
data = [("message", "Hello World", "text")]
env, env_json_str = smartsend("/chat/room1", data, nats_url="nats://localhost:4222")
# env: msgEnvelope_v1 object with all metadata and payloads
env, env_json_str = smartsend("/chat/room1", data, broker_url="nats://localhost:4222")
# env: msg_envelope_v1 object with all metadata and payloads
# env_json_str: JSON string representation of the envelope for publishing
println("Message sent!")
```
@@ -208,7 +208,7 @@ config = {
# Send as dictionary type
data = [("config", config, "dictionary")]
env, env_json_str = smartsend("/device/config", data, nats_url="nats://localhost:4222")
env, env_json_str = smartsend("/device/config", data, broker_url="nats://localhost:4222")
```
#### JavaScript
@@ -224,7 +224,7 @@ const config = {
const { env, env_json_str } = await smartsend("/device/config", [
{ dataname: "config", data: config, type: "dictionary" }
]);
], { brokerUrl: "nats://localhost:4222" });
```
#### Julia
@@ -239,7 +239,7 @@ config = Dict(
)
data = [("config", config, "dictionary")]
env, env_json_str = smartsend("/device/config", data)
env, env_json_str = smartsend("/device/config", data, broker_url="nats://localhost:4222")
```
### Example 2: Sending Binary Data (Image)
@@ -255,7 +255,7 @@ with open("image.png", "rb") as f:
# Send as binary type
data = [("user_image", image_data, "binary")]
env, env_json_str = smartsend("/chat/image", data, nats_url="nats://localhost:4222")
env, env_json_str = smartsend("/chat/image", data, broker_url="nats://localhost:4222")
```
#### JavaScript
@@ -269,7 +269,7 @@ const image_data = fs.readFileSync('image.png');
const { env, env_json_str } = await smartsend("/chat/image", [
{ dataname: "user_image", data: image_data, type: "binary" }
]);
], { brokerUrl: "nats://localhost:4222" });
```
#### Julia
@@ -281,7 +281,7 @@ using NATSBridge
image_data = read("image.png")
data = [("user_image", image_data, "binary")]
env, env_json_str = smartsend("/chat/image", data)
env, env_json_str = smartsend("/chat/image", data, broker_url="nats://localhost:4222")
```
### Example 3: Request-Response Pattern
@@ -296,11 +296,11 @@ data = [("command", {"action": "read_sensor"}, "dictionary")]
env, env_json_str = smartsend(
"/device/command",
data,
nats_url="nats://localhost:4222",
broker_url="nats://localhost:4222",
reply_to="/device/response",
reply_to_msg_id="cmd-001"
)
# env: msgEnvelope_v1 object
# env: MessageEnvelope object
# env_json_str: JSON string for publishing to NATS
```
@@ -361,7 +361,7 @@ large_data = os.urandom(2_000_000) # 2MB of random data
env, env_json_str = smartsend(
"/data/large",
[("large_file", large_data, "binary")],
nats_url="nats://localhost:4222",
broker_url="nats://localhost:4222",
fileserver_url="http://localhost:8080",
size_threshold=1_000_000
)
@@ -383,6 +383,7 @@ view.fill(42); // Fill with some data
const { env, env_json_str } = await smartsend("/data/large", [
{ dataname: "large_file", data: largeData, type: "binary" }
], {
brokerUrl: "nats://localhost:4222",
fileserverUrl: "http://localhost:8080",
sizeThreshold: 1_000_000
});
@@ -399,6 +400,7 @@ large_data = rand(UInt8, 2_000_000)
env, env_json_str = smartsend(
"/data/large",
[("large_file", large_data, "binary")],
broker_url="nats://localhost:4222",
fileserver_url="http://localhost:8080"
)
@@ -425,7 +427,7 @@ data = [
("user_avatar", image_data, "image")
]
env, env_json_str = smartsend("/chat/mixed", data, nats_url="nats://localhost:4222")
env, env_json_str = smartsend("/chat/mixed", data, broker_url="nats://localhost:4222")
```
#### JavaScript
@@ -446,7 +448,7 @@ const { env, env_json_str } = await smartsend("/chat/mixed", [
data: fs.readFileSync("avatar.png"),
type: "image"
}
]);
], { brokerUrl: "nats://localhost:4222" });
```
#### Julia
@@ -461,7 +463,7 @@ data = [
("user_avatar", image_data, "image")
]
env, env_json_str = smartsend("/chat/mixed", data)
env, env_json_str = smartsend("/chat/mixed", data, broker_url="nats://localhost:4222")
```
### Example 6: Table Data (Arrow IPC)
@@ -483,7 +485,7 @@ df = pd.DataFrame({
# Send as table type
data = [("students", df, "table")]
env, env_json_str = smartsend("/data/students", data, nats_url="nats://localhost:4222")
env, env_json_str = smartsend("/data/students", data, broker_url="nats://localhost:4222")
```
#### Julia
@@ -500,7 +502,7 @@ df = DataFrame(
)
data = [("students", df, "table")]
env, env_json_str = smartsend("/data/students", data)
env, env_json_str = smartsend("/data/students", data, broker_url="nats://localhost:4222")
```
---
@@ -519,7 +521,7 @@ using NATSBridge
# Send dictionary from Julia to JavaScript
config = Dict("step_size" => 0.01, "iterations" => 1000)
data = [("config", config, "dictionary")]
env, env_json_str = smartsend("/analysis/config", data, nats_url="nats://localhost:4222")
env, env_json_str = smartsend("/analysis/config", data, broker_url="nats://localhost:4222")
```
#### JavaScript Receiver
@@ -546,7 +548,7 @@ const { smartsend } = require('./src/NATSBridge');
const { env, env_json_str } = await smartsend("/data/transfer", [
{ dataname: "message", data: "Hello from JS!", type: "text" }
]);
], { brokerUrl: "nats://localhost:4222" });
```
#### Python Receiver
@@ -568,7 +570,7 @@ for dataname, data, type in env["payloads"]:
from nats_bridge import smartsend
data = [("message", "Hello from Python!", "text")]
env, env_json_str = smartsend("/chat/python", data)
env, env_json_str = smartsend("/chat/python", data, broker_url="nats://localhost:4222")
```
#### Julia Receiver
@@ -576,7 +578,7 @@ env, env_json_str = smartsend("/chat/python", data)
```julia
using NATSBridge
env = smartreceive(msg, fileserverDownloadHandler)
env = smartreceive(msg; fileserver_download_handler=_fetch_with_backoff)
for (dataname, data, type) in env["payloads"]
if type == "text"
println("Received from Python: $data")

View File

@@ -136,6 +136,7 @@ class ChatUI {
`/chat/${this.currentRoom}`,
data,
{
brokerUrl: window.config.broker_url,
fileserverUrl: window.config.fileserver_url,
sizeThreshold: window.config.size_threshold
}
@@ -288,8 +289,8 @@ Let's build a file transfer system that handles large files efficiently.
const { smartsend } = require('./NATSBridge');
class FileUploadService {
constructor(natsUrl, fileserverUrl) {
this.natsUrl = natsUrl;
constructor(brokerUrl, fileserverUrl) {
this.brokerUrl = brokerUrl;
this.fileserverUrl = fileserverUrl;
}
@@ -308,7 +309,7 @@ class FileUploadService {
`/files/${recipient}`,
data,
{
natsUrl: this.natsUrl,
brokerUrl: this.brokerUrl,
fileserverUrl: this.fileserverUrl,
sizeThreshold: 1048576
}
@@ -419,7 +420,7 @@ async function uploadFile(config) {
const filePath = await rl.question('Enter file path: ');
const recipient = await rl.question('Enter recipient: ');
const fileService = new FileUploadService(config.nats_url, config.fileserver_url);
const fileService = new FileUploadService(config.broker_url, config.fileserver_url);
try {
const env = await fileService.uploadFile(filePath, recipient);
@@ -500,8 +501,8 @@ import time
import random
class SensorSender:
def __init__(self, nats_url: str, fileserver_url: str):
self.nats_url = nats_url
def __init__(self, broker_url: str, fileserver_url: str):
self.broker_url = broker_url
self.fileserver_url = fileserver_url
def send_reading(self, sensor_id: str, value: float, unit: str):
@@ -518,7 +519,7 @@ class SensorSender:
smartsend(
f"/sensors/{sensor_id}",
data,
nats_url=self.nats_url,
broker_url=self.broker_url,
fileserver_url=self.fileserver_url
)
@@ -537,7 +538,7 @@ class SensorSender:
env, env_json_str = smartsend(
f"/sensors/{sensor_id}/prepare",
data,
nats_url=self.nats_url,
broker_url=self.broker_url,
fileserver_url=self.fileserver_url,
is_publish=False
)
@@ -572,7 +573,7 @@ class SensorSender:
smartsend(
f"/sensors/batch",
data,
nats_url=self.nats_url,
broker_url=self.broker_url,
fileserver_url=self.fileserver_url
)
else:
@@ -631,17 +632,17 @@ Let's build an IoT device using Micropython that connects to NATS.
import json
class DeviceConfig:
def __init__(self, ssid, password, nats_url, device_id):
def __init__(self, ssid, password, broker_url, device_id):
self.ssid = ssid
self.password = password
self.nats_url = nats_url
self.broker_url = broker_url
self.device_id = device_id
def to_dict(self):
return {
"ssid": self.ssid,
"password": self.password,
"nats_url": self.nats_url,
"broker_url": self.broker_url,
"device_id": self.device_id
}
```
@@ -656,7 +657,7 @@ import json
class DeviceBridge:
def __init__(self, config):
self.config = config
self.nats_url = config.nats_url
self.broker_url = config.broker_url
def connect(self):
# Connect to WiFi
@@ -676,7 +677,7 @@ class DeviceBridge:
smartsend(
f"/devices/{self.config.device_id}/status",
data,
nats_url=self.nats_url
broker_url=self.broker_url
)
def send_sensor_data(self, sensor_id, value, unit):
@@ -687,7 +688,7 @@ class DeviceBridge:
smartsend(
f"/devices/{self.config.device_id}/sensors/{sensor_id}",
data,
nats_url=self.nats_url
broker_url=self.broker_url
)
def receive_commands(self, callback):
@@ -725,7 +726,7 @@ import random
config = DeviceConfig(
ssid="MyNetwork",
password="password123",
nats_url="nats://localhost:4222",
broker_url="nats://localhost:4222",
device_id="device-001"
)
@@ -774,8 +775,8 @@ import pyarrow as pa
import io
class DashboardServer:
def __init__(self, nats_url, fileserver_url):
self.nats_url = nats_url
def __init__(self, broker_url, fileserver_url):
self.broker_url = broker_url
self.fileserver_url = fileserver_url
def broadcast_data(self, df):
@@ -792,7 +793,7 @@ class DashboardServer:
smartsend(
"/dashboard/data",
data,
nats_url=self.nats_url,
broker_url=self.broker_url,
fileserver_url=self.fileserver_url
)
@@ -836,6 +837,7 @@ class DashboardUI {
const { env, env_json_str } = await smartsend("/dashboard/request", [
{ dataname: "request", data: { type: "refresh" }, type: "dictionary" }
], {
brokerUrl: window.config.broker_url,
fileserverUrl: window.config.fileserver_url
});
}
@@ -954,7 +956,7 @@ def send_batch_readings(self, readings):
smartsend(
"/sensors/batch",
[("batch", arrow_data, "table")],
nats_url=self.nats_url
broker_url=self.broker_url
)
```