API Client Examples
Agenda
Warning: Always access JSON payload items via full name reference. Never use index in array as the item reference. API is growing and although the name references are kept the same, items order within JSON cannot be guaranteed. Following this rule assures that your system integration will work also with upcoming RTLS Studio versions.
cURL
cURL is a library and command line tool available for all popular programming languages. It has very broad support for REST queries.
You can try it just immediately via our interactive REST documentation available at https://demo.sewio.net/documentation/api-rest .
Example of cURL GET Tags query:
Python examples
REST
REST Client example is built on Requests library for python. Requests allows you to send organic, grass-fed HTTP/1.1 requests, without the need for manual labor. There's no need to manually add query strings to your URLs, or to form-encode your POST data. Keep-alive and HTTP connection pooling are 100% automatic, powered by urllib3, which is embedded within Requests.
Install Requests:
$ pip install requests
import requests print "Sewio REST API example" destUri = "http://192.168.225.2" X_API_KEY = "17254faec6a60f58458308763" FEED_ID = "22" url = destUri + "/sensmapserver/api/feeds/" + FEED_ID headers={'X-ApiKey':0} headers['X-ApiKey']= X_API_KEY output = requests.get(url, headers=headers) print output.text
WebSocket
Install websocket-client module:
$ pip install websocket-client
import websocket print "Sewio WebSocket API example" destUri = "ws://192.168.225.2:8080"; X_API_KEY = "17254faec6a60f58458308763"; FEED_ID = "65" def on_message(ws, message): print message def on_error(ws, error): print error def on_close(ws): print "### closed ###" def on_open(ws): print "### opened ###" msg = "{\"headers\":{\"X-ApiKey\":\""+ X_API_KEY +"\"},\"method\":\"subscribe\", \"resource\":\"/feeds/" + FEED_ID + "\"}"; print "Sending message..." print msg ws.send(msg) ws = websocket.WebSocketApp(destUri, on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever()
Source:
Java examples
REST
REST Client example for java is built on common java libraries.
package net.sewio.rtls.RESTapi; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class example { public static void main(String[] args) { try { String destUri = "http://192.168.225.2"; String X_API_KEY = "17254faec6a60f58458308763"; String FEED_ID = "65"; URL url = new URL(destUri + "/sensmapserver/api/feeds/" + FEED_ID); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("X-ApiKey", X_API_KEY); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
WebSocket
WebSocket Client example for java is built on Jetty websocket library. Jetty is an open-source project providing an HTTP server, HTTP client, and javax.servlet container. It’s important to download jetty and add lib folder to the build path of java project.
package net.sewio.rtls.websocket; import java.net.URI; import java.util.Scanner; import org.eclipse.jetty.websocket.client.WebSocketClient; public class example { @SuppressWarnings("resource") public static void main(String[] args) { String destUri = "ws://192.168.225.2:8080"; String X_API_KEY = "17254faec6a60f58458308763"; String FEED_ID = "65"; double posX = 0.0; double posY = 0.0; WebSocketClient client = new WebSocketClient(); SimpleRtlsWebSocket socket = new SimpleRtlsWebSocket(); try { client.start(); URI rtlsUri = new URI(destUri); client.connect(socket,rtlsUri); System.out.printf("Connecting to : %s%n",rtlsUri); while (!socket.isConnected()) { Thread.sleep(1000); } socket.subscribe(X_API_KEY, FEED_ID); while (true) { String method = new Scanner(System.in).next(); if (method.contains("close")) { socket.unsubscribe(X_API_KEY, FEED_ID); break; } else if (method.contains("put")) { socket.put(X_API_KEY, FEED_ID, posX, posY); } else if (method.contains("unsubscribe")) { socket.unsubscribe(X_API_KEY, FEED_ID); } else if (method.contains("subscribe")) { socket.subscribe(X_API_KEY, FEED_ID); } } } catch (Throwable t) { t.printStackTrace(); } finally { try { client.stop(); } catch (Exception e) { e.printStackTrace(); } } } }
This example open connection to WebSocket, then wait for one second and send message with method Subscribe, after that user can write to console other methods (put, subscribe, unsubscribe) or can be close by writing to console “close”. In file SimpleRtlsWebSocket.java is class which define methods and functions for WebSocket example.
package net.sewio.rtls.websocket; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; import org.eclipse.jetty.websocket.api.annotations.WebSocket; /** * Basic sewiortls WebSocket Client */ @WebSocket(maxTextMessageSize = 64 * 1024) public class SimpleRtlsWebSocket { private Session session; public SimpleRtlsWebSocket(){ } @OnWebSocketClose public void onClose(int statusCode, String reason) { System.out.printf("Connection closed: %d - %s%n",statusCode,reason); this.session = null; } @OnWebSocketConnect public void onConnect(Session session) { System.out.printf("Got connect: %s%n",session); this.session = session; } public void sendMessage(String msg) { try { Future fut; fut = session.getRemote().sendStringByFuture(msg); fut.get(2,TimeUnit.SECONDS); } catch (Throwable t) { t.printStackTrace(); } } public void subscribe(String xApiKey, String FEED_ID) { String method = "subscribe"; String msg = "{\"headers\":{\"X-ApiKey\":\""+ xApiKey +"\"},\"method\":\"" + method + "\", \"resource\":\"/feeds/" + FEED_ID + "\"}"; System.out.printf("Sending msg: %s%n",msg); sendMessage(msg); } public void unsubscribe(String xApiKey, String FEED_ID) { String method = "unsubscribe"; String msg = "{\"headers\":{\"X-ApiKey\":\""+ xApiKey +"\"},\"method\":\"" + method + "\", \"resource\":\"/feeds/" + FEED_ID + "\"}"; System.out.printf("Sending msg: %s%n",msg); sendMessage(msg); } public void put(String xApiKey, String FEED_ID, double posX, double posY) { String method = "put"; String msg = "{\"headers\":{\"X-ApiKey\":\"" + xApiKey +"\"},\"method\":\"" + method + "\",options:{savetoDB:false},\"body\":{\"id\":" + FEED_ID + ",\"datastreams\":[{\"id\":\"posX\",\"current_value\":" + posX + "},{\"id\":\"posY\",\"current_value\":" + posY + "}]}, \"resource\":\"/feeds/" + FEED_ID + "\"}"; System.out.printf("Sending msg: %s%n",msg); sendMessage(msg); } public boolean isConnected() { if (session != null){ return session.isOpen(); } else return false; } @OnWebSocketMessage public void onMessage(String msg) { System.out.printf("Got msg: %s%n",msg); } }
Source:
Node.js Examples
WebSocket
Requirements:
example for Node.js version >= 8.0.0
$ npm install --save ws fs
- fs - accessing the file system;
- ws - creating websocket connection;
(libs already included in the source zip file)
// GLOBAL VARIABLES const WEBSOCKET_HOST = "ws://192.168.225.2:8080"; const PATH_TO_STORE_DATA = "./output.txt"; const API_KEY = "17254faec6a60f58458308763"; // LIBS const ws = require("ws"); // websockets const fs = require("fs"); // file system // LOGIC const socket = new ws(WEBSOCKET_HOST); socket.on("open", () => { console.log("Connection Established!"); sendSubscribeMessage(); }); socket.on("message", message => { storeToFile(message); }); /** * Sends subscription to all feeds. * (will get the data from feeds that will be created in the future as well) */ function sendSubscribeMessage() { socket.send( '{"headers":{"X-ApiKey":"' + API_KEY + '"},"method":"subscribe", "resource":"/feeds/"}' ); } /** * Appends incomming messages to file. */ function storeToFile(message) { fs.appendFile(PATH_TO_STORE_DATA, message, error => { if (error) { console.error("Could not store data in file."); } }); }
Source: