Quick start
Some example scripts in Node.JS, C#, VB.Net, and Python are included with the installed files. For Python, we recommend using the newer asyncio example rather than the older synchronous examples.
-
Windows: %ProgramFiles%\Cambrionix\CambrionixAPI/examples
-
Linux: /usr/local/share/cambrionix/apiservice/examples.
-
macOS: /Library/Cambrionix/ApiService/examples.
For each code type in the examples folder you will need to install the necessary programs.
-
Python 3.4 for the python examples, as well as Python 3.4, you will need the jsonrpc-websocket module. Reference information on using Python can be found here.
-
Node.JS for the nodejs example, will also require either NPM or Yarn. More information can be found here.
-
Visual Studio for the C# or VB.Net examples
To install the Python async api package go to examples/python/asyncio and run
pip install .
Python Example
The jsonrpc-websocket module automatically converts python script to a JSON-RPC request. The below example is how the websocket will convert a simple script.
Python.
cbrxapi.cbrx_connection_open("DJ000102")
JSON-RPC Translation.
{
"id": 0,
"jsonrpc": "2.0",
"method": "cbrx_connection_open",
"params": [
"DJ000102"
]
}
Replies are automatically converted back from JSON into a Python dictionary, or list or value as appropriate.
Here is an example of using the API, the code is written in Python 3.6: The example code doesn’t check for errors so the Python script will simply stop on an error. Robust code error handling should be incorporated in your own software.
# Import the cbrxapi library.
import sys
from cbrxapi import cbrxapi
print("Querying API Version...")
try:
result = cbrxapi.cbrx_apiversion()
except Exception as e:
print(f"Could not communicate with API : {e}")
result = None
if result:
print(f"API Version {result[0]}.{result[1]}")
# Call cbrx_discover with "local" to find any locally attached Cambrionix units.
# This will return a list of local Cambrionix units.
print("Discovering local devices..")
result = cbrxapi.cbrx_discover("local")
if not result or len(result) == 0:
print("No Cambrionix unit found.")
sys.exit(0)
print(f"Discovered {len(result)} units")
for unit_id in result:
serial_port = cbrxapi.cbrx_discover_id_to_os_reference(unit_id)
try:
# Open a connection to the Cambrionix unit, which will return a handle for
# the connection.
handle = cbrxapi.cbrx_connection_open(unit_id)
except Exception as e:
print(f"Could not open connection to {unit_id} : {e}")
handle = None
if handle:
# Using the handle, get the "Hardware" and "nrOfPorts" properties
hardware = cbrxapi.cbrx_connection_get(handle, "Hardware")
n_ports = cbrxapi.cbrx_connection_get(handle, "nrOfPorts")
# Done using the Cambrionix unit, close the handle.
cbrxapi.cbrx_connection_close(handle)
# Finally, print out the information retrieved from the Cambrionix unit.
print(f"* {hardware} on {serial_port} has {n_ports} ports")
TypeScript Example
This is a simple example of using Typescript to use the API to obtain information on the hubs and devices. Further information on TypeScript can be found here.
import React from 'react';
import Websocket from 'react-websocket';
class MyApiInterface extends React.Component {
lastId = 0;
render() {
return (
<Websocket ref={r => this.websocket = r} reconnect
url="ws://localhost:43424" protocol="jsonrpc"
onMessage={this.onDataReceived.bind(this)}
onOpen={this.onApiConnection.bind(this)}
onClose={this.onApiDisconnection.bind(this)} />
);
}
requests = {};
onDataReceived(json) {
const data = JSON.parse(json);
const id = data.id;
if (id) {
const request = this.requests[id];
if (request && request.callback) {
request.callback(data);
}
delete this.requests[id];
}
else
{
//Could get a notification here if you enable them on active connection
//Notifications have no id and can arrive at any time
}
}
makeRequest(method, params, callback) {
var packet = {
jsonrpc: "2.0",
id: ++this.lastId,
method: method,
params: params,
};
this.requests[packet.id] = {packet: packet, callback: callback};
this.websocket.sendMessage(JSON.stringify(packet));
}
onApiConnection() {
console.log("Connected");
this.makeRequest("cbrx_discover", ["local"], console.log);
}
onApiDisconnection() {
console.log("Disconnected");
this.requests = {}
}
}
HTTP GET Example
Connections can be made directly to an http prefixed URI, in which case the json is extracted from either the address itself, or the body content of the GET request. You can try this example in your browser or from the command line, using curl:
curl -get http://localhost:43424/?{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"cbrx_discover\",\"params\":[\"all\"]}
Socket connections can be simple binary data, http GET requests or Web-sockets (such as from Node.js). For example, pasting the following into the address bar of your browser should allow you to see quick results:
http://localhost:43424/?{"jsonrpc":"2.0","id":1,"method":"cbrx_discover","params":["all"]}
Please be aware that on some Terminal/Command Prompt windows, you may find that you need to encode the URL to prevent error's from occuring.
Once encoded, the above URL should look like:
http://localhost:43424/%7B%22jsonrpc%22:%222.0%22,%22id%22:0,%22method%22:%22cbrx_apidetails%22%7D
Error Handling
A JSON-RPC error will return an error member containing the following members:
-
code (mandatory) – an integer indicating either a pre-defined JSON-RPC error code in the range -32768 to -32000 or a CBRXAPI error code as documented in the section CBRXAPI specific errors section.
-
message (optional) – a message string explaining the error code
-
data (optional) – extra information about the error like debug messages or handles.
The Python JSON-RPC used causes an exception for an error response with the following mapping:
-
member code is returned in e.error_code
-
member message is returned in e.error_message
-
member data is returned in e.error_data.
You can catch an error response with:
try:
handle = cbrxapi.cbrx_connection_open(id)
except jsonrpc.RPCFault as e:
gotException = True
errorCode = e.error_code
errorMessage = e.error_message
errorData = e.error_data
Example of how to create an error and the response it will give:
{
"jsonrpc": "2.0",
"id": 0,
"method": "cbrx_connection_open",
"params": [
"0"
]
}
Response:
{
"jsonrpc": "2.0",
"id": 0,
"error": {
"code": -10001,
"message": "ID not found"
}
}