Skip to main content

Quick start

In a few minutes you will connect to the WebSocket API, subscribe to device data and see the first uplink. Below are ready-made Python and Node.js examples you can copy and run.

What you need​

  • APP_ID — the application identifier, 8 hex characters, and a token of this application. Both are on the application page in the ONS web interface.
  • Python 3.8 or newer with the websockets library (pip install websockets), or Node.js 22 or newer.
  • At least one device in the application that sends data.

How it works​

  1. The client opens a connection to wss://kz1.orion-m2m.online/ws/v2/?app_id=APP_ID&token=APP_KEY. The server sends a connected message — more in Connection.
  2. The client sends consume_req — a subscription to device data. The "downlink_status": true flag adds messages about the status of frames sent to devices.
  3. The server sends every uplink from devices as a realtime_data message.
  4. To keep the connection open, the client sends ping_req once a minute: without it the server closes the connection after 300 seconds by default.

Try it in the browser​

Connect with your APP_ID and token, choose a command — Playground fills in a request example — and send it. Server responses and device data appear in the log; click an entry to expand it.

Python​

client.py
# Orion Network Server WebSocket API client: connect, subscribe, device data.
# pip install websockets
import asyncio
import json
import os

import websockets

URL = os.environ.get("ONS_URL", "wss://kz1.orion-m2m.online/ws/v2/")
APP_ID = os.environ["ONS_APP_ID"]
TOKEN = os.environ["ONS_TOKEN"]
PING_EVERY = 60 # seconds; without ping_req the server closes the connection after 300 seconds


async def keepalive(ws):
while True:
await asyncio.sleep(PING_EVERY)
await ws.send(json.dumps({"cmd": "ping_req"}))


async def main():
async with websockets.connect(f"{URL}?app_id={APP_ID}&token={TOKEN}") as ws:
hello = json.loads(await ws.recv())
if hello.get("cmd") != "connected" or hello.get("status") != 1:
raise SystemExit(f"Connection failed: {hello}")
print("Connected, connection uuid:", hello.get("uuid"))

await ws.send(json.dumps({"cmd": "consume_req", "operation_id": "sub-1", "downlink_status": True}))
ping = asyncio.create_task(keepalive(ws))
try:
async for raw in ws:
msg = json.loads(raw)
cmd = msg.get("cmd")
if cmd == "consume_resp":
if msg.get("status") == 1:
print("Subscribed")
elif msg.get("error_code") == 2:
print("The connection is already subscribed: auto-subscription is enabled in the application settings")
else:
raise SystemExit(f"Subscription failed: {msg}")
elif cmd == "realtime_data":
print("Data from", msg["devEui"], "port", msg["data"].get("fport"), ":", msg["data"].get("data"))
elif cmd == "downlink_status":
print("Frame", msg["dataId"], "→", msg["downlink_status_text"])
finally:
ping.cancel()


asyncio.run(main())

Run:

export ONS_APP_ID=77179F01
export ONS_TOKEN=your_token
python3 client.py

Node.js​

client.mjs
// Orion Network Server WebSocket API client: connect, subscribe, device data.
// Node.js 22 or newer — WebSocket is built in, nothing to install.
const URL = process.env.ONS_URL ?? 'wss://kz1.orion-m2m.online/ws/v2/';
const { ONS_APP_ID, ONS_TOKEN } = process.env;
const PING_EVERY = 60_000; // ms; without ping_req the server closes the connection after 300 seconds

const ws = new WebSocket(`${URL}?app_id=${ONS_APP_ID}&token=${ONS_TOKEN}`);
let ping;

ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
switch (msg.cmd) {
case 'connected':
if (msg.status !== 1) throw new Error(`Connection failed: ${event.data}`);
console.log('Connected, connection uuid:', msg.uuid);
ws.send(JSON.stringify({ cmd: 'consume_req', operation_id: 'sub-1', downlink_status: true }));
ping = setInterval(() => ws.send(JSON.stringify({ cmd: 'ping_req' })), PING_EVERY);
break;
case 'consume_resp':
if (msg.status === 1) console.log('Subscribed');
else if (msg.error_code === 2) console.log('The connection is already subscribed: auto-subscription is enabled in the application settings');
else throw new Error(`Subscription failed: ${event.data}`);
break;
case 'realtime_data':
console.log('Data from', msg.devEui, 'port', msg.data.fport, ':', msg.data.data);
break;
case 'downlink_status':
console.log('Frame', msg.dataId, '→', msg.downlink_status_text);
break;
}
};
ws.onclose = () => clearInterval(ping);

Run:

export ONS_APP_ID=77179F01
export ONS_TOKEN=your_token
node client.mjs

What next​