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

View File

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