Rotoclear C Pro
API – Documentation

Getting started

This API was developed to enable customized control in the diverse machine control environments. The API provides programmatic access to read state and control the camera system.

Two web-based communication protocols are available. On the one hand, it is possible to set up a stateless connection via the standard HTTP Get or Post request and to fetch or set the desired data. On the other hand, an event-driven system can be developed via a websocket connection. In this way, the software programmed by the customer could react to changing information, which are synchronized in real time.

  • Http API
  • WebSocket API
  • Camera stream
  • State Description
  • AI module
  • GPIO module

Http API

The http API is a RESTful API. The control unit of the Rotoclear C Pro represents the server in the local network environment and the program is the client. Communication happens stateless between server and client. This means that the server does not know anything about the last requested data and even if the data is still up to date it will be sent again on request.

This API is ideal for writing a simple and small control program. It is also easy to test. The Get Requests URL can be entered directly in the browser in the URL input field, or it can be tested with postman or curl. All that is needed is a http Client and some understanding of the http protocol, url queries, the http headers and JSON format.

Connection

Http API can be accessed via both web servers on the control unit. In principle, the origin of the connection url is the same under which we can also call the web client in the browser. The path '/api' is appended to this url origin (see 'Connection URL example'). Of course, the respective web server must be switched on in the connection settings (see http and https connection in menu). These connection settings also contain the port we need for our http client connection. Please note: For security reasons, the https connection is always recommended.

The API responds to two HTTP methods. The HTTP GET method can be used to set request details in the URL query. For practical reasons, it is also allowed to set parameters in the API (which will be explained below). With the HTTP POST method, more complex request structures can be mapped with a JSON formatted body.

Connection URL examples: 
    http://rotoclear-cam.local:80/api
    https://rotoclear-cam.local:443/api
    https://192.168.0.123:3000/api

Response:
    401 Unauthorized

Authentication and Authorization

Furthermore, we need also the API token from the settings. This is configurable after the activation of the API module. The system has an internal permissions system, which can assign different rights for different users. With the activation of the API module, an 'API-User' user is created in addition to the 'admin' user. The token set in the settings reflects the password of the 'API-User'.

Authentication via parameters in the url query:

The user and the password can be set as one parameter in the URL query. In this case, the keywords 'token' and 'password' are mapped to the same field of the user as password. If the user is not passed, the 'API-User' is assumed as default. (example: 'Authentication in URL Query'). This authentification variant has advantages and disadvantages. One disadvantage is that the token is readable in its raw form in the url query. One advantage is that a request can be made simply as URL text, as for example with the GET request by entering the url in browser.

If an http client connects only with this information, then all information authorized for the user is sent as response, since no further information and selection is provided.

Authentication in URL Query: 
    http://rotoclear-cam.local:80/api?user=API-User&token=***
    https://rotoclear-cam.local:443/api?token=***
    https://192.168.0.123:3000/api?password=***

Curl example:
    curl -X GET -G https://rotoclear-cam.local:443/api -d token=***

Response:
    200 Success. 
    With JsonObject as description of the state in body of the response.

Simplified and formatted body example of the response body: 
    {
      "oct0":"69.7°C",
      "oct1":"80.0°C",
      "light0":false,
      "light1":false,
      "hasInternet":true,
      "macAddr":"00:15:5D:7E:D9:46",
      "hostname":"rotoclear",
      "netInfo":[
        {
          "name":"eth0",
          "description":"eth0",
          "macAddress":"00:15:5D:7E:D9:46",
          "gateway":"",
          "isServer":false,
          "dhcp":true,
          "dhcpServers":[],
          "connections":[{
              "address":"172.28.32.226",
              "netmask":"255.255.240.0",
              "broadcast":"172.28.47.255"
          }],
          "dhcpSelected":true,
          "staticIp":"192.168.214.221",
          "staticMask":"255.255.255.0",
          "staticGateway":"192.168.214.1",
          "staticDns":"8.8.8.8",
          "staticUseGateway":false,
          "staticUseDns":false
        }
      ],
      "pan0":{"x":50.31323414252154,"y":49.89594172736733},
      "pan1":{"x":50,"y":50},
      "pip":0,
      "psi0":"1712mbar",
      "psi1":"1008mbar",
      "psiSetpoint":"1150mbar",
      "changeVideoName":"",
      "changeImageName":"",
      "changePostName":"",
      "record":"stop",
      "recordTime":0,
      "rtspPort":1025,
      ...
    }

Authentication via Basic Authentication:

The second authentication variant is Basic Authentication. For this purpose, according to the RFC7617 standard, the 'Authorization' key is specified in the http header. The value of authorization key composes the text "Basic " and the base64 encoded 'username:password'. Further information should be taken from the documentation of the respective http client and used programming language.

Basic Authentication - Curl example:
    curl -X GET -G https://rotoclear-cam.local:443/api \
        -u "API-User:token"

Response:
    200 Success. 
    With JsonObject as description of the state in body of the response.

Http Get method

Now that the connection and the authentication to the API was successful, we can go into some details about the requests. In the request with the http Get method, additional parameters can be added in the URL query. To get only the state of the system, the keyword 'get' can be used to list only the desired system state variables. The description of the state variables can be found at the end of this documentation (see: 'State Description'). All variables allowed to the user can be queried in this way. Unknown or unauthorized state variables are ignored by the API. This means that these values are not listed in the response.

Query selected state variables - URL example:
    https://rotoclear-cam.local:443/api?token=***&get=[light0,record,recordTime,pan0]

Query selected state variables - Curl example:
    curl -X GET -G https://rotoclear-cam.local:443/api \
        -d token=*** \
        -d get=[light0,record,recordTime,pan0]
    
Response:
    {
      "light0": true,
      "record": "stop",
      "recordTime": 0,
      "pan0": {
        "x": 50.26041666666666,
        "y": 50.0
      }
    }

The Get method can also be used to set values in the system state. Please note that complex and nested structure variables cannot be easily mapped in a query, so they will not work with a GET request. To set a variable, simply match its key to the value in the query. Since in the query the variables are written only in the form of text, these variables are converted internally into the respective data types. That means "true" or "false" becomes a JSON boolean, written-out numbers are converted into the respective JSON numbers as Integer or Float number and saturated. In addition, the values are validated and caught in a valid and defined range. After setting the variable, the updated state variables are listed in the response of the request.

Set state variables - URL example:
    https://rotoclear-cam.local:443/api?token=***&light0=true&record=start

Set state variables - Curl example:
    curl -X GET -G https://rotoclear-cam.local:443/api \
        -d token=*** \
        -d light0=true \
        -d record=start

Response:
    {
      "light0": true,
      "record": "stop",
    }
The system could respond with a "record": "stop" if, for example,
no storage medium was selected for recording.

Http Post method

There are also some slightly more complex data types in the system state. These include for example network, time, stream pan settings, etc. If you want to set these more complex data types, you can use the http post method. To do this, the settings in JSON format are passed to the request in the body.

Set pan for first camera head - Post Request with a JSON body:
    curl -X POST https://rotoclear-cam.local:443/api \
      -u "API-User:***" \
      -H "Content-Type: application/json" \
      -d '{"pan0": {"x": -10.5, "y": -10}, "zoom0": 20000}'

Response:
      {
        "pan0": {
          "x": 39.5,
          "y": 40.0
        },
        "zoom0": 20000
      }
While the control of the camera heads, i.e. the pan and the 
zoom are calculated relative to the current value, the return
value of the API is always the absolute value currently set.

For simplicity, values can also be queried via the post method. To do this, the get key must be matched with an array of keys in string form.

Furthermore, it should be mentioned that with one request state getter and setter can be sent at the same time. Usually these are executed in the written order. The same applies to the get requests, where the order of the query parameters is considered.

Query state - Post Request with a JSON body:
    curl -X POST https://rotoclear-cam.local:443/api \
      -u "API-User:***" \
      -H "Content-Type: application/json" \
      -d '{"get": ["light0","record","recordTime","pan0"]}'

Response:
    {
      "light0": true,
      "record": "stop",
      "recordTime": 0,
      "pan0": {
        "x": 50.26041666666666,
        "y": 50.0
      }
    }

Tag export (CSV)

Returns the tags as a CSV file (or TSV with format=tsv) for download. Use POST for large selections, as the length of the request line is limited to 8 KB. Titles and categories of AI tags are exported as they are stored, i.e. as translation keys (see AI module).

Export all tags of a time range:
    http://rotoclear-cam.local:80/export-tags-csv?timestampStartMs=<ms>×tampEndMs=<ms>&user=API-User&token=***
Export selected tags (optionally as TSV):
    http://rotoclear-cam.local:80/export-tags-csv?ids=1,2,3&format=tsv&user=API-User&token=***
Large selections:
    POST http://rotoclear-cam.local:80/export-tags-csv?user=API-User&token=***
    Body: {"ids": [1, 2, 3, ...]}

WebSocket API

The websocket API is suitable for programming an event-based system. The API is based, as the name says, on the extended http API protocol called websocket. With a websocket a permanent connection can be established. To understand the communication over the websocket with the API we must consider the following points.

1. communication data and format:
The API communicates like the http API internally with JSON formatted data (there are some internal exceptions, but these should never occur in normal usage). This means that incoming messages to the websocket client will 'always' be JSON objects. In these objects one or more state variables of the system can be listed. This also means that the websocket client must also send its control messages in JSON format.

2. subscription:
When a connection is established with the API and authorized, all variables of the system authorized to the user are automatically subscribed to. This means that first, all these variables are packaged in JSON and sent to the client as an initial state, and then second, whenever the state changes, the corresponding variables are sent again to the client in real time. This way a system can be built which is synchronized in real time with the control unit.

3. control:
It is also possible for the websocket client to participate in the state of the system. As with the http Post request, the websocket can send JSON formatted messages. These are evaluated and set in real time. The data type as well as the write permission for the variables must be considered here. See the state table at the end of the document.

Connection

The websocket connections reside in the same endpoints as the http API connections. Again, both web servers (http and https web servers) are accessible for this connection. We only must note that "ws" must be written as protocol instead of "http".

For more information about websocket connections, please refer to documentation of the websocket and the respective development programming language of your client system.

Connection URL examples: 
    ws://rotoclear-cam.local:80/api
    wss://rotoclear-cam.local:443/api
    wss://192.168.0.123:3000/api

In Javascript:

const socket = new WebSocket("wss://rotoclear-cam.local:443/api");

Response:
    401 Unauthorized

Authentication and Authorization

For authentication and authorization of the connection, the token and the user must be set in the url query. See also the authentication of the http API in the paragraph: Authentication in URL Query.

Connection to the WebSocket API in Javascript:

const token = "***"; // query conform encoding should be considered here
const socket = new WebSocket("wss://rotoclear-cam.local:443/api?token=" + token);

// add callbacks
socket.onerror = function(error){ console.error(error); };
socket.onmessage = function(evt) { 
  if (typeof evt.data === "string") {  
    var jsonMsg = JSON.parse(evt.data);
    console.debug(jsonMsg);
    // The first message will represent the entire allowed state. 
    // The following ones will represent the updates.
  }

Example

Connection to the WebSocket API in Nodejs:

var WebSocket = require('websocket').w3cwebsocket;

const token = "***"; // query conform encoding should be considered here
const socket = new WebSocket("wss://rotoclear-cam.local:443/api?token=" + token);

function sendToAPI(message) {
  // stringify json message
  connection.send(JSON.stringify(message));  
}

connection.onopen = function() {
  // now we can send messages to api
  sendToAPI({ "light0": true });
};

connection.onerror = function(error) { console.error(error); };

connection.onmessage = function(evt) { 
  if (typeof evt.data === "string") {  
    var stateMsg = JSON.parse(evt.data);
    console.debug(stateMsg);

    // Use data from api to control your system
    // .... 
  } 
};

Camera stream

To access the camera stream, the Rotoclear C Pro control unit provides a rtsp and http stream. The rtsp stream can be accessed via the RTSP protocol. The connection URL could look like this: 'rtsp://:554/stream.h264' or 'rtsp://:554/stream.mjpg'.

The camera stream can also be processed via the http GET requests. Please note that authentication with the corresponding credentials (username and password) is required in the request to access the camera stream. For authentication and authorization see http API authentication in paragraph: Authentication in URL query.
As long as no password is set on the control unit (user authentication switched off, state userAuthentication), all streams are accessible without credentials. There is no separate switch for this any more; the former key streamIsOpen has been removed.

1. Retrieving a JPEG image:
A JPEG image can be obtained by making an http GET request. To do this, the path '/camera.jpeg' and the authentication must be added to the connection.

Request Image:
    http://rotoclear-cam.local:80/camera.jpeg?user=API-User&token=***

2. Streaming MJPEG:
For streaming MJPEG, the content type 'multipart/x-mixed-replace' is used. The server sends a continuous series of JPEG images in response to the http request. The content type of each individual image is specified as 'Content-Type: image/jpeg'.
The server will respond with a continuous series of JPEG images, transmitted in the body of the http response. Each image has the content type 'image/jpeg' and is sent in a separate http message. The client can process the MJPEG stream by extracting and displaying each individual JPEG image.

Request MJPEG: 
    http://rotoclear-cam.local:80/camera.mjpeg?user=API-User&token=***

3. Streaming h264:
For streaming raw h264, the content type 'multipart/x-mixed-replace' is used. The server sends a continuous series of h264 frames in response to the http request. The content type of each individual frame is specified as 'Content-Type: video/h264'. Similar to the MJPEG stream, the server will respond with a continuous series of h264 frames, transmitted in the body of the http response. Each frame has the content type 'video/h264' and is sent in a separate http message. The client can process the h264 stream by extracting and decoding each individual frame.

Request h264 stream: 
    http://rotoclear-cam.local:80/camera.h264?user=API-User&token=***

4. Streaming raw nv12:
For streaming raw nv12, the content type 'multipart/x-mixed-replace' is used. The server sends a continuous series of nv12 frames in response to the http request. The content type of each individual frame is specified as 'Content-Type: video/nv12'.
Similar to the MJPEG and h264 streams, the server will respond with a continuous series of nv12 frames, transmitted in the body of the http response. Each frame has the content type 'video/nv12' and is sent in a separate http message. The client can process the nv12 stream by extracting and decoding each individual frame. Every frame has the size of width * height * 1.5 bytes, where width and height are the dimensions of the video frame (default 1920x1080).

Request nv12 stream: 
    http://rotoclear-cam.local:80/camera.nv12?user=API-User&token=***

WebRTC stream (WHEP)

The live stream is also available via WebRTC with very low latency. The session is negotiated with plain http requests following WHEP (WebRTC-HTTP Egress Protocol, draft-ietf-wish-whep): the client sends its SDP offer, the server answers with its SDP answer. No websocket is involved. The video codec is H.264; with the streaming format HEVC WebRTC is not available (the server answers 415). If the offer contains an audio section and the audio module is active, the microphone is sent as Opus in the same session.

The answer already contains all ICE candidates (non-trickle); PATCH for trickle ICE is answered with 501. Please end a session with DELETE when it is no longer needed - the number of simultaneous sessions is limited.

Status codes:
201 - session created
400 - invalid SDP offer
409 - the stream is still starting, retry after the time given in Retry-After (1 s)
415 - wrong Content-Type, or the offer offers no supported codec (e.g. no H.264, or streaming format HEVC)
503 - limit of simultaneous sessions reached or stream busy (e.g. during a special recording), retry after Retry-After (5 or 15 s)
404 - DELETE of an unknown session

Start session:
    POST https://rotoclear-cam.local:443/camera.whep?user=API-User&token=***
    Content-Type: application/sdp
    Body: SDP offer (recvonly video, optional recvonly audio)

Response:
    201 Created
    Content-Type: application/sdp
    Location: /camera.whep/<session-id>
    Body: SDP answer (complete, including all ICE candidates)

End session:
    DELETE https://rotoclear-cam.local:443/camera.whep/<session-id>?user=API-User&token=***

Stream via Websocket

Alternative to http GET requests, the client could acces the stream also via a Websocket and receive the stream data in blob Packets.

Request MJPEG via Websocket: 
    ws://rotoclear-cam.local:80/camera.mjpeg?user=API-User&token=***
Request h264 via Websocket: 
    ws://rotoclear-cam.local:80/camera.h264?user=API-User&token=***
Request nv12 via Websocket: 
    ws://rotoclear-cam.local:80/camera.nv12?user=API-User&token=***

State Description

The following table describes the state variables. Please note that some settings are dependent on each other. Accordingly, the system will validate the inputs and trigger notifications under certain circumstances.

API Key Value Datatype Permissions Description
cam0Exists Boolean r existence of the first camera head stream
cam1Exists Boolean r existence of the second camera head stream
head0Exists Boolean r existence of the first camera head
head1Exists Boolean r existence of the second camera head
head0IsSlowMoCompatible Boolean r first camera head is compatible with slow motion recording
head1IsSlowMoCompatible Boolean r second camera head is compatible with slow motion recording
cameraSwitch Boolean rw selection of the current streaming and recording camera head.
false -> first camera is selected
true -> second camera is selected
lineRateA String r data transmission rate of the first camera head
lineRateB String r data transmission rate of the second camera head
setLineRateA String rw set data transmission rate of the first camera.
possible values: "2Gbps", "1Gbps"
setLineRateB String rw set data transmission rate of the second camera.
possible values: "2Gbps", "1Gbps"
ver0 String r hardware and software version of the first camera head
ver1 String r hardware and software version of the second camera head
autoRotate0 Boolean rw automatic alignment of the first camera head
false -> disable automatic
true -> enable automatic
autoRotate1 Boolean rw automatic alignment of the second camera head
false -> disable automatic
true -> enable automatic
dictRotation0 Boolean rw first camera head disk rotation
dictRotation1 Boolean rw second camera head disk rotation
rpm0 Integer r read rotation speed setpoint of the first camera head
rpm1 Integer r read rotation speed setpoint of the second camera head
RPM0 Integer r measured rotation speed of the first camera head
RPM1 Integer r measured rotation speed of the second camera head
light0 Integer rw first camera head light
false -> disabled
true -> enabled
light1 Integer rw second camera head light
false -> disabled
true -> enabled
light0Dim Boolean r first camera head can set light brightness
light1Dim Boolean r second camera head can set light brightness
light0Brightness Integer [0,100] rw first camera head light brightness
light1Brightness Integer [0,100] rw second camera head light brightness
downstat String r state of the 'update process' working in the background
fpgaTemp String r temperature of the FPGA in the control unit
exposure Boolean rw automatically aligned exposure of the picture
false -> disabled
true -> enabled
whiteBalance Boolean rw automatically white balance of the picture
false -> disabled
true -> enabled
noiseSuppression Boolean rw automatically noise suppression
false -> disabled
true -> enabled
redGain Integer [-128,127] rw red gain value
works only if whiteBalance is disabled
blueGain Integer [-128,127] rw blue gain value
works only if whiteBalance is disabled
brightness Integer [-7,7] rw brightness of the picture
works only if exposure is disabled
expo Number [0.01,1000.0] rw exposure time
works only if exposure is disabled
gain Integer [0,42] rw gain
works only if exposure is disabled
sharpness Integer [1,15] rw sharpness of the picture
saturation Number [-7,7] rw color saturation of the picture
contrast Number [1,2.5] rw contrast of the picture
hdmiConnected Boolean r indicates whether a monitor is connected to the control unit
hdmiName String r name of the monitor
cfg30 String r rate of the first optical sensor of the first camera head (dependent on the quality of the connection)
"0" ≙ no optical sensor found
"30" ≙ optical sensor with 30fps found
"60" ≙ optical sensor with 60fps found
cfg40 String r rate of the second optical sensor of the first camera head (dependent on the quality of the connection)
"0" ≙ no optical sensor found
"30" ≙ optical sensor with 30fps found
"60" ≙ optical sensor with 60fps found
cfg31 String r rate of the first optical sensor of the second camera head (dependent on the quality of the connection)
"0" ≙ no optical sensor found
"30" ≙ optical sensor with 30fps found
"60" ≙ optical sensor with 60fps found
cfg41 String r rate of the second optical sensor of the second camera head (dependent on the quality of the connection)
"0" ≙ no optical sensor found
"30" ≙ optical sensor with 30fps found
"60" ≙ optical sensor with 60fps found
oct0 String r temperature of the first camera head
oct1 String r temperature of the second camera head
cam0Sensor0Exists Boolean r existence of the first optical sensor of the first camera head
cam0Sensor1Exists Boolean r existence of the second optical sensor of the first camera head
cam1Sensor0Exists Boolean r existence of the first optical sensor of the second camera head
cam1Sensor1Exists Boolean r existence of the second optical sensor of the second camera head
cam0SelectedSensor Integer [0,1] rw selected optical sensor of the first camera head
Be careful, if your head does not have 2 optical sensors, it will mirror your image!
cam1SelectedSensor Integer [0,1] rw selected optical sensor of the second camera head
Be careful, if your head does not have 2 optical sensors, it will mirror your image!
focusCam0Sensor0Exists Boolean r existence of the first focus sensor of the first camera head
focusCam0Sensor1Exists Boolean r existence of the second focus sensor of the first camera head
focusCam1Sensor0Exists Boolean r existence of the first focus sensor of the second camera head
focusCam1Sensor1Exists Boolean r existence of the second focus sensor of the second camera head
focusCam0Sensor0 Integer [0,1023] r focus value of the first focus sensor of the first camera head
focusCam0Sensor1 Integer [0,1023] r focus value of the second focus sensor of the first camera head
focusCam1Sensor0 Integer [0,1023] r focus value of the first focus sensor of the second camera head
focusCam1Sensor1 Integer [0,1023] r focus value of the second focus sensor of the second camera head
tapToFocus {'x': Number [0.0,1.0], 'y': Number} rw focus on a specific relative point in the current camera head image
language String rw current selected language in menu
Please note that only the selection of languages from the menu is valid.
licenseModules Json Array r list of modules in system
hasInternet Boolean r control unit has internet access
macAddr String r mac address of the first network device in hardware
hostname String rw hostname of the control unit in netork
workgroup String rw workgroup of the control unit in network
netInfo Json Array r list network devices and settings
zoomSettings Json Object r zoom settings of the current camera and sensor configuration
zoomState Json Object rw set zoom state of the current camera and sensor configuration
zoomState.left and zoomState.top are relative values between 0.0 and 1.0
zoomState.zoom is the zoom factor in the range of 1 to 4
pip Number [0,5] rw picture in picture or side by side mode selection
0 ≙ only current camera
1 ≙ pip is bot left
2 ≙ top left
3 ≙ top right
4 ≙ bottom right
5 ≙ side by side
psi0 String r sealing air of first camera head in bar
psi1 String r sealing air of second camera head in bar
psiControlBox String r sealing air of control unit in bar
psiSetpoint String r default sealing air set point in bar
changePostName String rw postfix of the recorded file
changeBackupPostName String rw postfix of the backup recorded file
changeVideoName String rw base name for video recordings.
max. 16 characters, automatically sanitized (forbidden characters are removed, spaces are replaced). The name "Backup" is reserved and will be rejected.
changeImageName String rw base name for snapshot images.
max. 16 characters, same sanitizing rules as 'changeVideoName'. The name "Backup" is reserved and will be rejected.
recordingFilename String r filename of the current or last normal recording
fotoFilename String r filename of the last taken snapshot
backupFilename String r filename of the current Visual Backup recording
record String rw state of recording
options: "start", "timelapse", "slowmotion" or "stop"
please note: that the recording requires some conditions such as the presence of the storage medium and sufficient storage space
takePicture Boolean w trigger snapshot
recordTime Number r traced time of current video recording
backupActive Boolean rw enable or disable the Visual Backup recording.
The Visual Backup continuously records to a separate backup storage (see 'backupStorage') in parallel to the normal recording. When the configured capacity (see 'backupNumberOfSavedHours') is reached, the oldest data is overwritten automatically.
false -> disabled
true -> enabled

please note: a backup storage must be configured. Under certain conditions the system can reset this to false automatically (e.g. when no backup capacity is left).
backupNumberOfSavedHours Integer rw maximum duration (in hours) of Visual Backup footage to keep on the backup storage. Once this limit is reached the oldest footage is overwritten.
minimum 1 hour, default 12
backupNumberOfSavedHoursSet Integer r maximum backup duration (in hours) actually applied by the system. May be lower than 'backupNumberOfSavedHours' if the backup storage cannot hold the requested duration.
backupUseCompleteSpace Boolean rw use the complete free space of the backup storage for the Visual Backup instead of limiting it to 'backupNumberOfSavedHours'.
false -> limit to the configured hours (default)
true -> use all available space
backupRemainingCapacitySeconds Integer r remaining Visual Backup recording capacity in seconds
backupAudioActive Boolean rw record the audio track into the Visual Backup recording (requires the audio module).
false -> disabled
true -> enabled (default)
audio Json Object rw description of the connected microphone (requires the audio module); empty object without microphone or license.
layout: {name: String, device: String, path: String, settings: [Objects], selected: Number}
write the index of an entry in settings (Number) to select the sample rate / channel setting
availableAudioDevices Json Array r list of detected audio input devices
selectedAudioDevice String rw identifier of the audio input device to use (see availableAudioDevices)
selectedAudioQuality Number r index of the selected entry in audio.settings (-1 = device default); set it via audio
prerollSettings Json Object rw pre-recording: the last seconds before a recording is started are included in the recording.
layout: {enabled: Boolean, durationSec: Number [15,30]}
default: {enabled: true, durationSec: 15}
prerollStatus Json Object r state of the pre-recording buffer.
layout: {enabled: Boolean, active: Boolean, busy: Boolean, configuredSec: Number, bufferedSec: Number, bufferedBytes: Number, capacityBytes: Number, frames: Number}
rtspPort Number rw port of rtsp server
rtspOn Boolean rw rtsp server running
rtspStatus Json Object r status of rtsp server
rtspUseTLS Boolean rw encrypt the rtsp stream with TLS (rtsps://).
false -> rtsp:// (default)
true -> rtsps://, uses the https certificate
rtspUseAuth Boolean rw require credentials for the rtsp stream.
true -> credentials required (default)
false -> every client is accepted without credentials
only effective while user authentication is switched on (a password is set, state userAuthentication); without a password the stream is open anyway
replaces the former key rtspAuthDisabled (inverted meaning), which is converted once on update
diskStorages Json Object r list of detected usb storages
netStorages Json Object r list of setted network storages
recordingStorage Json Object r selected manual recording storage description
recordingStorage String w select manual recording storage with uuid (select one id in diskStorages or netStorages)
backupStorage Json Object r selected backup recording storage description
backupStorage String w select backup recording storage with uuid (select one id in diskStorages or netStorages)
alignmentStream0 String rw rotate stream of first camera head
"0" ≙ 0°
"1" ≙ 180°
alignmentStream1 String rw rotate stream of second camera head
"0" ≙ 0°
"1" ≙ 180°
resolution String rw recording resolution
"4K": 3840x2160
"FullHD": 1920x1080
"HD": 1280x720
fps Integer rw recording and stream frames per second
options: 1,5,10,15,30,60
recordingFormat String rw video codec used for recording.
"h264" (default)
"hevc" (alias "h265")
"mjpg" (only used for slow motion)
recordingQuality Integer [1,100] rw quality of the recording encoder (default 75)
recordingMaxBitrate Integer rw maximum recording bitrate in bits per second (default 20000000 ≙ 20 Mbit/s)
recordingAudioActive Boolean rw record the audio track into the normal recording (requires the audio module).
false -> disabled
true -> enabled (default)
uvc0 Json Object rw description of the first USB camera (UVC module); empty object without device.
stream: /uvc0.mjpg
uvc1 Json Object rw description of the second USB camera (UVC module); empty object without device.
stream: /uvc1.mjpg
uvc2 Json Object rw description of the third USB camera (UVC module); empty object without device.
stream: /uvc2.mjpg
availableUvcDevices Json Array r list of detected USB cameras
preferredUvc0Device String rw device that should be used as first USB camera (see availableUvcDevices)
preferredUvc1Device String rw device that should be used as second USB camera (see availableUvcDevices)
preferredUvc2Device String rw device that should be used as third USB camera (see availableUvcDevices)
slowmoQuality Integer [1,100] rw quality of the slow motion recording encoder (default 85)
timelapseInputFps Number rw capture rate (frames per second) used as input for a timelapse recording (default 0.5)
see record option "timelapse"
timelapseOutputFps Number rw playback rate (frames per second) of the resulting timelapse video (default 30)
fotoResolution String rw resolution of the snapshot
"4K": 3840x2160
"FullHD": 1920x1080
"HD": 1280x720
pictureQuality Integer [1,100] rw quality of jpeg compressor
freeze Boolean rw freeze the stream
recordingWithTimeStamp Boolean rw burn the time into the recording.
independent of the live stream / visual backup, see "streamingWithTimeStamp"
not applied to slow motion recordings
recordingWithDateStamp Boolean rw burn the date into the recording.
independent of the live stream / visual backup, see "streamingWithDateStamp"
not applied to slow motion recordings
recordingTimestampSetting Json Object rw position and style of the timestamp overlay burned into the recording.
layout: {x: Number, y: Number, scaleValue: Number, drawBackdrop: Boolean, backdropColor: String, textColor: String}
streamingBps Number r ca. streaming bit per second
streamingFormat String rw video codec used for the live stream.
"h264" (default)
"hevc" (alias "h265")
streamingResolution String rw live stream resolution
"4K": 3840x2160
"FullHD": 1920x1080 (default)
"HD": 1280x720
streamingFps Integer rw live stream frames per second
options: 1,5,10,15,24,30,60 (default 30)
streamingQuality Integer [1,100] rw quality of the live stream encoder (default 75)
streamingBitrate Integer rw target live stream bitrate in bits per second.
0 ≙ automatic / variable bitrate (default)
streamingMaxBitrate Integer rw maximum live stream bitrate in bits per second (default 20000000 ≙ 20 Mbit/s)
streamingWithTimeStamp Boolean rw burn the time into the live stream - and therefore into the visual backup, which records the stream channel.
independent of the recording, see "recordingWithTimeStamp"
streamingWithDateStamp Boolean rw burn the date into the live stream - and therefore into the visual backup, which records the stream channel.
independent of the recording, see "recordingWithDateStamp"
streamingTimestampSetting Json Object rw position and style of the timestamp overlay burned into the live stream.
layout: {x: Number, y: Number, scaleValue: Number, drawBackdrop: Boolean, backdropColor: String, textColor: String}
systemDescription Json Object r hardware and system description of control unit
time Json Array of numbers r systems time [year,month,day,hours,minutes,seconds]
timezone String rw selected timezone
ntpHost String rw address ot the ntp server
ntpStatus Json Object r State of last connection try to ntp server
ntpSync Boolean rw enable ntp synchronization
seconds Integer r epoch time seconds
connectionUrls Json Object r list of detected and assumed possible connections
swVersion String r current software version
fmVersion String r current firmware version
httpOn Boolean rw http webserver run setting
httpsOn Boolean rw https webserver run setting
httpPort Integer [1,65000] rw http webserver port
httpsPort Integer [1,65000] rw https webserver port
httpStatus Json Object r http webserver status
httpsStatus Json Object r https webserver status
httpsCertificate Json Object r certificate description
categories Json Object r list of categories for the tags
changeTagCategory Json Object w create/update/delete tag category
category: { changeTagCategory: {action: String, id: String, name: String, color: String}}
action: "create", "update" or "delete"
example: {changeTagCategory: {action: "create", name: "new category", color: "#ff0000"}}
createTag Json Object w creates a new tag
layout { createTag: {title?: String, note?: String, category?: Name(String)|ID(Number), createdBy?: String}}
updateTag Json Object w updates a tag
layout {updateTag: {id: Number, title: String, note: String, category: ID(Number)}}
deleteTags Array of ID's(Numbers) w deletes tags by id
layout: {deleteTags: [id1, id2, ...]}
records Json Object rw returns a filtered list of records
request layout: {timestampStartMs: Number, timestampEndMs: Number}
response layout: {backup: [Objects], media: [Objects], tags: [Objects], timestampStartMs: Number, timestampEndMs: Number}]}

AI module

The AI module runs neural network models on the control unit (Hailo accelerator) and derives a traffic light, a live and history graph and automatic tags from their detections. It requires the license module ki (see licenseModules). There are three projects, each with its own models: humandetect (up to 4 models), spandetekt (chip detection, up to 4 models) and motiondetect. Only one project runs at a time.

Model management

Models are uploaded as .rhef bundle: the compiled Hailo model (HEF) plus an optional JSON configuration (the sidecar) with class names, detection profiles, traffic light thresholds and auto tag rules. Maximum size 55 MB. Both requests require the permission to change system settings and answer with the new content of kiModels (200).
Status codes upload: 400 - invalid project, name, bundle or JSON; 403 - missing permission; 409 - model limit of the project reached or model already exists; 413 - file too large.
Status codes delete: 404 - unknown model; 409 - the model is active while the AI is running.

Upload a model:
    POST https://rotoclear-cam.local:443/ki/models/upload?project=spandetekt&name=my_model.rhef&user=API-User&token=***
    Content-Type: multipart/form-data  (one part containing the .rhef file)

Delete a model:
    DELETE https://rotoclear-cam.local:443/ki/models/delete?project=spandetekt&name=my_model&user=API-User&token=***

AI states

API Key Value Datatype Permissions Description
kiControl Json Object rw start/stop the AI and select the project.
layout: {active: Boolean, project_name: "humandetect"|"spandetekt"|"motiondetect", confidence_threshold: Number, status: String, error: String}
write e.g. {kiControl: {project_name: "spandetekt", active: true}}
status: "idle", "pending" or "running"; error: reason why the AI is not running (e.g. "no license", "not available during recording")
the AI cannot run during a special recording (slow motion, X-recording)
kiModels Json Object rw models per project.
layout: {<project>: {models: [{name, size, uploadedAt, profiles: [String], sourceHash}], activeModel: String, limit: Number}}
writeable is only the active model: {kiModels: {spandetekt: {activeModel: "my_model"}}}
kiRuntimeSettings Json Object rw runtime settings per project, override the defaults of the model sidecar.
layout: {<project>: {displayMode, showTool, profile, autoTag, deletable, tagRetentionDays, window, triggerTime, gap, cooldown, classes, titles, ampel}}
defaults: profile "balanced", autoTag false, deletable true, window 2 s, triggerTime 10 s, gap 10 s, cooldown 20 s
only the sent keys are changed; null resets a key ({spandetekt: {window: null}}) or the whole project ({spandetekt: null}) to the model default
kiProjects Json Object r projects that currently deliver samples.
layout: {projects: [String]}
processAmpel Json Object r traffic light per running project, evaluated once per second from the thresholds of the model.
layout: {projects: {<project>: {state: "gray"|"green"|"orange"|"red"}}}
"gray" = AI not running or model without traffic light
processGraph Json Object r latest detection distribution per running project; sent with every sample (about once per second), also when the values are unchanged.
layout: {projects: {<project>: {classes: {<class name>: Number [0,1]}, frames: Number}}}
the value per class is the share of frames of that second in which the class was detected
kiLiveSamples Json Object w (query) raw samples of the last seconds, e.g. for a live graph.
request: {kiLiveSamples: {project: String, seconds?: Number (up to 60, default 60)}}
response: {kiLiveSamples: {project, classes: [String], t: [ms], frames: [Number], values: [[per mille per sample]]}} (values[class][sample])
kiGraphProjects Json Object w (query) projects with a stored history.
request: {kiGraphProjects: {}}
response: {kiGraphProjects: {projects: [{name, firstMs, lastMs}]}}
kiGraphHistory Json Object w (query) stored detection history of a project, aggregated into buckets. Requires a Visual Backup storage (retention 90 days).
request: {kiGraphHistory: {project: String, timestampStartMs: Number, timestampEndMs: Number, buckets?: Number}}
response: {kiGraphHistory: {project, timestampStartMs, timestampEndMs, t0, stepMs, count, classes: [String], frames: [..], wavg: [[..]], avg: [[..]], peak: [[..]]}} (values in per mille)
kiSample Json Object w input for AI processes: detection distribution of one second.
layout: {kiSample: {project: String, distribution: {<class name>: Number [0,1]}, frameCount: Number}}
only accepted for the running project; send only when frameCount > 0 (no samples = AI off)
scanForModel String w searches a storage device for .rhef bundles and installs them; the response lists installed and failed files with a reason.
request: {scanForModel: "<storage id>"} or {scanForModel: {storage: "<storage id>"}}
deleteKiModel Json Object w deletes a model, same as DELETE /ki/models/delete.
request: {deleteKiModel: {project: String, name: String}}
reconstruction3dActive Boolean r 3D reconstruction is running (set by the AI process)

Automatic tags

With autoTag switched on (see kiRuntimeSettings) the AI creates tags in the Visual Backup automatically: as soon as the average share of a class (over window seconds) stays above its threshold for triggerTime seconds, a tag is opened; it is extended while the class stays active and closed after gap seconds below the threshold. After closing, no new tag of the same class is opened for cooldown seconds. Tags are only created while the Visual Backup is recording.

AI tags carry auto: true and deletable (true = the video is not protected from cleanup). Category and title are stored as translation keys, not as text: the category is aiTagCategoryChip, the title the key of the class (e.g. aiSpanClassSpanstau). The web and HDMI clients show them translated; API clients receive the keys (see records, categories and the tag export).

Code Examples

These code examples will help you get started with our API.

  • C#
  • NIM
  • Python

Node.js

npm install websocket


#!/usr/bin/env node

// Rotoclear C Pro - WebSocket API Example
//
// 1. Connect to the WebSocket API
// 2. Check if the first camera stream is available
// 3. Toggle the light of the first camera
// 4. Download and save a JPEG image
// 5. Close the connection
//
// Install dependencies:
//   npm install websocket

const WebSocket = require("websocket").w3cwebsocket;
const http = require("http");
const fs = require("fs");

const ROTO_IP = "192.168.0.123";
const ROTO_PORT = 80;
const API_TOKEN = "YOUR_API_TOKEN";

const baseUrl = `http://${ROTO_IP}:${ROTO_PORT}`;
const auth = `user=API-User&token=${encodeURIComponent(API_TOKEN)}`;

const websocketUrl =
  `ws://${ROTO_IP}:${ROTO_PORT}/api?${auth}`;

const imageUrl = `${baseUrl}/camera.jpeg?${auth}`;
const imageName = "cpro_image.jpg";

const connection = new WebSocket(websocketUrl);
let processed = false;

function sendToAPI(message) {
  connection.send(JSON.stringify(message));
}

function downloadImage() {
  return new Promise((resolve, reject) => {
    http.get(imageUrl, (response) => {
      if (response.statusCode !== 200) {
        response.resume();
        reject(new Error(`HTTP ${response.statusCode}`));
        return;
      }

      const chunks = [];

      response.on("data", chunk => chunks.push(chunk));
      response.on("error", reject);

      response.on("end", () => {
        fs.writeFileSync(imageName, Buffer.concat(chunks));
        console.log(`Image saved: ${imageName}`);
        resolve();
      });
    }).on("error", reject);
  });
}

connection.onopen = () => {
  console.log("Connected to Rotoclear C Pro");
};

connection.onerror = (error) => {
  console.error("WebSocket error:", error);
};

connection.onclose = () => {
  console.log("Connection closed");
};

connection.onmessage = async (event) => {
  if (processed || typeof event.data !== "string") return;

  try {
    const state = JSON.parse(event.data);

    // The first message contains the initial system state.
    if (typeof state.cam0Exists !== "boolean") return;

    processed = true;

    if (!state.cam0Exists) {
      console.log("No camera stream detected");
      connection.close();
      return;
    }

    console.log("Camera stream detected");

    // Toggle camera light (boolean values as documented).
    if (typeof state.light0 === "boolean") {
      sendToAPI({ light0: !state.light0 });
    } else {
      console.log("Light state not available as boolean");
    }

    await downloadImage();

  } catch (error) {
    console.error("Error:", error.message);
  } finally {
    if (processed) connection.close();
  }
};

C#

dotnet new console


using System;
using System.IO;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

// Rotoclear C Pro - C# WebSocket API Example

class Program
{
    const string ServerIp = "192.168.0.123";
    const int ServerPort = 80;
    const string ApiToken = "YOUR_API_TOKEN";

    static async Task SendJson(
        ClientWebSocket socket,
        object message)
    {
        string json = JsonSerializer.Serialize(message);
        byte[] bytes = Encoding.UTF8.GetBytes(json);

        await socket.SendAsync(
            new ArraySegment<byte>(bytes),
            WebSocketMessageType.Text,
            true,
            CancellationToken.None
        );
    }

    static async Task<string> ReceiveMessage(
        ClientWebSocket socket)
    {
        byte[] buffer = new byte[8192];
        using var stream = new MemoryStream();

        while (true)
        {
            var result = await socket.ReceiveAsync(
                new ArraySegment<byte>(buffer),
                CancellationToken.None
            );

            if (result.MessageType == WebSocketMessageType.Close)
                throw new Exception("WebSocket closed by server");

            stream.Write(buffer, 0, result.Count);

            if (result.EndOfMessage)
                break;
        }

        return Encoding.UTF8.GetString(stream.ToArray());
    }

    static async Task Main()
    {
        string auth =
            "user=API-User&token=" +
            Uri.EscapeDataString(ApiToken);

        string wsUrl =
            $"ws://{ServerIp}:{ServerPort}/api?{auth}";

        string imageUrl =
            $"http://{ServerIp}:{ServerPort}/camera.jpeg?{auth}";

        using var socket = new ClientWebSocket();

        try
        {
            await socket.ConnectAsync(
                new Uri(wsUrl),
                CancellationToken.None
            );

            Console.WriteLine("Connected to Rotoclear C Pro");

            string response = await ReceiveMessage(socket);

            using var document = JsonDocument.Parse(response);
            JsonElement state = document.RootElement;

            Console.WriteLine(state.ToString());

            bool cameraAvailable =
                state.TryGetProperty("cam0Exists", out var camera) &&
                camera.ValueKind == JsonValueKind.True;

            if (!cameraAvailable)
            {
                Console.WriteLine("No camera stream detected");
                return;
            }

            // Toggle the camera light
            if (state.TryGetProperty("light0", out var light) &&
                (light.ValueKind == JsonValueKind.True ||
                 light.ValueKind == JsonValueKind.False))
            {
                bool lightOn = light.GetBoolean();

                await SendJson(socket, new
                {
                    light0 = !lightOn
                });
            }

            // Download JPEG image
            using var client = new HttpClient();

            using var imageResponse = await client.GetAsync(imageUrl);
            imageResponse.EnsureSuccessStatusCode();

            byte[] imageBytes =
                await imageResponse.Content.ReadAsByteArrayAsync();

            await File.WriteAllBytesAsync(
                "cpro_image.jpg",
                imageBytes
            );

            Console.WriteLine("Image saved: cpro_image.jpg");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        finally
        {
            if (socket.State == WebSocketState.Open)
            {
                await socket.CloseAsync(
                    WebSocketCloseStatus.NormalClosure,
                    "Finished",
                    CancellationToken.None
                );
            }
        }
    }
}

NIM

# Rotoclear C Pro - Nim HTTP API Example
#
# 1. Connect to the HTTP API
# 2. Read selected system state variables
# 3. Set zoom position and zoom factor
# 4. Read the updated state
#
# Note:
# The C Pro uses zoomState instead of pan0 / zoom0.

import std/[httpclient, json, strformat, uri]

const
  rotoclearIp = "192.168.0.123"
  rotoclearPort = 80
  apiToken = "YOUR_API_TOKEN"

let
  baseUrl = fmt"http://{rotoclearIp}:{rotoclearPort}"
  auth = "user=API-User&token=" & encodeUrl(apiToken)
  apiUrl = baseUrl & "/api?" & auth

var client = newHttpClient()

try:
  # Read selected system variables
  let getRequest = %*{
    "get": [
      "cam0Exists",
      "light0",
      "record",
      "recordTime",
      "zoomState"
    ]
  }

  client.headers = newHttpHeaders({
    "Content-Type": "application/json"
  })

  let getResponse = client.request(
    apiUrl,
    httpMethod = HttpPost,
    body = $getRequest
  )

  if getResponse.code != Http200:
    raise newException(
      IOError,
      "API request failed: " & $getResponse.code
    )

  let state = parseJson(getResponse.body)

  echo "Current system state:"
  echo state.pretty()

  # Set zoom position and zoom factor
  #
  # left: relative horizontal position [0.0, 1.0]
  # top:  relative vertical position [0.0, 1.0]
  # zoom: zoom factor [1.0, 4.0]
  #
  # Unlike C2 pan0, these are not relative
  # displacement commands.

  let zoomRequest = %*{
    "zoomState": {
      "left": 0.2,
      "top": 0.3,
      "zoom": 2.0
    }
  }

  let setResponse = client.request(
    apiUrl,
    httpMethod = HttpPost,
    body = $zoomRequest
  )

  if setResponse.code != Http200:
    raise newException(
      IOError,
      "Zoom request failed: " & $setResponse.code
    )

  echo "Zoom response:"
  echo parseJson(setResponse.body).pretty()

  # Read back the applied zoom state
  let verifyRequest = %*{
    "get": ["zoomState"]
  }

  let verifyResponse = client.request(
    apiUrl,
    httpMethod = HttpPost,
    body = $verifyRequest
  )

  if verifyResponse.code != Http200:
    raise newException(
      IOError,
      "Verification failed: " & $verifyResponse.code
    )

  echo "Applied zoom state:"
  echo parseJson(verifyResponse.body).pretty()

except CatchableError as error:
  echo "Error: ", error.msg

finally:
  client.close()
# Example in NIM - Use http api to get and set data
#
# 1. Connect to websocket-server
# 2. Fetch some information from the system (eg. light0, record, recordTime, pan0)
# 3. Disable light and move pan cursor from current position via post request
# 

import std/[strformat, json, httpclient]

const
  rotoclearIp = "192.168.178.61" 
  rotoclearApiPort = "80" 
  apiToken = "1a2B3c4D5e6f7G8h"
  urlWithAuthInQuery = fmt("http://{rotoclearIp}:{rotoclearApiPort}/api?token={apiToken}")

let
  client = newHttpClient()
  response = client.getContent(urlWithAuthInQuery & "&get=[light0,record,recordTime,pan0]")
  jsonResponse = response.parseJson()

echo jsonResponse.pretty()

# disable light and move pan cursor from current position via post request
let
  message = %*{ 
    "light0": false,
    "pan0": { # relative values
      "x": -20.0, 
      "y": -30.0
    }
  }

echo client.postContent(urlWithAuthInQuery, $message)

Python3

pip install requests


#!/usr/bin/env python3

# Rotoclear C Pro - Python HTTP API Example
#
# 1. Connect to the HTTP API
# 2. Read selected system state variables
# 3. Disable camera light (if boolean)
# 4. Set zoom position and zoom factor
# 5. Verify the updated state

import requests

ROTOCLEAR_IP = "192.168.0.123"
ROTOCLEAR_PORT = 80
API_TOKEN = "YOUR_API_TOKEN"

API_URL = (
    f"http://{ROTOCLEAR_IP}:{ROTOCLEAR_PORT}/api"
)

AUTH = ("API-User", API_TOKEN)

session = requests.Session()
session.auth = AUTH

try:
    # Read selected system state variables
    get_request = {
        "get": [
            "cam0Exists",
            "light0",
            "record",
            "recordTime",
            "zoomState"
        ]
    }

    response = session.post(
        API_URL,
        json=get_request,
        timeout=10
    )
    response.raise_for_status()

    state = response.json()

    print("Current system state:")
    print(state)

    if not state.get("cam0Exists", False):
        print("No camera stream detected")
    else:
        print("Camera stream detected")

        # Disable camera light if boolean is supported
        if isinstance(state.get("light0"), bool):
            light_response = session.post(
                API_URL,
                json={"light0": False},
                timeout=10
            )
            light_response.raise_for_status()
            print("Light response:", light_response.json())

        # Set zoom position and zoom factor
        #
        # left: relative horizontal position [0.0, 1.0]
        # top:  relative vertical position [0.0, 1.0]
        # zoom: zoom factor [1.0, 4.0]

        zoom_request = {
            "zoomState": {
                "left": 0.2,
                "top": 0.3,
                "zoom": 2.0
            }
        }

        response = session.post(
            API_URL,
            json=zoom_request,
            timeout=10
        )
        response.raise_for_status()

        print("Zoom response:")
        print(response.json())

        # Verify the applied zoom state
        response = session.post(
            API_URL,
            json={"get": ["zoomState"]},
            timeout=10
        )
        response.raise_for_status()

        print("Applied zoom state:")
        print(response.json())

except requests.RequestException as error:
    print("HTTP/API error:", error)

except ValueError as error:
    print("Invalid JSON response:", error)

finally:
    session.close()
#!/usr/bin/python3

# Example in Python3 - Use http api to get and set data
#
# 1. Connect to websocket-server
# 2. Fetch some information from the system (eg. light0, record, recordTime, pan0)
# 3. Disable light and move pan cursor from current position via post request
#
# Install dependencies:
#   pip install requests
#   pip install json
#

import requests
import json

ROTO_CLEAR_IP = "192.168.178.61"
ROTO_CLEAR_PORT = "80"
MY_API_TOKEN = "1a2B3c4D5e6f7G8h"
HTTP_API_URL_WITH_AUTH = "http://" + ROTO_CLEAR_IP + ":" + ROTO_CLEAR_PORT + "/api?user=API-User&token=" + MY_API_TOKEN

response = requests.get(HTTP_API_URL_WITH_AUTH + 
                            "&get=[light0,record,recordTime,pan0]")
jsonResponse = json.loads(response.content)

print(jsonResponse)

# disable light and move pan cursor from current position via post request
message = json.dumps({ 
    "light0": False,
    "pan0": { # relative values
        "x": -20.0, 
        "y": -30.0
    }
})

response = requests.post(HTTP_API_URL_WITH_AUTH, message)
print(response.content)