Skip to content
Snippets Groups Projects
Select Git revision
  • master default
  • feature/typescript
  • feature/formatting
  • feature/arm7
  • super_worker
  • worker
  • 0.17.10
  • 0.17.9
  • 0.17.8
  • 0.17.7
  • 0.17.4
  • 0.17.3
  • 0.17.2
  • v0.17.1
  • 0.15.1
  • 0.15.0
  • v0.10.4
17 results

motorcortex-js

  • Clone with SSH
  • Clone with HTTPS
  • user avatar
    Alexey Zakharov authored
    1641c8b6
    History

    Welcome to Motorcortex JS

    Motorcortex JS is a communication library to develop JavaScript client applications for the Motorcortex Core. Motorcortex JS provides an implementation of the low-level API defined in motorcortex.proto.

    Motorcortex Core is a hard-real-time Linux-based Control System Framework for building high-end industrial applications. It provides real-time control of inductrial hardware (e.g. over EtherCAT) and flexible, high-performance communication server to interact with higher level applications (such as a User Interface, Data Visualization or Analysis Tools). Motorcortex server allows direct real-time communication to the webbrowser.

    Motorcortex currently has open API's for JavaScript, Python, C++ and C# bindings.

    Prerequisites

    Node.js v7.10+
    Node npm v5.3+

    Installation

    npm install @vectioneer/motorcortex-js
    npm run build
    
    Build library is in the ./dist folder.

    Modules

    motorcortex

    Motorcortex Bindings for JavaScript

    Classes

    MessageTypes

    Class for handling motorcortex data types: load proto and hash files, creates a dictionary with all available data types, resolves data types by name or by hash, performs encoding and decoding of the messages.

    Request

    Request/Reply communication is used to send commands to a motorcortex server.

    RequestAsync

    Request/Reply communication is used to send commands to a motorcortex server.

    ConnectionData

    Container for the session parameters

    SessionManager

    SessionManager manages a communication session for Request and Subscribe. SessionManager monitors if the connection is alive and tries to recover if the connection is lost.

    Parameter

    Parameter value with a timestamp

    Subscription

    Subscription class represents an active subscription group. It returns latest values and timestamps of the group parameters. Subscription class could be used as an observer, which notifies on every update or could be used as polling.

    Subscribe

    Subscribe class is used to receive continuous parameter updates from motorcortex server. Subscribe class simplifies creating and removing subscription groups.

    Constants

    SessionState

    Enumerator of possible session states

    Typedefs

    SubscriptionClb : function

    This callback is resolved when subscription is ready or failed.

    SubscriptionUpdateClb : function

    This callback notifies when subscription is updated with new values.

    motorcortex

    Motorcortex Bindings for JavaScript

    Author: Alexey Zakharov zakharov@vectioneer.com
    License: Copyright (C) Vectioneer - All Rights Reserved
    Copyright: Vectioneer

    module.exports ⏏️

    motorcortex namespace.

    Kind: Exported member

    module.exports.statusToStr(code) ⇒ string

    Returns description of the Motorcortex Status Code. Status codes are defined in the StatusCode enumerator in msg/motorcortex.proto.

    Kind: static method of module.exports
    Returns: string - Text description of the status

    Param Type Description
    code number Code of the status.

    Example

    motorcortex.statusToStr(0x2100);

    module.exports.getDataType(name) ⇒ number

    Returns a сode of the Parameter Data Type. Сodes are defined in the DataType enumerator in msg/motorcortex.proto.

    Kind: static method of module.exports
    Returns: number - Code of the data dype

    Param Type Description
    name string Name of the data type.

    Example

    if (parameterDataType === motorcortex.getDataType('UINT8')) {
       // do something
    }

    module.exports.getParameterFlag(name) ⇒ number

    Returns a сode of the Parameter Flag. Сodes are defined in the ParameterFlag enumerator in msg/motorcortex.proto.

    Kind: static method of module.exports
    Returns: number - Code of the parameter flag

    Param Type Description
    name string Name of the flag.

    Example

    if (parameterFlag === motorcortex.getParameterFlag('OVERWRITE_IS_ACTIVE')) {
       // do something
    }

    module.exports.getParameterType(name) ⇒ number

    Returns a сode of the Parameter Type. Сodes are defined in the ParameterType enumerator in msg/motorcortex.proto.

    Kind: static method of module.exports
    Returns: number - Code of the parameter type

    Param Type Description
    name string Name of the flag.

    Example

    if (parameterType === motorcortex.getParameterType('INPUT')) {
       // do something
    }

    module.exports.getPermission(name) ⇒ number

    Returns a сode of the Permision Type. Сodes are defined in the Permission enumerator in msg/motorcortex.proto.

    Kind: static method of module.exports
    Returns: number - Code of the permission type

    Param Type Description
    name string Name of the permission type.

    Example

    if (parameterDataType | motorcortex.getPermission('USER_WRITE')) {
       // user has a write access
    }

    module.exports.getStatusCode(name) ⇒ number

    Returns a сode of the Status. Сodes are defined in the StatusCode enumerator in msg/motorcortex.proto.

    Kind: static method of module.exports
    Returns: number - Code of the status

    Param Type Description
    name string Name of the status code.

    Example

    if (replyCode === motorcortex.getStatusCode('OK')) {
       // all good
       console.log(motorcortex.statusToStr(motorcortex.getStatusCode('OK')));
    }

    module.exports.getUserGroup(name) ⇒ number

    Returns a сode of the User Group. Сodes are defined in the UserGroup enumerator in msg/motorcortex.proto.

    Kind: static method of module.exports
    Returns: number - Code of the user group

    Param Type Description
    name string Name of the user group.

    Example

    if (userGroup === motorcortex.getUserGroup('OPERATOR')) {
       // operator has an access
    }

    MessageTypes

    Class for handling motorcortex data types: load proto and hash files, creates a dictionary with all available data types, resolves data types by name or by hash, performs encoding and decoding of the messages.

    Kind: global class

    new exports.MessageTypes()

    Creates message types object

    messageTypes.load(proto_hash_pair_list) ⇒ Promise.<string>

    Loads an array of .proto and .json file pairs.

    Kind: instance method of MessageTypes
    Returns: Promise.<string> - Returns a Promise, which is resolved when loading is complete.

    Param Type Description
    proto_hash_pair_list Array.<object> a list of corresponding proto message files and hash files.

    Example

    let motorcortex_types = new motorcortex.MessageTypes();
    let type_load_done = motorcortex_types.load([{
         proto: 'msg/motorcortex.proto',
         hash: 'msg/motorcortex_hash.json'}, {
         proto: 'msg/motionJS.proto',
         hash: 'msg/motionJS_hash.json'}, {
         proto: 'msg/motionSL.proto',
         hash: 'msg/motionSL_hash.json'
    }]);
    
    type_load_done.then(() => {
         console.log('Loaded all data types');}).catch((reason) => {
         console.error('Failed to load data types: ' + reason);
    });

    messageTypes.createType(type_name, [payload]) ⇒ object

    Returns an instance of the loaded data type and fills it with payload.

    Kind: instance method of MessageTypes
    Returns: object - Instance of the requested type, filled with payload.

    Param Type Description
    type_name string Type name from the proto files.
    [payload] object Payload data to fill.

    Example

    let load_msg = motorcortex_types.createType('motorcortex.LoadMsg', { path: '', fileName: 'control.xml' });
    let encoded_msg = this.encode(load_msg);

    messageTypes.getTypeByName(type_name) ⇒ object

    Returns type with given name

    Kind: instance method of MessageTypes
    Returns: object - Returns a Protobuf Type

    Param Type Description
    type_name string Name of the message type from the proto files.

    Example

    let ErrorList = motorcortex_types.getTypeByName('motorcortex.ErrorList');
    let error_list = ErrorList.decode(encoded_msg);
    console.log('Error list: ', error_list);

    Request

    Request/Reply communication is used to send commands to a motorcortex server.

    Kind: global class

    new exports.Request(protobuf_types)

    Creates request object

    Param Type Description
    protobuf_types MessageTypes Reference to an instance of the MessageTypes class.

    request.getMessageTypes()

    Returns loaded message types.

    Kind: instance method of Request

    request.connectionState() ⇒ number

    Actual Request/reply connection state.

    Kind: instance method of Request
    Returns: number - Returns a connection state.
    Example

    CONNECTING   0    The connection is not yet open
    OPEN         1    The connection is open and ready to communicate
    CLOSING      2    The connection is in the process of closing
    CLOSED       3    The connection is closed or could not be opened

    request.connect(url, timeout_ms, max_request_queue_size) ⇒ Promise.<string>

    Opens a request connection.

    Kind: instance method of Request
    Returns: Promise.<string> - A promise, which completes when connection is ready. If connection fails, a short error description is passed to the catch method.

    Param Type Description
    url string Motorcortex server URL.
    timeout_ms number Reply timeout in milliseconds.
    max_request_queue_size number Maximum size of the request queue.

    Example

    let req = new motorcortex.Request(motorcortex_types);
    let req_conn_done = req.connect(`ws://${server}:5558`, 10000, 100);
    req_conn_done
    .then(() => {
          console.log('Request connection is established');
      })
    .catch((reason) => {
          console.error('Failed to establish connection: ' + reason);
      });

    request.close()

    Closes connection to the server

    Kind: instance method of Request

    request.encode(msg) ⇒ Uint8Array

    Encodes a data type from MessageTypes to a binary wire type.

    Kind: instance method of Request
    Returns: Uint8Array - msg A binary array with encoded message.

    Param Type Description
    msg Object A message created by MotorcortexTypes.

    Example

    let motion_script = motorcortex_types.createType('motion_spec.MotionScript', {.id = 1, name = 'Test script'});
    motion_script.script = `print('Hello world');`;
    let encoded_msg = req.encode(motion_script);
    req.send(encoded_msg);

    request.send(encoded_msg, timeout_ms) ⇒ Promise.<Object>

    Sends an encoded request to the server

    Kind: instance method of Request
    Returns: Promise.<Object> - Returns a Promise, which completes when reply from the server is received. If request fails, catch callback is triggered.

    Param Type Description
    encoded_msg Uint8Array A binary array with encoded message.
    timeout_ms integer Timeout in milliseconds.

    Example

    let joint2cart = calcJointToCart({
         cartpose: [0, 0, 0, 0, 0, 0],
         jointpose: [0, 0, 1.57, 0, 1.57, 0] });
    let reply = req.send(req.encode(joint2cart));
    reply.then((msg) => {
         console.log('Got reply: ' + JSON.stringify(msg));
    }).catch((msg) => {
         console.error('Failed: ' + JSON.stringify(msg));
    });

    request.sendMsg(msg) ⇒ Promise.<Object>

    Encodes and sends a request to the server

    Kind: instance method of Request
    Returns: Promise.<Object> - Returns a Promise, which completes when reply from the server is received.

    Param Type Description
    msg Object A message created by MotorcortexTypes.

    Example

    let motion_script = motorcortex_types.createType('motion_spec.MotionScript', {.id = 1, name = 'Test script'});
    motion_script.script = `print('Hello world');`;
    let reply = req.encodeAndSend(motion_script);
    reply.then((msg) => {
         console.log('Got reply: ' + JSON.stringify(msg));
    }).catch((msg) => {
         console.error('Failed: ' + JSON.stringify(msg));
    });

    request.login(login, password) ⇒ Promise.<StatusMsg>

    Sends a login request to the server

    Kind: instance method of Request
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves if login is successful and fails otherwise. Returned message has a status code, which indicates a status of the login.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    login string User login.
    password string User password.

    Example

    let login_reply = req.login('operator', 'god123');
    login_reply.then((reply) => {
         console.log('Logged-in successful: ' + motorcortex.statusToStr(reply.status));
    }).catch((reply) => {
         console.log('Failed to login: ' + motorcortex.statusToStr(reply.status));
    });

    request.getSessionTokenMsg()

    Kind: instance method of Request

    request.restoreSessionMsg()

    Kind: instance method of Request

    request.logout() ⇒ Promise.<StatusMsg>

    Sends logout request to the server

    Kind: instance method of Request
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves if login is successful and fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode
    Example

    let logout_reply = req.logout();
    logout_reply.then((reply) => {
         console.log('Logged-out successful: ' + motorcortex.statusToStr(reply.status));
    }).catch((reply) => {
         console.log('Failed to logout: ' + motorcortex.statusToStr(reply.status));
    });

    request.getParameterTree(timeout_msec) ⇒ Promise.<ParameterTreeManager>

    Requests a parameter tree manager to update its structure from the cache or from the server

    Kind: instance method of Request
    Returns: Promise.<ParameterTreeManager> - Returns a Promise, which resolves when the parameter tree is received or fails otherwise.
    See: ParameterTreeManager

    Param Type Description
    timeout_msec integer Timeout in milliseconds.

    Example

    let param_tree_reply = req.getParameterTree();
    param_tree_reply.then((param_tree_manager) => {
         console.log('Got parameter tree msg: ' + JSON.stringify(param_tree_manager.getList()));
    }).catch((param_tree) => {
         console.log('Failed to get parameter tree: ' + motorcortex.statusToStr(param_tree.status));
    });

    request.getParameterTreeHash() ⇒ Promise.<ParameterTreeHashMsg>

    Requests a parameter tree hash from the server

    Kind: instance method of Request
    Returns: Promise.<ParameterTreeHashMsg> - Returns a Promise, which resolves when tree hash message is received or fails otherwise.
    See: motorcortex.proto, ParameterTreeHashMsg, StatusCode
    Example

    let tree_hash_reply = req.getParameterTreeHash();
    tree_hash_reply.then((tree_hash) => {
         console.log('Got parameter tree hash: ' + tree_hash.hash);
    }).catch((tree_hash) => {
         console.log('Failed to get tree hash: ' + motorcortex.statusToStr(tree_hash.status));
    });

    request.getParameter(path) ⇒ Promise.<ParameterMsg>

    Requests a parameter with full information and value from the server

    Kind: instance method of Request
    Returns: Promise.<ParameterMsg> - Returns a Promise, which resolves when parameter message is successfully obtained, fails otherwise.
    See: motorcortex.proto, ParameterMsg, StatusCode

    Param Type Description
    path string Parameter path in the tree.

    Example

    let param_reply = req.getParameter('root/Control/actualActuatorPositions');
    param_reply.then((param) => {
         console.log('Got parameter: ' + JSON.stringify(param));
    }).catch((param) => {
         console.log('Failed to get parameter: ' + motorcortexs.statusToStr(param.status));
    });

    request.setParameter(path, value, [options]) ⇒ Promise.<StatusMsg>

    Sets new value to a parameter with given path.

    Kind: instance method of Request
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when parameter value is updated or fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    path string Parameter path in the tree.
    value any New parameter value.
    [options] Object Various options to parametrize Set operation. For example 'offset' and 'length' could be used to set an element offset and number of the elements to update in the destination array.

    Example

    // updates a value of a simple parameter
    let reply_handle = req.setParameter('root/Motorcontroller/actualmode', 2);
    reply_handle.catch((reply) => {
         console.log('Failed to set parameter: ' + motorcortex.statusToStr(reply.status));
    });
    
    // updates an array
    req.setParameter('root/Control/dummyDoubleArray6', [1.1,1.2,1.3,1.4,1.5,1.6]);
    // updates single element of array with the offset 2 (index 3)
    req.setParameter('root/Control/dummyDoubleArray6', 1.0, {offset: 2});
    // updates 2 elements of the arrays with the offset 4
    req.setParameter('root/Control/dummyDoubleArray6', [10.0, 20.0], {offset: 4, length: 2});

    request.overwriteParameter(path, value, force_activate, [options]) ⇒ Promise.<StatusMsg>

    Overwrites actual value of the parameter and depending on the flag forces this value to stay active. This method of setting values is useful during debug and installation process, it is not recommended to use this method during normal operation.

    Kind: instance method of Request
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when parameter value is updated or fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Default Description
    path string Parameter path in the tree.
    value any New parameter value.
    force_activate boolean false Forces new value to stay active. By default is set to 'false'.
    [options] Object Various options to parametrize Set operation. For example 'offset' and 'length' could be used to set an element offset and number of the elements to update in the destination array.

    Example

    // overwrite and force to stay active a value of a simple parameter
    let reply_handle = req.overwriteParameter('root/Motorcontroller/actualmode', 2, true);
    reply_handle.catch((reply) => {
         console.log('Failed to set parameter: ' + motorcortex.statusToStr(reply.status));
    });
    
    // overwrite and force to stay active an array
    req.overwriteParameter('root/Control/dummyDoubleArray6', [1.1,1.2,1.3,1.4,1.5,1.6], true);
    // overwrite and release force of a single element of the array with an offset 2 (index 3)
    req.overwriteParameter('root/Control/dummyDoubleArray6', 1.0, {offset: 2});
    // overwrite and force to stay active 2 elements of the arrays with an offset 4
    req.overwriteParameter('root/Control/dummyDoubleArray6', [10.0, 20.0], {offset: 4, length: 2});

    request.releaseParameter(path) ⇒ Promise.<StatusMsg>

    Deactivate overwrite operation of the parameter.

    Kind: instance method of Request
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when parameter overwrite is deactivated or fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    path string Path to a parameter in the tree.

    Example

    let reply_handle = releaseParameter('root/Motorcontroller/actualmode');
    reply_handle.catch((reply) => {
         console.log('Failed to release overwrite of the parameter: ' + motorcortex.statusToStr(reply.status));
    });

    request.setParameterList(param_list) ⇒ Promise.<StatusMsg>

    Sets new values to a parameter list.

    Kind: instance method of Request
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when parameters from the list are updated, otherwise fails.
    See: setParameter, motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    param_list Array.<{path, value, options}> A list of the parameters to update values.

    Example

    let reply_handle = req.setParameterList([{path: 'root/Motorcontroller/actualmode', value: 2},
         {path: 'root/Control/dummyDoubleArray6', value: [1.1,1.2,1.3,1.4,1.5,1.6]},
         {path: 'root/Control/dummyDoubleArray6', value: [10.0, 20.0], options:  {offset: 4, length: 2}}]);
    reply_handle.catch((reply) => {
         console.log('Failed to set list of parameter: ' + motorcortex.statusToStr(reply.status));
    });

    request.getParameterList(path_list, timeout_ms) ⇒ Promise.<StatusMsg>

    Get info and values of requested parameters.

    Kind: instance method of Request
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when list of the parameter values is received, otherwise fails.
    See: getParameter, motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    path_list Array.<string> List of parameter paths.
    timeout_ms number Reply timeout in milliseconds.

    Example

    let reply_handle = req.getParameterList(['root/Motorcontroller/actualmode, 'root/Control/dummyDoubleArray6']);
    reply_handle.then((param_list) => {
         console.log('Got parameter list: ' + JSON.stringify(param_list));
    }).catch((param_list) => {
         console.log('Failed to get parameter list: ' + motorcortex.statusToStr(param_list.status));
    });

    request.createGroup(path_list, group_alias, [frq_divider]) ⇒ Promise.<GroupStatusMsg>

    Create a subscription group for a list of the parameters. This method is used inside Subscription class, use subscription class instead.

    Kind: instance method of Request
    Returns: Promise.<GroupStatusMsg> - Returns a Promise, which resolves when subscription is complete, fails otherwise.
    See: Subscription, motorcortex.proto, GroupStatusMsg, StatusCode

    Param Type Description
    path_list Array.<string> List of the parameters to subscribe to.
    group_alias string Name of the group.
    [frq_divider] number Frequency divider is downscaling factor of the group publish rate. Default value is 1, every cycle of the publisher.

    Example

    // creates a group with two signals, which is published every 10th cycle.
    let group_handle = req.createGroup(['root/Motorcontroller/actualmode, 'root/Control/dummyDoubleArray6'],
         'myGroup1', 10);
    reply_handle.then((group) => {
         console.log('Group layout: ' + JSON.stringify(group));
    }).catch((group) => {
         console.log('Failed to create group: ' + motorcortex.statusToStr(group.status));
    });

    request.removeGroup(group_alias) ⇒ Promise.<StatusMsg>

    Unsubscribes from the group. This method is used inside Subscription class, use subscription class instead.

    Kind: instance method of Request
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when the unsubscribe operation is complete, fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    group_alias string Name of the group to unsubscribe from.

    Example

    let group_handle = req.removeGroup('myGroup1');
    group_handle.catch((group) => {
         console.log('Failed to remove group: ' + motorcortex.statusToStr(group.status));
    });

    request.save(file_name) ⇒ Promise.<StatusMsg>

    Request a server to save a parameter tree in the file.

    Kind: instance method of Request
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when save operation is completed, fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    file_name string A file name where to save actual state of the parameter tree

    Example

    let reply = req.save('controls.xml');
    reply.catch((save) => {
         console.log('Failed to save parameters:' + motorcortex.statusToStr(save.status));
    });

    request.load(file_name) ⇒ Promise.<StatusMsg>

    Request a server to load value from the file to the parameter tree.

    Kind: instance method of Request
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when load operation is complete, fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    file_name string A file name from which to load values to the parameter tree.

    Example

    let reply = req.load('controls.xml');
    reply.catch((load) => {
         console.log('Failed to load parameters:' + motorcortex.statusToStr(load.status));
    });

    RequestAsync

    Request/Reply communication is used to send commands to a motorcortex server.

    Kind: global class

    new exports.RequestAsync(protobuf_types)

    Creates request object

    Param Type Description
    protobuf_types MessageTypes Reference to an instance of the MessageTypes class.

    requestAsync.getMessageTypes()

    Returns loaded message types.

    Kind: instance method of RequestAsync

    requestAsync.connectionState() ⇒ number

    Actual Request/reply connection state.

    Kind: instance method of RequestAsync
    Returns: number - Returns a connection state.
    Example

    CONNECTING   0    The connection is not yet open
    OPEN         1    The connection is open and ready to communicate
    CLOSING      2    The connection is in the process of closing
    CLOSED       3    The connection is closed or could not be opened

    requestAsync.close()

    Closes connection to the server

    Kind: instance method of RequestAsync

    requestAsync.login(login, password) ⇒ Promise.<StatusMsg>

    Sends a login request to the server

    Kind: instance method of RequestAsync
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves if login is successful and fails otherwise. Returned message has a status code, which indicates a status of the login.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    login string User login.
    password string User password.

    Example

    let login_reply = req.login('operator', 'god123');
    login_reply.then((reply) => {
         console.log('Logged-in successful: ' + motorcortex.statusToStr(reply.status));
    }).catch((reply) => {
         console.log('Failed to login: ' + motorcortex.statusToStr(reply.status));
    });

    requestAsync.logout() ⇒ Promise.<StatusMsg>

    Sends logout request to the server

    Kind: instance method of RequestAsync
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves if login is successful and fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode
    Example

    let logout_reply = req.logout();
    logout_reply.then((reply) => {
         console.log('Logged-out successful: ' + motorcortex.statusToStr(reply.status));
    }).catch((reply) => {
         console.log('Failed to logout: ' + motorcortex.statusToStr(reply.status));
    });

    requestAsync.getSessionTokenMsg()

    Kind: instance method of RequestAsync

    requestAsync.restoreSessionMsg()

    Kind: instance method of RequestAsync

    requestAsync.getParameterTree(timeout_msec) ⇒ Promise.<ParameterTreeManager>

    Requests a parameter tree manager to update its structure from the cache or from the server

    Kind: instance method of RequestAsync
    Returns: Promise.<ParameterTreeManager> - Returns a Promise, which resolves when the parameter tree is received or fails otherwise.
    See: ParameterTreeManager

    Param Type Description
    timeout_msec integer Timeout in milliseconds.

    Example

    let param_tree_reply = req.getParameterTree();
    param_tree_reply.then((param_tree_manager) => {
         console.log('Got parameter tree msg: ' + JSON.stringify(param_tree_manager.getList()));
    }).catch((param_tree) => {
         console.log('Failed to get parameter tree: ' + motorcortex.statusToStr(param_tree.status));
    });

    requestAsync.getParameterTreeHash() ⇒ Promise.<ParameterTreeHashMsg>

    Requests a parameter tree hash from the server

    Kind: instance method of RequestAsync
    Returns: Promise.<ParameterTreeHashMsg> - Returns a Promise, which resolves when tree hash message is received or fails otherwise.
    See: motorcortex.proto, ParameterTreeHashMsg, StatusCode
    Example

    let tree_hash_reply = req.getParameterTreeHash();
    tree_hash_reply.then((tree_hash) => {
         console.log('Got parameter tree hash: ' + tree_hash.hash);
    }).catch((tree_hash) => {
         console.log('Failed to get tree hash: ' + motorcortex.statusToStr(tree_hash.status));
    });

    requestAsync.getParameter(path) ⇒ Promise.<ParameterMsg>

    Requests a parameter with full information and value from the server

    Kind: instance method of RequestAsync
    Returns: Promise.<ParameterMsg> - Returns a Promise, which resolves when parameter message is successfully obtained, fails otherwise.
    See: motorcortex.proto, ParameterMsg, StatusCode

    Param Type Description
    path string Parameter path in the tree.

    Example

    let param_reply = req.getParameter('root/Control/actualActuatorPositions');
    param_reply.then((param) => {
         console.log('Got parameter: ' + JSON.stringify(param));
    }).catch((param) => {
         console.log('Failed to get parameter: ' + motorcortex.statusToStr(param.status));
    });

    requestAsync.setParameter(path, value, [options]) ⇒ Promise.<StatusMsg>

    Sets new value to a parameter with given path.

    Kind: instance method of RequestAsync
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when parameter value is updated or fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    path string Parameter path in the tree.
    value any New parameter value.
    [options] Object Various options to parametrize Set operation. For example 'offset' and 'length' could be used to set an element offset and number of the elements to update in the destination array.

    Example

    // updates a value of a simple parameter
    let reply_handle = req.setParameter('root/Motorcontroller/actualmode', 2);
    reply_handle.catch((reply) => {
         console.log('Failed to set parameter: ' + motorcortex.statusToStr(reply.status));
    });
    
    // updates an array
    req.setParameter('root/Control/dummyDoubleArray6', [1.1,1.2,1.3,1.4,1.5,1.6]);
    // updates single element of array with the offset 2 (index 3)
    req.setParameter('root/Control/dummyDoubleArray6', 1.0, {offset: 2});
    // updates 2 elements of the arrays with the offset 4
    req.setParameter('root/Control/dummyDoubleArray6', [10.0, 20.0], {offset: 4, length: 2});

    requestAsync.overwriteParameter(path, value, force_activate, [options]) ⇒ Promise.<StatusMsg>

    Overwrites actual value of the parameter and depending on the flag forces this value to stay active. This method of setting values is useful during debug and installation process, it is not recommended to use this method during normal operation.

    Kind: instance method of RequestAsync
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when parameter value is updated or fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Default Description
    path string Parameter path in the tree.
    value any New parameter value.
    force_activate boolean false Forces new value to stay active. By default is set to 'false'.
    [options] Object Various options to parametrize Set operation. For example 'offset' and 'length' could be used to set an element offset and number of the elements to update in the destination array.

    Example

    // overwrite and force to stay active a value of a simple parameter
    let reply_handle = req.overwriteParameter('root/Motorcontroller/actualmode', 2, true);
    reply_handle.catch((reply) => {
         console.log('Failed to set parameter: ' + motorcortex.statusToStr(reply.status));
    });
    
    // overwrite and force to stay active an array
    req.overwriteParameter('root/Control/dummyDoubleArray6', [1.1,1.2,1.3,1.4,1.5,1.6], true);
    // overwrite and release force of a single element of the array with an offset 2 (index 3)
    req.overwriteParameter('root/Control/dummyDoubleArray6', 1.0, {offset: 2});
    // overwrite and force to stay active 2 elements of the arrays with an offset 4
    req.overwriteParameter('root/Control/dummyDoubleArray6', [10.0, 20.0], {offset: 4, length: 2});

    requestAsync.releaseParameter(path) ⇒ Promise.<StatusMsg>

    Deactivate overwrite operation of the parameter.

    Kind: instance method of RequestAsync
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when parameter overwrite is deactivated or fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    path string Path to a parameter in the tree.

    Example

    let reply_handle = releaseParameter('root/Motorcontroller/actualmode');
    reply_handle.catch((reply) => {
         console.log('Failed to release overwrite of the parameter: ' + motorcortex.statusToStr(reply.status));
    });

    requestAsync.setParameterList(param_list) ⇒ Promise.<StatusMsg>

    Sets new values to a parameter list.

    Kind: instance method of RequestAsync
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when parameters from the list are updated, otherwise fails.
    See: setParameter, motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    param_list Array.<{path, value, options}> A list of the parameters to update values.

    Example

    let reply_handle = req.setParameterList([{path: 'root/Motorcontroller/actualmode', value: 2},
         {path: 'root/Control/dummyDoubleArray6', value: [1.1,1.2,1.3,1.4,1.5,1.6]},
         {path: 'root/Control/dummyDoubleArray6', value: [10.0, 20.0], options:  {offset: 4, length: 2}}]);
    reply_handle.catch((reply) => {
         console.log('Failed to set list of parameter: ' + motorcortex.statusToStr(reply.status));
    });

    requestAsync.getParameterList(path_list, timeout_ms) ⇒ Promise.<StatusMsg>

    Get info and values of requested parameters.

    Kind: instance method of RequestAsync
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when list of the parameter values is received, otherwise fails.
    See: getParameter, motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    path_list Array.<string> List of parameter paths.
    timeout_ms number Reply timeout in milliseconds.

    Example

    let reply_handle = req.getParameterList(['root/Motorcontroller/actualmode, 'root/Control/dummyDoubleArray6']);
    reply_handle.then((param_list) => {
         console.log('Got parameter list: ' + JSON.stringify(param_list));
    }).catch((param_list) => {
         console.log('Failed to get parameter list: ' + motorcortex.statusToStr(param_list.status));
    });

    requestAsync.save(file_name) ⇒ Promise.<StatusMsg>

    Request a server to save a parameter tree in the file.

    Kind: instance method of RequestAsync
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when save operation is completed, fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    file_name string A file name where to save actual state of the parameter tree

    Example

    let reply = req.save('controls.xml');
    reply.catch((save) => {
         console.log('Failed to save parameters:' + motorcortex.statusToStr(save.status));
    });

    requestAsync.encode(msg) ⇒ Uint8Array

    Encodes a data type from MessageTypes to a binary wire type.

    Kind: instance method of RequestAsync
    Returns: Uint8Array - msg A binary array with encoded message.

    Param Type Description
    msg Object A message created by MotorcortexTypes.

    Example

    let motion_script = motorcortex_types.createType('motion_spec.MotionScript', {.id = 1, name = 'Test script'});
    motion_script.script = `print('Hello world');`;
    let encoded_msg = req.encode(motion_script);
    req.send(encoded_msg);

    requestAsync.send(encoded_msg, timeout_ms) ⇒ Promise.<Object>

    Sends an encoded request to the server

    Kind: instance method of RequestAsync
    Returns: Promise.<Object> - Returns a Promise, which completes when reply from the server is received. If request fails, catch callback is triggered.

    Param Type Description
    encoded_msg Uint8Array A binary array with encoded message.
    timeout_ms integer Timeout in milliseconds.

    Example

    let joint2cart = calcJointToCart({
         cartpose: [0, 0, 0, 0, 0, 0],
         jointpose: [0, 0, 1.57, 0, 1.57, 0] });
    let reply = req.send(req.encode(joint2cart));
    reply.then((msg) => {
         console.log('Got reply: ' + JSON.stringify(msg));
    }).catch((msg) => {
         console.error('Failed: ' + JSON.stringify(msg));
    });

    requestAsync.sendMsg(msg) ⇒ Promise.<Object>

    Encodes and sends a request to the server

    Kind: instance method of RequestAsync
    Returns: Promise.<Object> - Returns a Promise, which completes when reply from the server is received.

    Param Type Description
    msg Object A message created by MotorcortexTypes.

    Example

    let motion_script = motorcortex_types.createType('motion_spec.MotionScript', {.id = 1, name = 'Test script'});
    motion_script.script = `print('Hello world');`;
    let reply = req.encodeAndSend(motion_script);
    reply.then((msg) => {
         console.log('Got reply: ' + JSON.stringify(msg));
    }).catch((msg) => {
         console.error('Failed: ' + JSON.stringify(msg));
    });

    requestAsync.load(file_name) ⇒ Promise.<StatusMsg>

    Request a server to load value from the file to the parameter tree.

    Kind: instance method of RequestAsync
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when load operation is complete, fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    file_name string A file name from which to load values to the parameter tree.

    Example

    let reply = req.load('controls.xml');
    reply.catch((load) => {
         console.log('Failed to load parameters:' + motorcortex.statusToStr(load.status));
    });

    ConnectionData

    Container for the session parameters

    Kind: global class

    new ConnectionData(host, req_port, sub_port, security, request_timeout_ms, tree_timeout_ms, token_update_interval_ms, queue_length)

    Creates connection data object

    Param Type Description
    host string Motorcortex server URL.
    req_port number Request port.
    sub_port number Subscribe port.
    security boolean Use secured communication.
    request_timeout_ms number Request timeout in milliseconds..
    tree_timeout_ms number Request Parameter Tree timeout in milliseconds.
    token_update_interval_ms number Toke update interval in milliseconds.
    queue_length number Maximum size of the request queue.

    connectionData.getRequestUri()

    Returns request URI, for example wss://192.168.2.200:5568

    Kind: instance method of ConnectionData

    connectionData.getSubscribeUri()

    Returns subscribe URI, for example wss://192.168.2.200:5567

    Kind: instance method of ConnectionData

    connectionData.getRequestTimeoutMs()

    Returns request timeout in milliseconds.

    Kind: instance method of ConnectionData

    connectionData.getTreeTimeoutMs()

    Returns parameter tree request timeout in milliseconds.

    Kind: instance method of ConnectionData

    connectionData.getTokenUpdateIntervalMs()

    Returns how often session toke is updated.

    Kind: instance method of ConnectionData

    connectionData.getQueueLength()

    Returns maximum length of the request queue.

    Kind: instance method of ConnectionData

    SessionManager

    SessionManager manages a communication session for Request and Subscribe. SessionManager monitors if the connection is alive and tries to recover if the connection is lost.

    Kind: global class

    sessionManager.open(connection_data, login_data, options) ⇒ Promise.<string>

    Opens new session.

    Kind: instance method of SessionManager
    Returns: Promise.<string> - A promise, which completes when connection is ready. If connection fails, a short error description is passed to the catch method.

    Param Type Description
    connection_data ConnectionData Motorcortex server URL and all necessary connection parameters.
    login_data Object Login and password to access Motorcortex server.
    options Object Extra option for future use.

    Example

    let motorcortex_types = new motorcortex.MessageTypes();
    let req = new motorcortex.RequestAsync(motorcortex_types);
    let sub = new motorcortex.Subscribe(req);
    let session = new motorcortex.SessionManager(req, sub);
    let open_handle = session.open({
          host: '192.168.2.100',
          security: true,
          request_port: 5568,
          subscribe_port: 5567,
          timeout_ms: 1000,
          queue_length: 1000
      }, {
          login: 'test',
          password: 'test'
      });
    open_handle.then({
          console.log('connection ready');
      }).catch(e => {
          console.log('connection failed:' + e.text);
      });

    sessionManager.close()

    Closes connection to the server

    Kind: instance method of SessionManager

    sessionManager.ready() ⇒ boolean

    Checks if connection is ready

    Kind: instance method of SessionManager
    Returns: boolean - Returns True if connection is ready.

    sessionManager.hasError() ⇒ boolean

    Checks if there are connection errors

    Kind: instance method of SessionManager
    Returns: boolean - Returns True if connection is in the error state.

    sessionManager.isConnecting() ⇒ boolean

    Checks if there establishing connection is in progress

    Kind: instance method of SessionManager
    Returns: boolean - Returns True if establishing connection is in progress.

    sessionManager.notify(observer) ⇒ number

    Register an observer, which is notified after communcation state is changed.

    Kind: instance method of SessionManager
    Returns: number - id Unique identifier of the registered observer.

    Param Type Description
    observer Object A callback function, which is called after state is changed.

    Example

    let motorcortex_types = new motorcortex.MessageTypes();
    let req = new motorcortex.RequestAsync(motorcortex_types);
    let sub = new motorcortex.Subscribe(req);
    let session = new motorcortex.SessionManager(req, sub);
    session.notify(data => {
      if (session.hasError()) {
          console.error('Session error: ' + motorcortex.SessionState.getInfo(data.state));
      } else {
          console.log('Session state: ' + motorcortex.SessionState.getInfo(data.state));
          if (session.ready()) {
              let tree = parameter_manager.getTree();
              console.log(tree);
        }
      }

    sessionManager.remove(id)

    Removes an observer from the notify list.

    Kind: instance method of SessionManager

    Param Type Description
    id number Unique identifier of the registered observer.

    Example

    let id = session.notify(data => {});
    session.remove(id);

    sessionManager.getState(id) ⇒ SessionState

    Returns an active state of the communication session.

    Kind: instance method of SessionManager
    Returns: SessionState - Session state description

    Param Type Description
    id number Unique identifier of the registered observer.

    Example

    if (motorcortex.session.getState() == SessionState.OK) {
      // session is connected
    }

    Parameter

    Parameter value with a timestamp

    Kind: global class

    parameter.get() ⇒ Object

    Gets a parameter timestamp and a value

    Kind: instance method of Parameter
    Returns: Object - Returns an object with parameter timestamp and value.
    See: motorcortex.proto DataType
    Example

    // Reads latest update from the subscription
    let parameters = subscription.read();
    // Iterates through all the parameters
    for (let parameter of parameters) {
         // Gets time and value
         let time_value_pair = parameter.get();
         console.log('Parameter timestamp: ' + time_value_pair.timestamp + ' value: ', time_value_pair.value);
    }

    parameter.getTimestamp() ⇒ Timestamp

    Gets parameter timestamp

    Kind: instance method of Parameter
    Returns: Timestamp - Returns parameter timestamp.
    Example

    // Reads latest update from the subscription
    let parameters = subscription.read();
    // Iterates through all the parameters
    for (let parameter of parameters) {
         // Gets time
         console.log('Parameter timestamp: ' + parameter.getTimestamp());
    }

    parameter.getValue() ⇒ DataType

    Gets parameter value

    Kind: instance method of Parameter
    Returns: DataType - Returns parameter value.
    See: motorcortex.proto DataType
    Example

    Reads latest update from the subscription
    let parameters = subscription.read();
    // Iterates through all the parameters
    for (let parameter of parameters) {
         // Gets value
         console.log('Parameter value: ', parameter.getValue());
    }

    parameter.toString() ⇒ string

    Gets parameter as a string

    Kind: instance method of Parameter
    Returns: string - String formatted as 'timestamp: parameter'.
    Example

    Reads latest update from the subscription
    let parameters = subscription.read();
    // Iterates through all the parameters
    for (let parameter of parameters) {
         // Gets value
         console.log('Parameter value: ', parameter.toString());
    }

    Subscription

    Subscription class represents an active subscription group. It returns latest values and timestamps of the group parameters. Subscription class could be used as an observer, which notifies on every update or could be used as polling.

    Kind: global class

    subscription.id() ⇒ number

    Returns subscription identifier

    Kind: instance method of Subscription

    subscription.alias() ⇒ string

    Return group alias

    Kind: instance method of Subscription

    subscription.then(subscription_complete) ⇒ Promise.<GroupStatusMsg>

    Returns a Promise which is resolved when subscription request is complete.

    Kind: instance method of Subscription
    See: motorcortex.proto GroupStatusMsg

    Param Type Description
    subscription_complete SubscriptionClb A callback which is resolved when subscription is complete.

    Example

    let data_sub = sub.subscribe(["root/Control/jointReferenceGenerator/enable",
         "root/Control/jointReferenceGenerator/signalGenerator01/amplitude",
         "root/Control/jointReferenceGenerator/signalGenerator02/amplitude"], "group1");
    
    data_sub.then((subscription) => {
         console.log("Subscribed: " + subscription);
    }).catch((subscription) => {
         console.log("Subscription failed: " + motorcortex.statusToStr(subscription.status));
    });

    subscription.catch(subscription_failed) ⇒ Promise.<GroupStatusMsg>

    Returns a Promise which is resolved when subscription request fails.

    Kind: instance method of Subscription
    See: motorcortex.proto GroupStatusMsg

    Param Type Description
    subscription_failed SubscriptionClb A callback which is resolved when subscription fails.

    Example

    let data_sub = sub.subscribe(["root/Control/jointReferenceGenerator/enable",
         "root/Control/jointReferenceGenerator/signalGenerator01/amplitude",
         "root/Control/jointReferenceGenerator/signalGenerator02/amplitude"], "group1");
    
    data_sub.then((subscription) => {
         console.log("Subscribed: " + subscription);
    }).catch((subscription) => {
         console.log("Subscription failed: " + motorcortex.statusToStr(subscription.status));
    });

    subscription.read() ⇒ Array.<Parameter>

    Reads the latest values of the parameters in the group

    Kind: instance method of Subscription
    Returns: Array.<Parameter> - Returns a list of parameters.

    subscription.layout() ⇒ Array.<string>

    Gets a layout of the group.

    Kind: instance method of Subscription
    Returns: Array.<string> - Returns ordered list of the parameters in the group.
    Example

    let data_sub = sub.subscribe(["root/Control/jointReferenceGenerator/enable",
         "root/Control/jointReferenceGenerator/signalGenerator01/amplitude",
         "root/Control/jointReferenceGenerator/signalGenerator02/amplitude"], "group1");
    
    data_sub.then((subscription) => {
         let group_layout = data_sub.layout();
         console.log("Subscribed for: " + group_layout.toString());
    });

    subscription.notify(observer)

    Sets an observer, which is notified on every group update.

    Kind: instance method of Subscription

    Param Type Description
    observer SubscriptionUpdateClb A callback to notify when new values are available.

    Example

    let data_sub = sub.subscribe(["root/Control/jointReferenceGenerator/enable",
         "root/Control/jointReferenceGenerator/signalGenerator01/amplitude",
         "root/Control/jointReferenceGenerator/signalGenerator02/amplitude"], "group1");
    
    data_sub.then((subscription) {
         data_sub.notify((parameters) => {
             console.log('Received group update');
             let layout = data_sub.layout();
             for(let i = 0; i < layout.length; i++) {
                 console.log("Parameter: " + layout[i] + " value: " + parameters[i].toString());
             }
         }
    });

    Subscribe

    Subscribe class is used to receive continuous parameter updates from motorcortex server. Subscribe class simplifies creating and removing subscription groups.

    Kind: global class

    new exports.Subscribe(request)

    Creates subscribe

    Param Type Description
    request Request A reference to the request object.

    subscribe.connectionState() ⇒ number

    Actual Publish/Subscribe connection state.

    Kind: instance method of Subscribe
    Returns: number - Returns a connection state.
    Example

    CONNECTING   0    The connection is not yet open
    OPEN         1    The connection is open and ready to communicate
    CLOSING      2    The connection is in the process of closing
    CLOSED       3    The connection is closed or could not be opened

    subscribe.connect(url) ⇒ Promise.<string>

    Opens a subscribe connection.

    Kind: instance method of Subscribe
    Returns: Promise.<string> - A promise, which completes when connection is ready. If connection is failed, short error description is passed to the cathe method.

    Param Type Description
    url string Motorcortex server URL.

    Example

    let sub = new motorcortex.Subscribe(req);
    let sub_conn_done = sub.connect(`ws://${server}:5557`);
    sub_conn_done.then(() => {
         console.log('Subscribe connection is established');
    })
    .catch((reason) => {
         console.error('Failed to establish connection: ' + reason);
    });

    subscribe.close()

    Closes connection to the server

    Kind: instance method of Subscribe

    subscribe.subscribe(path_list, group_alias, [frq_divider]) ⇒ Subscription.<GroupStatusMsg>

    Create a subscription group for a list of the parameters.

    Kind: instance method of Subscribe
    Returns: Subscription.<GroupStatusMsg> - Returns a subscription handle, which acts as a JavaScript Promise, it is resolved when subscription is ready or failed. After the subscription is ready the handle is used to retrieve latest data.
    See: Subscription, motorcortex.proto, GroupStatusMsg, StatusCode

    Param Type Description
    path_list Array.<string> List of the parameters to subscribe to.
    group_alias string Name of the group.
    [frq_divider] number Frequency divider is a downscaling factor of the group publish rate. Default value is 1, every cycle of the publisher.

    Example

    let data_sub = sub.subscribe(["root/Control/jointReferenceGenerator/enable",
         "root/Control/jointReferenceGenerator/signalGenerator01/amplitude",
         "root/Control/jointReferenceGenerator/signalGenerator02/amplitude"], "group1");
    
    data_sub.then((subscription) => {
         console.log('Subscription is ready');
         // when subscription is ready, setting an update callback
         data_sub.notify((parameters) {
             console.log('Received group update');
             let layout = data_sub.layout();
             for(let i = 0; i < layout.length; i++) {
                 console.log("Parameter: " + layout[i] + " value: " + parameters[i].toString());
             }
         }
    }).catch((subscription) => {
         console.log('Failed to subscribe: ' + motorcortex.statusToStr(group.status));
    });

    subscribe.unsubscribe(group_alias) ⇒ Promise.<StatusMsg>

    Unsubscribe from the group.

    Kind: instance method of Subscribe
    Returns: Promise.<StatusMsg> - Returns a Promise, which resolves when the unsubscribe operation is complete, fails otherwise.
    See: motorcortex.proto, StatusMsg, StatusCode

    Param Type Description
    group_alias string Name of the group to unsubscribe from.

    Example

    let unsub_handle = req.unsubscribe('myGroup1');
    unsub_handle.catch((unsubscribe) => {
         console.log('Failed to remove group: ' + motorcortex.statusToStr(unsubscribe.status));
    });

    SessionState

    Enumerator of possible session states

    Kind: global constant

    SessionState.getInfo(state) ⇒ string

    Converts session state to the text

    Kind: static method of SessionState
    Returns: string - Text description of the session state.

    Param Type Description
    state number Id of the session state.

    Example

    console.log('Session state: ' + motorcortex.SessionState.getInfo(motorcortex.SessionState.CONNECTION_FAILED));

    SubscriptionClb : function

    This callback is resolved when subscription is ready or failed.

    Kind: global typedef

    Param Type Description
    status GroupStatusMsg A status and layout of the subscribe request.

    SubscriptionUpdateClb : function

    This callback notifies when subscription is updated with new values.

    Kind: global typedef

    Param Type Description
    parameters Array.<Parameter> A list of values and timestamps, ordered according to the group layout.