This the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Introduction

A introduction to Motorcortex

Motorcortex is a collection of libraries and tools to build Industry 4.0 Hard-Real-Time Control Systems. Motorcortex has extremely fast, open and secure communication built-in that is also natively supported by web-browsers. Building multi-threaded hard-realtime control applications is very easy, becasue all the hard stuff is taken care off, you just need to focus on your logic and control structure.

Motorcortex provides Open Source Client Libraries allowing all kinds of Applications built on top of a Control System, such as super-smooth visualization or user interfaces in the browser, data logging and analysis tools in Python or integrate a Motorcortex system with other frameworks like ROS. The modern communication is super fast and super scalable allowing connections to hundreds of clients simultaneously.

On this website you will find the documentation to learn working with Motorcortex. For new users it is recommended to start with the Geting started section. In this section you will learn the basics of interacting with Motorcortex.

motorcortex.io is the Motorcortex portal where you can Build, Deploy, Control and Analyze your control systems. In Motorcortex.io Tools you will find all the information and tutorials needed to get started using motorcortex.io.

Client applications are non-realtime applications but support multiple languages like Python C++ and Java Script. In Developing Client Applications you will find all the information and tutorials needed to get started creating Client application in Motorcortex.

Control applications are realtime application running on the controller generally containing control loops and state machines. In Developing Control Applications you will find all the information and tutorials needed to get started creating Control application in Motorcortex.

1 - Getting Started

This is where you learn the basics working with Motorcortex.

In This Getting started you will learn you the basics to get started with Motorcortex. These basics consist of 5 steps to Install, Connect, Deploy, Configure and Play with your Motorcortex application. There are a couple of different ways to get started and using Motorcortex.

1. Install/Update

To start off you will install or update a fresh image to your Controller.

In short, the following steps need to be performed:

  1. Download the latest MCX-OS Image from the motorcortex Store
  2. Create a bootable MCX-Imager USB-Stick with the MCX-Imager Tools
  3. Copy the MCX-OS Image onto your MCX-Imager USB-Stick
  4. Boot your controller from the MCX-Imager USB-Stick and restore the MCX-OS Image to your controller.

Depending on the type of hardware the update procedure is slightly different. Currently, there are 4 different Controller options to choose from:

GCC Industrial PC Raspberry PI Virtual Machine
Download MCX-OS Download MCX-OS Download MCX-OS Download MCX-OS
Install using MCX-Imager Install using MCX-Imager Install on Memory Card Convert the image to a Virtual Machine

2. Connect your PC

If a Motorcortex Image is installed you have to setup the connection between your PC and your Controller. connecting to Motorcortex is different for every Operating system on your PC there is a manual for Linux, Windows and MacOS.

Linux
Windows
MacOS
Configure Your Network (For Linux) Configure Your Network (For Windows) Configure Your Network (For MacOS)
Install a Browser Certificate (For Linux) Install a Browser Certificate (For Windows) Install a Browser Certificate (For MacOS)
Remote Access & File Transfer (For Linux) Remote Access & File Transfer (For Windows) Remote Access & File Transfer (For MacOS)

3. Deploy App

After a connection is established between your PC and your Controller it is time to deploy a application using motorcortex.io.

Deploy
Deploy App

4. Configure

Every piece of hardware has to be configured. Here we will use Motorcortex Ecat to configure your devices.

Configure
Configure Ethercat

5. Play

After completing the EtherCAT configuration we can start using Motorcortex to control our basic application.

Play
Use Motorcortex Desk
Create A GUI

These 5 steps are everything you need to get started using Motorcortex. If you want to learn how to create your own application you should take a look at Developing Client applications and Developing Control Applications.

More detailed information about the Motorcortex tools can be found in Motorcortex.io Tools.

1.1 - Install/Update

This section will show you how to install or update your Controller.

In this section you will go trough the installation process of a new Motorcortex image onto your Controller. To start off you will download the latest Motorcortex Image, after this you will follow the installation process for your designated Controller.

GCC Industrial PC Raspberry PI Virtual Machine
Download Image Download Image Download Image Download Image
Install Image On USB Install Image On USB Install Image On SD Card Install Image On Virtual Machine

1.1.1 - Download MCX-OS

This section will show you how to download a Motorcortex-OS image from Motorcortex.io.

Download an MCX-OS image

The MCX-OS Image is a complete Realtime System image that can be flashed onto your controller’s harddrive. Users of Motorcortex.io can download the correct image for their controller architecture by clicking the button below. If you don’t have a account yet make sure to request a trail.

The latest Motorcortex OS Image can always be found in the motorcortex.io Store. After the download is completed a .zip file should appear in your Download folder. Extract the .zip file to get access to your. .img.xz file.

The next step is to install the MCX-OS Image on your controller. Install an Image

1.1.2 - Install Image On Virtual Machine For Linux

This Section will show you how to a Image on your Virtual Machine for Linux.

There are a couple of different ways to install a image onto your Controller.

  • For a GCC or Industrial PC you will need to create a MCX Imager USB Stick.
  • For a Rasberry Pi you will need to create a MCX SD Card.
  • With a Virtual Machine you can Simulate a Motorcortex Controller.

Please choose what kind of Controller you will be using:

USB SD Card VirtualMachine

Getting a Virtual machine working is different for every Operating system. Please choose the Operating system you are working from below:

Linux Windows MacOS

A vitrual machine can be used to try out Motorcortex on your PC. Using a virtual machine you will need a .img file or a .vdi file. and VirtualBox installed on your machine. this chapter will show how to install VirtualBox and get your virtual machine up and going.

Installing VirtualBox For Linux

To get VirtualBox you wil have to download it from the https://www.virtualbox.org/wiki/Downloads website. choose the operating system you are using. and download the .deb file.

  1. Double click the .deb file.

  2. Click install in the pop-up. VirtualBox will now be installed.

Converting image

to use virtual box you will need a .vdi file. If you have a .img or compressed .img.xz you will need to convert these files using the following commands.

to uncompress a .img.xz file run the following command in the folder the file is located.

    unxz -k -v yourfile.xz

the compressed image will now be uncompressed. after this you can convert the .img file to a .vdi file. make sure you are in the correct folder where the file is located.

    VBoxManage convertfromraw yourfile.img yourfile.vdi		

Setting up the virtal machine

Setting up the virtual machine has to be done using the folowing steps:

  1. Open VirtualBox and click on New.

  1. In the Create Virtual Machine pop-up the following settings have to be selected.
  • Name: desired name
  • Machine Folder: desired folder
  • Type: Linux
  • Version: Linux 2.6/3.x/4.x(64-bit)

  1. Click Next.

  2. Set the memory size to 8000 MB and click Next.

  1. select the Use an existing virtual hard disk file and click on the folder icon.

  1. Click the Add icon and browse to the desired .vdi file.

  1. Click Choose.

  1. Click Create.

A virtual machine is created. Now the Network has to be configured.

  1. Click File and go to Host Network Manager.

  1. In the Host Network Manager fill in the settings as following:
  • Disable the DHCP Server by unchecking the box
  • IPv4 Address: 192.168.2.1
  • Network Mask: 255.255.255.0

  1. Close the Host Network Manager.

The network manager is now configured. Now the system settings have to be checked.

  1. click on settings.

  1. In System under the Motherboard tab make sure the Enable EFI box is checked.

  1. In System under the Motherboard tab make sure that Processor(s) is set to 4 CPU’s.

  1. In Network under the Adapter1 tab set Attached to to Host-only Adapter.

  1. Click OK

The virtual machine has now been set up.

Using virtual machine

Starting your virtual machine has to be done using the folowing steps:

  1. In virtual box select the desired virtual machine and press Start.

  1. The virtual machine will boot now this can take up to 5 seconds or longer.

  1. Log in to the controller.
  • Login: Admin
  • Password: vectioneer

the command line should change like this.

    mcx-intel:~$

If no hardware is connected to the virtual machine make sure the simulation mode is activated. how to activate simulation mode is described in Sumulation Mode

1.1.3 - Install an Image for MacOS

This Section will show you how to install a Image using a USB Drive

There are a couple of different ways to install a image onto your Controller.

  • For a GCC or Industrial PC you will need to create a MCX Imager USB Stick.
  • For a Rasberry Pi you will need to create a MCX SD Card.
  • With a Virtual Machine you can Simulate a Motorcortex Controller.

Please choose what kind of Controller you will be using:

USB SD Card Virtual Machine

To install a MCX-OS a MCX-Imager stick has to be made, for this you will need a USB Drive. Creating a MCX-Imager Stick is different for every OS. Please select the OS that you are using.

Linux Windows MacOS

The MCX-Imager Stick is a bootable USB drive that can be used to create backups and restore images of Motorcortex Systems.

1.1.4 - Install an Image for Windows

This Section will show you how to install a Image using a USB Drive

There are a couple of different ways to install a image onto your Controller.

  • For a GCC or Industrial PC you will need to create a MCX Imager USB Stick.
  • For a Rasberry Pi you will need to create a MCX SD Card.
  • With a Virtual Machine you can Simulate a Motorcortex Controller.

Please choose what kind of Controller you will be using:

USB SD Card Virtual Machine

To install a MCX-OS a MCX-Imager stick has to be made, for this you will need a USB Drive. Creating a MCX-Imager Stick is different for every OS. Please select the OS that you are using.

Linux Windows MacOS

The MCX-Imager Stick is a bootable USB drive that can be used to create backups and restore images of Motorcortex Systems.

Creating a Motorcortex-Imager USB Drive (For Windows)

Before we start you will need an USB Drive of at least 6Gb and at least 7Gb of free space on your PC.

  1. Motorcortex.io Users can download the latest MCX-Imager from the Shop by pressing the button below:

  2. Extract the .zip file, After extracting you should have a 6Gb .img file.

  3. Insert your USB Drive into your PC.

  4. Write the image to your USB Drive, When done, your USB Drive will be named ImageData, here you can put imager that you want to install onto a controller.

  5. Copy the MCX-OS Image .img.xz file into the ImageData folder.

Congratulations you have made your own MCX-Imager Stick. lets continue to install a image onto your controller.

Booting from the MCX-Imager Stick

  1. Make sure the controller is turned off.

  2. Insert the MCX-Imager Stick into your controller.

  3. Turn the controller on.

  4. Your machine should automatically boot from the Motorcortex-Imager USB Drive.

    There are 2 ways to Interact with the Imager stick:

    • By attaching a Keyboard and a Display to your controller. The screen should inmediatly show you a similar screen like below.

    • Or trough SSH connection on your laptop.

      1. Open a terminal.

      2. Connect to your Controller by typing:

        ssh tc@192.168.2.100
        
      3. log in with password vectioneer.

      4. The terminal should inmediatly show you a similar screen like below.

Congradulations you have booted from the MCX-Imager Stick. We can now Restore a MCX-OS image onto your Controller.

Restoring an image (Cold Start)

  1. To start the restore procedure type
sudo mcx-restore -f
  1. Now the prompt will ask you what image you would like to restore. Choose the image that you would like to restore.
  2. Second the prompt will ask you to choose the drive where you want to restore your image to.
  3. Restoring the image will take some time. When the process is done, check for any errors in the console
  1. You will get the message Done when the process is finished.

  1. Now you can reboot or poweroff.

     sudo poweroff`
    
  2. Wait for a couple seconds for the system to power off.

  3. Remove the USB Drive.

  4. Turn on your machine again.

  5. Congratulations you have installed MCX-OS onto your Machine. Next up we can start connecting to your controller.

1.1.5 - Install Image On a SD Card

This Section will show you how to omstall a Image on your SD Card.

There are a couple of different ways to install a image onto your Controller.

  • For a GCC or Industrial PC you will need to create a MCX Imager USB Stick.
  • For a Rasberry Pi you will need to create a MCX SD Card.
  • With a Virtual Machine you can Simulate a Motorcortex Controller.

Please choose what kind of Controller you will be using:

USB SD Card VirtualMachine

1.1.6 - Install Image On Virtual Machine For MacOS

This Section will show you how to a Image on your Virtual Machine for MacOS.

There are a couple of different ways to install a image onto your Controller.

  • For a GCC or Industrial PC you will need to create a MCX Imager USB Stick.
  • For a Rasberry Pi you will need to create a MCX SD Card.
  • With a Virtual Machine you can Simulate a Motorcortex Controller.

Please choose what kind of Controller you will be using:

USB SD Card VirtualMachine

Getting a Virtual machine working is different for every Operating system. Please choose the Operating system you are working from below:

Linux Windows MacOS

1.1.7 - Install Image On Virtual Machine For Windows

This Section will show you how to a Image on your Virtual Machine for Windows.

There are a couple of different ways to install a image onto your Controller.

  • For a GCC or Industrial PC you will need to create a MCX Imager USB Stick.
  • For a Rasberry Pi you will need to create a MCX SD Card.
  • With a Virtual Machine you can Simulate a Motorcortex Controller.

Please choose what kind of Controller you will be using:

USB SD Card VirtualMachine

Getting a Virtual machine working is different for every Operating system. Please choose the Operating system you are working from below:

Linux Windows MacOS

A vitrual machine can be used to try out Motorcortex on your PC. Using a virtual machine you will need a .img file or a .vdi file. and VirtualBox installed on your machine. this chapter will show how to install VirtualBox and get your virtual machine up and going.

Installing VirtualBox (For Windows)

To get VirtualBox you wil have to download it from the https://www.virtualbox.org/wiki/Downloads website. choose the operating system you are using. and download the .exe file.

  1. Double click the .exe file.

  2. The setup wizard will pop-up click next.

  1. Click Next unless you want to change the location for the VirtualBox.

  1. Click ‘Next’ unless you want to change some of the install options.

  1. A warning will tell you that network connections will be disconected temporarily. Click Yes.

  1. Click Install.

  1. The instalation will start. During the instalation a security warning will pop-up click Install.

  1. click Finish to complete the instalation.

Converting image

to use virtual box a .vdi file is needed. .img files or compressed .img.xz files have to be converted.

to uncompress a .img.xz file run the following command in the folder the file is located.

    unxz -k -v yourfile.xz

the compressed image will now be uncompressed. after this you can convert the .img file to a .vdi file. make sure you are in the correct folder where the file is located.

    VBoxManage convertfromraw yourfile.img yourfile.vdi		

Setting up virtal machine

Setting up the virtual machine has to be done using the folowing steps:

  1. Open VirtualBox and click on New.

  1. In the Create Virtual Machine pop-up the following settings have to be selected.
  • Name: desired name
  • Machine Folder: desired folder
  • Type: Linux
  • Version: Linux 2.6/3.x/4.x(64-bit)

  1. Click Next.

  2. Set the memory size to 8000 MB and click Next.

  1. select the Use an existing virtual hard disk file and click on the folder icon.

  1. Click the Add icon and browse to the desired .vdi file.

  1. Click Choose.

  1. Click Create.

A virtual machine is created. Now the Network has to be configured.

  1. Click File and go to Host Network Manager.

  1. In the Host Network Manager fill in the settings as following:
  • Disable the DHCP Server by unchecking the box
  • IPv4 Address: 192.168.2.1
  • Network Mask: 255.255.255.0

  1. Close the Host Network Manager.

The network manager is now configured. Now the system settings have to be checked.

  1. click on settings.

  1. In System under the Motherboard tab make sure the Enable EFI box is checked.

  1. In System under the Motherboard tab make sure that Processor(s) is set to 4 CPU’s.

  1. In Network under the Adapter1 tab set Attached to to Host-only Adapter.

  1. Click OK

The virtual machine has now been set up.

Using virtual machine

Starting your virtual machine has to be done using the folowing steps:

  1. In virtual box select the desired virtual machine and press Start.

  1. The virtual machine will boot now this can take up to 5 seconds or longer.

  1. Log in to the controller.
  • Login: Admin
  • Password: vectioneer

the command line should change like this.

    mcx-intel:~$

If no hardware is connected to the virtual machine make sure the simulation mode is activated. how to activate simulation mode is described in Sumulation Mode

1.1.8 - Install MCX-OS

This Section will show you how to install the MCX-OS Image using the MCX-Imager USB-Stick

There are a couple of different ways to install a MCX-OS image onto your Controller.

  • For a GCC or Industrial PC you will need to create a MCX-Imager USB-Stick, copy your new MCX-OS Image onto the Stick, boot your Controller from the stick and restore the image to the Controller’s harddrive.
  • For a Rasberry Pi you will need to transfer the appropriate MCX-OS Image to the Pi’s SD Card.
  • To use a Virtual Machine as your Controller, you need to convert the MCX-OS Image to a Virtual Box Image.

Please choose what kind of method you will use to install your Controller:

MCX-Imager USB-Stick SD Card Virtual Machine

To install a MCX-OS Image on your controller you will need to create an MCX-Imager USB-Stick. The MCX-Imager USB-Stick is a bootable USB drive that can be used to create backups and restore images of Motorcortex Systems.

You will need an empty USB Drive of at least 8 Gb. Creating a MCX-Imager USB-Stick is different for every OS. Please select the OS that you are using.

Linux Windows MacOS

Creating a MCX-Imager USB-Stick (For Linux)

Before we start you will need an USB Stick of at least 8Gb and at least 7Gb of free space on your PC.

  1. Motorcortex.io Users can download the latest MCX-Imager USB-Stick Image from the Shop by pressing the button below:

  2. Extract the .zip file, After extracting you should have a 6Gb .img file.

  3. Insert your empty USB Drive into your PC. Beware that we will erase everything that is already on your USB Stick.

  4. Right-click on the .img file and select Disk Image Writer.

  5. In the following window select the drive you want to write the MCX-Imager image file to and hit the Make Startup Disk button.

    When restoring of the image is complete, the system should automatically mount the ImageData partition of the USB-Stick.

Copying the MCX-OS Image to your MCX-Imager USB-Stick

  1. Copy the MCX-OS Image .img.xz file into the ImageData folder of you USB-Stick.

Booting your Controller from the MCX-Imager USB-Stick

  1. Make sure your Controller is turned off.

  2. Insert the MCX-Imager USB-Stick into your Controller.

  3. Turn the Controller on.

  4. Your Controller should automatically boot from the Motorcortex-Imager USB Drive. If it does not boot automatically from USB check your Controller’s BIOS settings to enable booting from USB.

  5. Log in to the MCX-Imager terminal

    There are 2 ways to access the terminal of the MCX-Imager:

    • By attaching a Keyboard and a Display to your Controller. The screen should immediatly show you a similar screen like below.

    • Or trough SSH connection on your laptop.

      1. Connect your controller with your pc using the Ethernet port (In the virtual machine this is already set-up).

      2. Make sure the ip address of your network adapter that is connected to the Controller is in the 192.168.2.xxx range (do not use 192.168.2.100)

      3. Open a terminal.

      4. Connect to your Controller by typing:

        ssh tc@192.168.2.100
        
      5. log in with password vectioneer.

      6. The terminal should inmediatly show you a similar screen like below.

Installing an MCX-OS image onto your Controller

  1. To start the restore procedure type
sudo mcx-restore -f
  1. Now the prompt will ask you what image you would like to restore. Choose the image that you would like to restore.
  2. Second the prompt will ask you to choose the drive where you want to restore your image to.
  3. Restoring the image will take some time. When the process is done, check for any errors in the console
  1. You will get the message Done when the process is finished.

  1. Remove the MCX-Imager Stick.

  2. Now you can reboot or poweroff.

    sudo reboot
  1. Wait for a couple seconds for the system to restart.
  2. Congratulations you have installed MCX-OS onto your Controller!

The next step is to set-up the connection between your controller and your laptop. Connect Your PC

1.2 - Connect your PC

This section will show you how to connect to a Motorcortex machine.

After installing a Motorcortex image onto your Controller, its time to establish a connection with your laptop. During this step you are going to configure your network, install a browser certificate and learn how to get remote access to your Controller.

Linux
Windows
MacOS
Configure Your Network (For Linux) Configure Your Network (For Windows) Configure Your Network (For MacOS)
Install a Browser Certificate (For Linux) Install a Browser Certificate (For Windows) Install a Browser Certificate (For MacOS)
Remote Access & File Transfer (For Linux) Remote Access & File Transfer (For Windows) Remote Access & File Transfer (For MacOS)

1.2.1 - Configure Your Network

Setting up the connection between your PC and Motorcortex.

To be able to connect to a Motorcortex Controller, Your computer should be connected to the local network of the Motorcortex Controller. It is important that the user sets a fixed IP address to the Client computer. This chapter will explain how to set a fixed IP address. Before we start please select your operating system:

Linux Windows MacOS

Setting up your connection.

After your PC has booted and you have logged in it’s time to go trough the following steps:

  1. Go to System Settings.
  2. In System Settings go to the Network tab.
  3. Under Wired go to Wired Setings by clicking the cogwheel ⚙️ icon.

  1. In Wired Settings go to the IP4 tab.
  2. Set IPv4 Method to Manual.
  3. Fill in Addresses for the Address: 192.168.2.XYZ, where XYZ is not equal to the controller ip and smaller than 255. (Motorcortex Controller default IP address is 192.168.2.100).
  4. Fill in Addresses for the Netmask: 255.255.255.0.

Test your connection

After configuring your connection it is time to check if your connection is working

  1. Connect your controller with your pc using the Ethernet port (In the virtual machine this is already set-up).

  2. . Check if your connection is established by using the following command in the terminal.

     ping 192.168.2.100
    
  3. Hit Ctrl C to stop pinging.

The the terminal should look like this. If this is not the case please make sure you check out Connection Troubleshooting section that serves as a step by step guide.

  1. Congratulations you have established a connection!

The next step is to learn how to get remote access and transfer files between your pc and your controller. Remote Access & File Transfer

1.2.2 - Remote Access & File Transfer

Setting up remote access with Motorcortex and transfer file transfer from your PC.

In some cases it is needed to have remote access with your Controller. To get remote access to your Controller works different from every OS. Please select the OS that you are using:

Linux Windows MacOS

In this section we wil cover how to login to a Motorcortex Controller from a client using SSH (Secure SHell) to use command line tools of the Motorcortex controller or use SFTP (SSH File Transfer Protocol) to transfer files to and from the Motorcortex Linux system.

All of the Motorcortex configuration is stored on the Motorcortex controller in the folder /etc/Motorcortex/.

The files can be accessed from a computer that is connected to network connection of the controller and is configured to be on the same network. The Motorcortex controller has a SSH server installed that makes file transfer (through sftp) or remote login (ssh) possible.

Remote access to the Motorcortex Computer

The Motorcortex Controller has a ssh server installed which makes remote login (ssh) and transfer of files possible (sftp). It is possible to log into the Motorcortex Computer with a terminal. using the following default user accounts.

  1. Logging in to execute commands can be done directly by typing the following command in the terminal:
ssh admin@192.168.2.100

ssh [username]@[IP address], where [username] is the username (standard admin) and the [IP address] is the IP address is from the computer(standard 192.168.2.100).

  1. Continue by typing in yes.

  2. Fill in the controller password (the standard password is vectioneer).

Once you are logged-in you will see a command prompt like follows:

mcx-intel:\~\$ _

File transfer

The Motorcortex Controller has a ssh server installed which makes remote login (ssh) and transfer of files possible (sftp). Most Linux distributions come with native support for ssh and sftp, both as command-line or desktop tools.

  1. In the Ubuntu Linux File Manager click on Other Locations
  2. Fill in the url sftp://admin@192.168.2.100 under Connect to Server.(admin is the standard user)
  3. Click Connect

  1. Fill in the password to logon (standard password is vectioneer). The remote filesystem of the controller will now be mounted and files can be transferred back and forth.
  2. Congratulations you now know how to get remote access and transfer files to your controller!

The next step is to install a browser certificate for using Motorcortex.io tools. Install Browser Certificate

SSH Troubleshooting

Having trouble remote accessing to your controller? The following steps will help you solve these issues.

  1. Check if you are receiving the following message in the terminal while connecting trough ssh.

  1. Remove the old key using the following command copied from the error message.
  ssh-keygen -f "/home/user/.ssh/known_hosts" -R "192.168.2.100"

1.2.3 - Configure Your Network For Windows

Setting up the connection between your PC and Motorcortex.

To be able to connect to a Motorcortex Controller, Your computer should be connected to the local network of the Motorcortex Controller. It is important that the user sets a fixed IP address to the Client computer. This chapter will explain how to set a fixed IP address. Before we start please select your operating system:

Linux Windows MacOS

After your PC has booted and you have logged in it’s time to go trough the following steps:

  1. Press the Windows-key and type Ethernet Settings.
  2. In the Ethernet tab click Change connection properties.

  1. Right-click on your wired ethernet adapter (the one with a network cable in it) and select Properties.

  1. Click in the list on Internet Protocol Version 4 (TCP/IPv4).
  2. Click on Properties.

  1. Select Use the following IP address:.

  2. Fill for the IP Address:: 192.168.2.XYZ, where XYZ is not 100 and smaller than 255 (MOTORCORTEX Controller default IP address is 192.168.2.100).

  3. Fill for the Netmask:: 255.255.255.0.

  1. Click OK

  2. Nexst check if the connection works by open Windows command line (Windows-key and type cmd).

  3. In the command line type ping 192.168.2.100. This should give a response like below:

Note: In case the MOTORCORTEX Controller is configured for a different network, the settings may have to be adapted.

1.2.4 - Configure Your Network For MacOS

Setting up the connection between your PC and Motorcortex.

To be able to connect to a Motorcortex Controller, Your computer should be connected to the local network of the Motorcortex Controller. It is important that the user sets a fixed IP address to the Client computer. This chapter will explain how to set a fixed IP address. Before we start please select your operating system:

Linux Windows MacOS

After your PC has booted and you have logged in it’s time to go trough the following steps:

1.2.5 - Install a Browser Certificate

A certificate is required to support a secure (encrypted) connection between your PC and Motorcortex.

Motorcortex uses a secure (encrypted) connection. This means that installing a certificate is required, installing a certificate is different for every OS. Please select the OS that you are using:

Linux Windows MacOS

When using Linux Browser certificates can be installed directly in your browser. Please select the browser that you are using:

Chrome Firefox

Install a Certificate for Chrome

Motorcortex applications are using Transport Layer Security (TLS) for end-to-end encryption of the communication channel between the server application and its clients. To be able to connect to your Motorcortex application you need to use a special certificate signed by Vectioneer.

Download a standard Motorcortex Encryption Certificate by clicking the download button below. The download should start automatically and should appear in your downloads folder.

After downloading the certificate it has to be installed. Installing this certificate is different for every Operating system. For Linux users it is only necessary to install Motorcortex Encryption Certificate. The following steps show how to install the Motorcortex Encryption Certificate.

  1. Open ⋮Settings menu in the top right corner of your Chrome browser.

  1. In the Settings go to the Privacy and Security tab expand with More and go to Manage certificates.

  1. In the Manage certificates tab go to the Authorities tab and click on the Import button.

  1. Browse to and open the mcx.cert.pem that you have downloaded.

  2. Next you will receive a pop-up check Trust this certificate for identifying websites and press OK.

  1. Check if the certificate is installed by checking the list of your certificates.

  2. Open a new tab in your browser and go to [Controller IP address]:8000, per default` 192.168.2.100:8000

  1. Fill in Server Address The IP address of the controller (Host), per default 192.168.2.100.

  2. Select secure connection by closing the lock icon 🔓/🔒.

  3. Fill in Login the admin as user.

  4. Use as password vectioneer.

  5. Click the Connect button. You should now be able to acces the Motorcotex Desk tool. If this is not te case make sure you take a look at Connection Troubleshooting.

  1. Congratulations you have installed a Motorcortex Certificate to your browser.

The next step is to Deploy a app to your controller using motorcortex.io. Deploy App

Install a Certificate for Firefox

Motorcortex applications are using Transport Layer Security (TLS) for end-to-end encryption of the communication channel between the server application and its clients. To be able to connect to your Motorcortex application you need to use a special certificate signed by Vectioneer.

Download a standard Motorcortex Encryption Certificate by clicking the download button below. The download should start automatically.

After downloading the certificate it has to be installed. Installing this certificate is different for every Operating system. For Linux users it is only necessary to install Motorcortex Encryption Certificate. The following steps show how to install the Motorcortex Encryption Certificate.

  1. Open Settings menu in the top right corner of the Firefox browser.

  1. In the Settings go to the Privacy and Security and scroll down to the Security section. now click Vieuw Certificates....

  1. In the Manage certificates pop-up go to the Authorities tab and click on the Import... button.

  1. Browse to and open the mcx.cert.pem that you have downloaded.

  2. Next you will receive a Downloading Certificate pop-up check Trust this CA to identify websites and press OK.

  1. Check if the certificate is installed by checking the list of your certificates.

  2. Open a new tab in your browser and go to [Controller IP address]:8000, per default 192.168.2.100:8000

  1. Fill in Server Address The IP address of the controller (Host), per default 192.168.2.100.
  2. Select secure connection by closing the lock icon 🔓/🔒.
  3. Fill in Login the admin as user.
  4. Use as password vectioneer.
  5. Click the Connect button. You should now be able to acces the Motorcotex Desk tool. If this is not te case make sure you take a look at Connection Troubleshooting.

  1. Click the Connect button. You should now be able to acces the Motorcotex Desk tool. If this is not te case make sure you take a look at Connection Troubleshooting.

  2. Congratulations you have installed a Motorcortex Certificate to your browser.

The next step is to Deploy a app to your controller using motorcortex.io. Deploy App

1.2.6 - Install a Browser Certificate For Windows

A certificate is required to support a secure (encrypted) connection between your PC and Motorcortex.

Motorcortex uses a secure (encrypted) connection. This means that installing a certificate is required, installing a certificate is different for every OS. Please select the OS that you are using:

Linux Windows MacOS

Install a Browser Certificate For Windows

Motorcortex applications are using Transport Layer Security (TLS) for end-to-end encryption of the communication channel between the server application and its clients. To be able to connect to your Motorcortex application you need to use a special certificate signed by Vectioneer.

Download a standard Motorcortex Encryption Certificate by clicking the download button below. The download should start automatically.

After downloading the certificate it has to be installed. Installing this certificate is different for every Operating system. For Windows users it is necessary to install VECTIONEER Root Certificate to the trusted root ceritifcate storage. The following steps will show how to install the certificates for windows.

  1. To do that double click on the downloaded vectioneer-ca.crt file.

  2. In the Certificate pop-up click Install Certificate.

  1. The Certificate Import Wizard will pop-up, select the store location where you want to install the certificate. and click Next.

  1. Now the certificate store has to be selected. select Place all certificates in the following store click Browse in the Select Certificate Store choose Trusted Root Certification Authoities and click OK.

  1. The Trusted Root Certification Authorities will show in the Certificate store: bar. click Next.

  1. Completing the certificate import wizard click Finish.

  1. Because a certificate will be installed to the Trusted root certification Authorities a warning will pop up. click Yes.

  1. The import was successful will show, click OK.

  1. Reboot Windows for the changes to take effect.

1.2.7 - Install a Browser Certificate For MacOS

A certificate is required to support a secure (encrypted) connection between your PC and Motorcortex.

Motorcortex uses a secure (encrypted) connection. This means that installing a certificate is required, installing a certificate is different for every OS. Please select the OS that you are using:

Linux Windows MacOS

1.2.8 - Remote Access & File Transfer

Setting up remote access with Motorcortex and transfer file transfer from your PC.

In some cases it is needed to have remote access with your Controller. To get remote access to your Controller works different from every OS. Please select the OS that you are using:

Linux Windows MacOS

Remote access to the Controller (Windows)

Here is explained how to login to a Motorcortex Controller from a client using SSH (Secure SHell) to use command line tools of the Motorcortex controller or use SFTP (SSH File Transfer Protocol) to transfer files to and from the Motorcortex Linux system.

All of the Motorcortex configuration is stored on the Motorcortex controller in the folder /etc/Motorcortex/.

The files can be accessed from a computer that is connected to network connection of the controller and is configured to be on the same network. The Motorcortex controller has a SSH server installed that makes file transfer (through sftp) or remote login (ssh) possible.

The Motorcortex Controller has a ssh server installed which makes remote login (ssh) and transfer of files possible (sftp). It is possible to log into the Motorcortex Computer with a terminal. using the following default user accounts.

Subsystem IP address Username Default Password Description
Motorcortex Contorller 192.168.2.100 (default) admin vectioneer Administrator account (all privileges)

Logging in to execute commands can be done directly by typing the following command in the cmd-line :

ssh admin@192.168.2.100

ssh [username]@[IP address], where [username] is the username and the [IP address] the IP address is from the computer. Values are listed in the table above. Once you are logged-in you will see a command prompt like follows:

mcx-intel:\~\$ _

The controller command line can also be accessed via a program like Putty (all operating systems: www.putty.org).

2.3.2 File transfer (windows)

On Windows the recommended tool is the FileZilla Client www.filezilla-project.org.

NOTE: for security reasons it is not possible to copy files directly into all system folders, only system folders that are needed for configuration of EtherCAT slaves are writable with the “admin” account.

1.2.9 - Remote Access & File Transfer For MacOS

Setting up remote access with Motorcortex and transfer file transfer from your PC.

In some cases it is needed to have remote access with your Controller. To get remote access to your Controller works different from every OS. Please select the OS that you are using:

Linux Windows MacOS

1.2.10 - Connection Troubleshooting

These are some steps that will help out if you can’t connect to Motorcortex.

If you are unable to connect to Motorcortex your motorcortex application please use the following steps to find and solve the problem.

  1. Try to ping the Motorcortex controller.

    ping 192.168.2.100
    
  2. Hit Ctrl C to stop pinging. If there are problems with your connection the terminal will look like this.

  1. Check your connections the possible problems could be:
  • Broken Ethernet cable
  • Broken Network adapter
  1. If your connections are good the check your network settings as explained in Configure Your Network.
  1. Check if a network is detected using the following command.

    ifconfig
    
  2. The terminal should show your connection similar as shown below.

If no connections are found there is a hardware problem that has to be resolved.

If connections are found it might be needed to reset the wired connection.

  1. Unplug your cable.

  2. Go to the following directory.

    cd /etc/NetworkManager/system-connections 
    
  3. Check your connections using.

    ls
    
  4. Remove the connection mostly starting with Wired connection.

    sudo rm Wired_connection_name
    
  5. Reconnect your cable.

  6. Retry following the steps in Configure Your Network.

  1. On your machine Turn Motorcortex off and on again by using the following steps.

  2. Log into the system through ssh as explained in Remote Access & File Transfer (For Linux).

  3. Run the following command:

    sudo /etc/init.d/motorcortex restart
    
  4. Retry Connecting to your Motorcortex application

  5. If this is still not working check if your Certificate is installed correctly as explained in Install a Browser Certificate.

  6. If the Certificate correctly installed check if your anti-virus software on your computer blocks the ports used by Motorcortex. There are known issue with the default settings of Kaspersky and other Security Apps.

  7. If that is not the case maybe you are behind a firewall. Try to connect your computer directly or change the firewall settings.

1.3 - Deploy App

This Page will show you how to Deploy packages to your Motorcortex Controller

After succesfully setting up a connection to your Controller running Motorcortex, it is time to start using Motorcortex.io. If you don’t have a Motorcortex.io account yet make sure to request a Free trail. The following steps explain how to deploy a Motorcortex application to your Controller:

Create a new project

  1. Login to Motorcortex.io.

  2. Create a 📄 new project.

  3. Fill in the title and version of your new project.

  1. Press the select a template button.
  2. Select the general category and select Motorcortex-Generic-App.
  3. Press the + create button. Your project will now be generated based on the Generic-App template.

Deploy all required Packages

Now that a project is generated you can deploy all of the packages inside the template to your controller.

Configuration package

The Configuration package Contains the configuration of your Motorcortex application. Here you will also find your EtherCAT Configuration. More about this you will find in motorcortex.io.

  1. Click on your Configuration-GCC Configuration Package to go inside the directory.

  1. Press Deploy in te Actions menu.

  1. Fill in the controller local IP adress the IP adress of your Controller (per default 192.168.2.100). And press the Deploy button.

Binary Package

In the Binary package you will find the .deb files for your controller these .deb files contain software blocks that you can use for your application. More about the structure of these packages are described in motorcortex.io. are you interested in creating one of these packages make sure to check out Developing Control Applications.

  1. Return to your Projectdirectory.

  2. Click on your Generic-App binary Package to go inside the directory.

  1. Press Deploy in te Actions menu.

  1. Fill in the controller local IP adress the IP adress of your Controller (per default 192.168.2.100). And press the Deploy button.

GUI Package

The GUI Package contains everything that you need for creating a GUI. More detail about a GUI Package can be found in motorcortex.io.

  1. Return to your Projectdirectory.

  2. Click on your User Interface binary Package to go inside the directory.

  1. Press Deploy in te Actions menu.

  1. Fill in the controller local IP adress the IP adress of your Controller (per default 192.168.2.100). And press the Deploy button.

Restarting The Application

For the installed packages to take effect the application has to be restarted. this can be done by using ssh, or by restarting the controller.

  1. Use ssh to connect to your controller as explained in Remote Access & File Transfer.

  2. When logged in use the following command sudo motorcortex restart

  3. Congratulations you have all your packages deployed.

The next step is to configure your EtherCAT devices. Configure

1.4 - Configure

This Page will show you how to Configure your EtherCAT devices.

After successfully Deploying a application it is time to configure your EtherCAT devices. In this section we will use a example to show how to configure your EtherCAT with the motorcortex Ecat Tool. For this example we have made use of a Beckhoff EP2316-0003 IO module.

With your EtherCAT device connected it is time to configure your Ethercat device(s) using the Motorcortex Ecat tool.

  1. Login to Motorcortex.io.

  2. Under tools press the Ecat button. This will open a new tab with the Motorcortex Ecat tool.

  3. Press fetch to fetch the current EtherCAT configuration file on the Controller.

  4. In the menu on the left Domains and Devices will show up that are pre-configgured. Users of the GCC will need to keep the GCC domain. all other domains have to be deleted.

  5. Next we will add a new domain by clicking the + button.

  6. In this new domain you have to add a new device by pressing the + button.

  7. Within the tool a new window will pop up. Press the Scan Bus button to scan for all Available Ethercat Devices.

  8. The fist 3 devices shown are GCC components. These are already configured so we can uncheck these. If we have checked the devices that we want to add we can push the Add Devices Button.

  9. Click on your device. This will show your device configuration.

  10. Every EtherCAT supplier should supply a ESI.xml file upload the ESI.xml in the Motorcortex Ecat thiss will fill in your PDO’s automatically.

  11. Press the deploy button to deploy your new configuration to your machine.

  12. Go back to your motorcortex.io project and under Create Package press the fetch config button.

  13. Fill in the IP of your controller. per default this is 192.168.2.100.

  14. Your configuration will be added to your project. Rename the configuration to keep track for later use.

  15. Congratulations you have configured your EtherCAT devices.

The next step is to Play with our Application. play

1.5 - Play

On this Page you will start creating a Motorcortex application.

After configuring EtherCAT we have everything we need to control our application. In this section we will start testing our EtherCAT devices using Motorcortex Desk.

The next step would be creating a GUI (Graphical User Interface) using Motorcortex Grid.

After creating a GUI we have all of the basics we need to create a Motorcortex application. To become a more advanced user u can check out Developing Client Applications or Developing Control Applications to start learning to create your own application.

1.5.1 - Use Motorcortex Desk

In this section we will control our application using Motorcortex Desk.

Motorcortex Desk is a visualisation based on the Parameter Tree. The Parameter Tree is the epicenter of controlling our appllication. Everything that is happening inside our application is shown and can be controlled in this Parameter Tree. In the following steps we are going to controll our application using Motorcortex Desk.

  1. To enter Motorcortex desk browse to your project and click on the Desk button.This will open a new tab with Motorcortex Desk.

  2. Fill in the server address per default this is 192.168.2.100.

  3. Close the lock button 🔒 to select a secure connection.

  4. Click the Connect button, per default a login an password is not needed.

Motorcortex desk visualised all parameters and works like a directory sytem. For the following example we have connected a switch and a light to our IO device to check our IO’s.

  1. In the left menu you can browse to the Ethercat folder. This folder contains all the parameters of our EtherCAT configuration. With these parameters we can control the configured our EtherCAT devices.

  2. In the Ethercat folder you will find parameters and the Domain folders that were configured in Motorcortex Ecat.

  3. In the Domain folder(s) you will find the Device folders that were configured in Motorcortex Ecat.

  4. In the Device folder(s) wil contain the parameters to control your device.

  1. Double click the parameters that you would like to manipulate or plot. these will be shown in the small menu below.

  2. Left of the parameters is a checkbox, clicking this checkbox will plot the signal. In our example we plotted both our Input and Output signals of our EtherCAT device.

  3. By pushing the button we see that the input signal is changing from 0 to 1.

  4. On the right of our output parameter we see a input field we can use this field to manipulate the value of our output. by filling in a value of 1 and hitting enter the output value is set to high and the light wil light up.

  1. Congradualtions you have now controlled your own Motorcortex application.

The next step is to create your own Motorcortex Graphical User Interface. Create a GUI

More information about the Motorcortex Desk tool can be found under Motorcortex Desk

1.5.2 - Create a GUI

In this section we will create a Motorcortex Graphical User Interface

After controlling our application we can start to create a GUI for our application. The following steps will show you how to create your own Motorcortex GUI.

  1. Go to your project folder in Motorcortex.io.

  2. Go into your User Interface directory.

  3. Create a new Grid file by pressing the grid file button in the right tab and give it a name.

  4. Double Click the .grid file you made to open Motorcortex Grid.

  5. In Grid press the Connect button on the right upperhand side.

  6. Fill in the controller IP (Per default this is 192.168.2.100)

  7. Check the secure connection checkbox.

  8. Hit the connect button to connect to your controller.

  9. On the top left you will find the library button. Hit this button to expand the Library.

  10. For our Example we will add a switch to connect to our lamp and a light to connect to our push button.

  11. Drag the elements to your desired location in the grid.

  12. Select the switch element. The right tab will now show the element properties of this switch.

  13. Under PATHclick the path input box. This will open the Parameter Tree on the left tab.

  14. In the Parameter tree browse to Ethercat/yourdomain/yourdevice and click the Output that has the lamp connected to it. this will add the path to your element.

  15. Select the light element. The right tab will now show the element properties of this light.

  16. Under PATHclick the path input box. This will open the Parameter Tree on the left tab.

  17. In the Parameter tree browse to Ethercat/yourdomain/yourdevice and click the Input that has the switch connected to it. This will add the path to your element.

  18. Press the preview button on the upper right hand side to test our GUI.

  19. A new tab will open with our Previeuw GUI. Here we can test if our switch and light works. If everything works, we can deploy the new GUI to your controller

  20. Go back to your project folder and User Interface directory.

  21. On the right tab press the deploy button.

  22. fill in your IP adress and deploy your GUI.

  23. Congratulations you have now created a GUI for your application.

This was the last step of the Getting started. you now have all the basics you need to create a Motorcortex Application. The next step is to create automated programs. For realtime applications you need to take a look at Developing Control Applications

If your program does nog have to be realtime and you prefer other programming languages make sure to take a look at Developing Client Applications

More information about the Motorcortex grid tool can be found under Motorcortex Grid

1.5.3 - Use the MCX-Generic-App

In this section you will be using the Motorcortex Generic-App

The goal of this tutorial is to learn how to use a Motorcortex GUI. to control the commissioned control devices we are using the Generic-App.

Introduction to a Motorcortex GUI

Before going in to detail of using the Generic-App GUI you will have to know how to access a Motorcortex GUI and the Basics of using a Motorcortex GUI. An overview of all GUIs deployed on your controller can be found at [Controller IP address]/list, per default http://192.168.2.100/list. You will get a view like below.

  1. Click on gui to access the user interface.
  2. If there are more than one gui deployed to your system you can mark that particular gui as your default. This means that when you access the controller’s main url http://192.168.2.100/ you will be taken straight to you favorite GUI. To come back to this menu type http://192.168.2.100/list in your address bar.

Main components of a GUI

After clicking Generic-App/gui.grid the Generic-App GUI will show. Before going into details it is important to know about the components that a GUI exists out of:

1. Screen Selector: Select the screen you want to view (each screen will be described in seperate sections).
2. Screen Elements: The content of the screen.
3. Status and time: Status of the motion controller and the time on the controller/GUI.
4. Active Error list: Here all active errors are visible. Depending on the severity of the error the ϟ button will have different colors.
5. Recent Logs: Here the latest state changes are located.

Screen Elements

A Motorcortex GUI has many interaction elements.

The user can interact with the GUI via the following items:

  • Buttons
  • Sliders
  • Input fields
  • Joysticks

For more detail on all GUI elements, go to Motorcortex Grid.

Status and time

The Status shows the state of the system e.g. OFF, ENGAGED and ESTOP. depending on the application you are running these states can change.

The time shown on the controller is the set time by the user. More information on changing the time on the controller can be found at Change Time.

Active Error List

If Motorcortex encounters a error you will be notified. And can lookup and act on these errors in the active error list. Depending on the severity of the error the ϟ button will have different colors:

  • No error:
  • Warning present:
  • Fault present:

The List can be shown by click on the ϟ button:

In the list the following properties are shown:

  • Time: the controller time when the error occurred.
  • Sub: code for the axis where the error occurred, in this case 1 stands for axis 1.
  • Level: this is the severity of the error: Wa = Warning, ES = Emergency Stop
  • Number: error ID, is linked to the type of error
  • Description: very short error description. A more detailed error description will be shown when on the error is clicked.

There are several types of Errors:

  • Warning: an error to inform the user a more sever error is about to happen, however till that time the system will keep running.
  • Forced Disengaged: the system will move to Disengaged position: power is still present on the drives, but motion is not allowed after Disengaged state is reached.
  • Shutdown: an error has occur ed that the application will shutdown.
  • Emergency Stop: an emergency stop is generated, all power to the actuators shall be cut (how depends on the application, either by an emergency relay or by sending a STO (Safe Torque Off) signal to the drives.

Errors can be acknowledge by pressing the button , but it is strongly recommended to first carefully read, analyze the error description and find a solution for the error, before pressing this button. If the causes for all errors have been removed, the system will be in a normal operating state. If a cause for an error is still active, the error is triggered again.

⚠ After an Error the operator shall check the cause of the Error and make sure the problem is solved. Only after that a reset is allowed.

⚠ Errors shall only be acknowledged after a user interaction, never automatically.

Recent log entries

The recent logs will slide upwards by clicking on the button.

The Generic-App

Make and save data traces

Before a data trace is started, all desired signals should be selected (and thus being plotted in the Plot Window). To start the tracing, click on the ▶️ RECORD button. To stop the tracing, click on the ⏹ STOP button. After the trace will be straight away be downloaded to your computer. The format is a .csv file, which can be opened in a text editor, but also in Microsoft Excel, Python or Matlab.

Changing values

Modifying a parameter value

A parameter can be changed in two locations:

  1. In the parameter tree by clicking on the value. This will open an input field where you can type the new value. The value will be taken over as soon as enter is pressed.
  2. By clicking on the input field behind the signal and its actual value and type the new value. The value will be taken over as soon as enter is pressed.

NOTE: MotorCortex-Desk accepts calculations and values from the math.js library and will directly fill-in the resulting values. So typing “cos(pi/2)” will result into a value of 0.

⚠ Changing parameters may cause unpredictable or unstable machine behavior and may cause danger to personnel or cause damage to the machine or its surroundings.

Saving and loading parameter sets

It is possible to save and load parameter list. In this way a functional configuration can be backed-up and reloaded easily.

  1. Saving the parameter set To save the (changed) parameter files to the Motion Controller, click in the top right of the Parameter Window on the 💾 save button . If no name is specified, the file will directly overwrite “control.xml” located on the motion controller in the folder /etc/motorcortex/config/control.
    The controller will by default load control.xml at start-up. If the parameters are changed, but list is NOT saved, the unchanged control.xml will be loaded the next time the software is restarted.

⚠ If no file name is specified the original parameter file “control.xml” will be overwritten, without any backup of the old file. Any wrong filled in parameters will be also automatically loaded after the next reboot of system.

Changing parameters may cause unpredictable or unstable machine behavior and may cause danger to personnel or cause damage to the machine or its surroundings.

The user is advised to save the current “control.xml” before overwriting the file.

  1. Loading a parameter set To upload a parameter parameter file from your computer, click on the upload button in the top right of the Parameter Window. Any new values will be straight away applied. Make sure that your system is in a safe state before uploading and keep a copy of the original parameter file.

⚠ Changing parameters during operation may cause unpredictable or unstable machine behavior and may cause danger to personnel or cause damage to the machine or its surroundings.

Make sure that the system is in a safe condition and cannot start by itself.

The user is advised to save the current “control.xml” before uploading the file.

Overriding inputs and outputs

Sometimes it is needed to temporary overwrite an input or output (e.g. to test an output). This can be done by ticking the checkbox behind the signal, both in the Tracing Overview as in the Parameter tree. The signal will than become orange and will not change unless the user removes the overwrite or will fill in a different value.

An example is below: the enable of jointReferenceGenerator controls the enable of all 6 signalGenerators. If the enable of signalGenerator01 has to be disabled, while the rest have to stay enabled, an overwrite has to be applied to signalGenerator01/enable

⚠ Changing signal values during operation may cause unpredictable or unstable machine behavior and may cause danger to personnel or cause damage to the machine or its surroundings.

Make sure that trained personnel is operating MotorCortex-Desk and the system is or can be quickly put in a safe state (e.g. by pressing the emergency button that is within reach).

NOTE: Overriding inputs is not possible when the input is written to from inside the block. The value that is sent to the application is then immediately overwritten by the application itself.

NOTE: Overwritten values are shown in orange, but if the folder is closed, you will not see it anymore. If the sofware is restarted, all overwritten values are gone.

2.3 - Motorcortex-ECAT

With Motorcortex-ECAT you can configure your EtherCAT Devices

Introduction

Motorcortex ECAT is a web-based application that is used to configure your EtherCAT devices for Motorcortex. The Motorcortex ECAT tool generates a .xml file that is used inside the parameter tree.

Screen Layout

The Motorcortex-ECAT build environment screen layout contains the following main elements:

  • Top Menu Bar The Top Menu Bar is where you can manage your settings and also Fetch and Deploy your .xml files.
  • Domains Configuration Panel In the Domains Configuration Panel you configure the domais of your EtherCat devices.
  • Device Configuration Panel In the Device Configuration Panel you can configure your EtherCAT devices.

2.3.1 - Top Menu Bar

With Motorcortex-ECAT you can configure your EtherCAT Devices

Top Menu Bar

On the top of the Motorcortex-ECAT screen you will find the Top Bar. In this bar you wil find the folowing buttons:

Button Description
Gear The gear button will open the Top Bar drop down menu.
Connection Pressing the Connection button will open the connection settings.
Add Devices With the Add Devices button the add devices menu will open.
New Configuration The New Configuration button will empty the current configuration.
Load Configuration With the Load Configuration button you can upload a locally saved configuration .xml file.
Download Configuraton With the Download Configuration button you will download the current configuration to your local machine.
Dark Mode This beautiful switch will turn on Dark Mode.
Fetch Pressing the Fetch button will download the current configuration from the connected controller.
Deploy Pressing the Deploy button will Upload the current configuration from the connected controller.

2.3.2 - Domains Configuration Panel

Explanation of the Domains Configuration Panel

Domains Configuration Panel

On the left of the Motorcortex-ECAT screen you will find the Domains Configuration Panel. In this panel you can configure the domains of your EtherCAT devices.

Ethercat devices have to be placed inside of Domains. A Domain is an group of EtherCAT slaves (physical cluster of EtherCAT modules). For your project you can make use of one single domain, or multiple domains. An advantage multiple domains, is that every domain is separate and can (if configured properly) be disconnected and reconnected (hot-plug), while other devices in other domains that remain connected are still operational. Beside hot-plug capability domains also keep your structure more clear.

Adding devices

To add a new device you can click the button or add devices from the Top Bar dropdown. After this the Add devices menu will pop up.

From the Add Devices menu you can you can add Ethercat devices in several ways.

Tab Description
From Scan In the From Scan tab When connected to a Motorcortex controller with Ethercat devices connected, you can scan the EtherCAT bus for devices that are connected by pressing the button.
From Configuration In the From Configuration Tab you can add Ethercat devices from a previous configuration by pressing the button.
From Description Files In the From Description Files Tab you can add devices by uploading the ESI files provided by the component manufacturer by pressing the button.
Manually In the Manually tab It is also possible to add Devices manually by pressing the button. The device menu will popup here you can fill in the device data and hit save.

Domains

After having devices added the Domains Configuration Panel should look like this.

You can change the name of the domain to whatever name you like. By pressing the Checkbox you can include or exclude the domain from the EtherCAT message, this means that this domain will not be used for your application.

Devices

The number infront of a device is the device alias number, this number is normally used as the device position in the EtherCAT bus. By pressing the Checkbox you can include or exclude the device from the EtherCAT message, this means that this device will not be used for your application.

2.3.3 - Device Configuration Panel

With Motorcortex-ECAT you can configure your EtherCAT Devices

Device Configuration Panel

In the middle of the Motorcortex-ECAT screen you will find the Device Configuration Panel. With this panel you can configure your devices. A device has multiple tabs:

Tab Description
rxPDO A Proces Data Object (PDO) present the Inputs and Outputs of a node device to the EtherCAT master and are updated every cycle. RxPDO’s are received by a node and are used maily to control device Outputs.
txPDO A Proces Data Object (PDO) present the Inputs and Outputs of a node device to the EtherCAT master and are updated every cycle. RxPDO’s are transmitted by a node and are used maily to read device Inputs.
rxSDO A Service Data Object (SDO) present device parameters and are only updated via the ethercat mailbox request. RxSDO’s are received by the node device and are used for writable parameters.
txSDO A Service Data Object (SDO) present device parameters and are only updated via the ethercat mailbox request. TxSDO’s are send by the node device and are used for readable parameters.
Distributed Clock .
Info .
Startup .

rxPDO

In the rxPDO tab you can configure the rxPDO’s from your device.

Field Description
Here you fill in the PDO index defined by the device manufacturer.
Here you can define the group of this PDO within the device in the parametertree.
This is where you can change the name of the PDO .
With this checkbox you can choose to include/exclude this PDO from the EtherCAT message.
With this button you can choose to make this PDO visible in the parameter tree.
Pressing this button will show a dropdown with more options.
The Add Link button will ad a link for this PDO.
The Add PDO will add a new PDO for this device.
The Add Entry button will ad a Entry for this device.
With the delete button you will delete this PDO.

txPDO

In the txPDO tab you can configure the txPDO’s from your device.

Field Description
Here you fill in the PDO index defined by the device manufacturer.
Here you can define the group of this PDO within the device in the parametertree.
This is where you can change the name of the PDO .
With this checkbox you can choose to include/exclude this PDO from the EtherCAT message.
With this button you can choose to make this PDO visible in the parameter tree.
Pressing this button will show a dropdown with more options.
The Add Link button will ad a link for this PDO.
The Add PDO will add a new PDO for this device.
The Add Entry button will ad a Entry for this device.
With the delete button you will delete this PDO.

rxSDO

In the rxSDO tab you can configure the rxSDO’s from your device.

Field Description
Here you define the SDO type, this can either be CoE (CANopen over EtherCAT) or SoE (Servo drive over Ethercat).
Here you can define the group of this SDO within the device in the parametertree.
This is where you can change the name of the SDO .
Here you fill in the SDO entry index defined by the device manufacturer.
Here you can define the group of this SDO entry within the device in the parametertree.
Here you fill in the SDO entry index defined by the device manufacturer.
The data type of a SDO entry can be defined here this can be: Not set, Bit, Bool, Int, Uint, Float, Double.
The data lengt of a SDO entry can be defined here.
This is where you can change the name of the SDO entry.
Pressing this button will show a dropdown with more options.
The Add SDO will add a new SDO for this device.
The Add Entry button will ad a Entry for this device.
With the delete button you will delete this SDO.

txSDO

In the rxSDO tab you can configure the rxSDO’s from your device.

Field Description
Here you define the SDO type, this can either be CoE (CANopen over EtherCAT) or SoE (Servo drive over Ethercat).
Here you can define the group of this SDO within the device in the parametertree.
This is where you can change the name of the SDO .
Here you fill in the SDO entry index defined by the device manufacturer.
Here you can define the group of this SDO entry within the device in the parametertree.
Here you fill in the SDO entry index defined by the device manufacturer.
The data type of a SDO entry can be defined here this can be: Not set, Bit, Bool, Int, Uint, Float, Double.
The data lengt of a SDO entry can be defined here.
This is where you can change the name of the SDO entry.
Pressing this button will show a dropdown with more options.
The Add SDO will add a new SDO for this device.
The Add Entry button will ad a Entry for this device.
With the delete button you will delete this SDO.

Distributed Clock

In the Distributed Clock tab you can configure the distributed clock for your device.

Field Description
With this button you will enable Distributed clock synchronization mode for this application.
In the assign active field you fill in the HEX number defined in the ESI file of the Device. It tels this specific device to activate the the distributed clock.
Here you fill in the time between Sync0 events in nano seconds.
Here you fill in the shift time between Sync0 events in nano seconds.
Here you fill in the time between Sync1 events in nano seconds.
Here you fill in the shift time between Sync1 events in nano seconds.

Info

In the info tab the device information is displayed.

Startup

COE Configuration

Field Description
.
.
.
.
.
.
.
Pressing this button will show a dropdown with more options.
The Add Entry button will ad a Entry for this device.
With the delete button you will delete this SDO.

SOE Configuration

Field Description
.
.
.
.
.
.
.
Pressing this button will show a dropdown with more options.
The Add Entry button will ad a Entry for this device.
With the delete button you will delete this SDO.

2.3.4 -

EtherCAT slaves configuration

Introduction

MOTORCORTEX is a Hard-Realtime Control System with an integrated high-speed communication system. It is especially designed to allow easy and high-performance interaction with the control system from any client platform and with many supported programming languages.

This document will explain how to link EtherCAT slave devices to a MOTORCORTEX application.

Configuring EtherCAT slaves requires a number of steps:

  1. scan the EtherCAT bus and generate a topology file;
    the topology file is used by MOTORCORTEX to create the correct format of EtherCAT messages, such that all slave devices and their data objects can be addressed.
  2. configure each input or output for each device and link it to the MOTORCORTEX application.
  3. create special configurations for some more complex devices, such a servo-controllers or configurable i/o cards. This step is not always required.

MOTORCORTEX and EtherCAT basics

MOTORCORTEX

In a MOTORCORTEX application all control objects are organized in a tree structure; the Parameter Tree. The Parameter Tree contains a snapshot of all the inputs, outputs and internal data of the control objects at the current time.

MOTORCORTEX has a tree structure in which the data objects are published. Each task or objects inside a task can create their own subtree (folder). Objects can be nested. In a general control application there are usually a “Logic”, “Control” and also “EtherCAT” folders that represent the data of different tasks. In the EtherCAT folder you will find the configured EtherCAT slave devices.

The names of the folders are configurable and the application developer can change these, but it is good practice to stick to some convention.

Inside the folders the data of the associated object is contained. MOTORCORTEX currently supports the following datatypes: boolean, integer, double or binary (e.g. a c-struct). Also arrays of the same datatype are supported. Array elements start at index 0 (zero).

To view the tree structure use the MOTORCORTEX-Desk tool.

EtherCAT Domains/Groups

It is possible to divide the EtherCAT IOs in separate domains.

A Domain is an group of EtherCAT slaves (physical cluster of EtherCAT modules). Each domain has a dedicated XML file. An advantage different domains, is that every domain is separate and can (if configured properly) be disconnected and reconnected (hot-plug), while other devices in other domains that remain connected are still operational. Beside hot-plug capability domains also keep your structure more clear.

Per domain, groups (and subgroups) can be created. Typically each EtherCAT slave is assigned to a name and/or group. In that case the slave will appear in MOTORCORTEX-Desk as a dedicated folder.
Optionally it is possible to create subfolders for data objects (e.g. if the user prefers to separate inputs and outputs). This is all for a clear structure, functionally all data objects from one domain can also be dumped together.

Sending Information over EtherCAT

The information sent and received over the EtherCAT network consists (among others) of data packages of the following types: PDOs and SDOs.

PDO stands for Process Data Object. This is cyclic data that is send or received during every EtherCAT broadcast. Examples are: status of switches and lights, actuator setpoints and actual values.

SDO stands for Service Data Object. This is in data that is normally only send during start-up or during an event. Examples are: motor parameters, sensor configuration and (drive) error information.

The configuration of the SDOs on an EtherCAT module can be send via a mailbox file. There are two file types: CANopen over EtherCAT (CoE) and Sercos over EtherCAT (SoE, sometimes also called Servo over EtherCAT). The structure of the file is very similar for both types. The EtherCAT module manufacturer decides which type is used.

There are also other types of information that can be send over EtherCAT (e.g. File over EtherCAT (FoE), EtherNet over EtherCAT (EoE)), but this is out of scope of this document that will only focus on adding EtherCAT slaves to the MOTORCORTEX software.

Parameter Types in MOTORCORTEX:

This subsection shortly describes how the different parameter types can be used in combination with EtherCAT.

The MOTORCORTEX structure has the following parameter types:

  • Input: In this parameter type a value can be written. A typical use is an sensor. In the EtherCAT configuration file the sensor value will be linked to an input. However it is possible to also write this value an input into EtherCAT output. An input is typically linked to a PDO. In MOTORCORTEX Desk an input is depicted as:

  • Output: this parameter type is read-only. A typical use is a set point value. The value is calculated within the MOTORCORTEX and shall not be overwritten. Therefore this value can only be linked to an EtherCAT output, but never to an EtherCAT input. An output is typically linked to a PDO. In MOTORCORTEX Desk an output is depicted as:

  • Parameter: This is parameter type that is used to configure the system. Typical uses are motor parameters and system constants.Parameters are retrieved from the parameter list during start-up. If the user changes a value and wants to use in the future, he has to save the list before rebooting/switching off the controller. A parameter can be read and written. However due to its character, it will be used mostly in combination with SDOs. In MOTORCORTEX Desk an parameter is depicted as:

  • Persistent: these are values that contain process data that is continuously updated and will be retained through application restarts. Typical applications are running ours or amount of produced products. In MOTORCORTEX Desk an persistent is depicted as:

Configuring EtherCAT Topology

Introduction

The EtherCAT Topology contains information about which devices are in a network and how they are connected. Each slave device will receive an ID that is determined by its place in the topology. With this ID the application can address the device and send information to an receive information from the device.

In an EtherCAT network a single message is sent that passes by all devices and is returned back to the Master. Each device takes its own information from this message and inserts data back into the message as it passes. The Master needs to know the topology before it can build the correct message, containing data for all the slaves.

MOTORCORTEX is capable of using different EtherCAT Master stacks. By default the EtherLab (https://etherlab.org/) Master is used. The tools to scan the EtherCAT topology are provided as part of the EtherLab driver. MOTORCORTEX is compatible with the topology files generated by the EtherLab tools.

Scanning available slaves

Connect all slaves to the EtherCAT Network. Also the slaves that you want to hot-plug later.

Log in to the controller (via SSH) and type the following (on some systems it may be required to use sudo to execute the command with root privileges):

ethercat slaves

This command should output the connected EtherCAT slaves, for instance:

0 0:0 PREOP + EK1100 EtherCAT Coupler (2A E-Bus)
1 0:1 PREOP + EL1018 8K. Dig. Eingang 24V, 10�s
2 0:2 PREOP + EL2008 8K. Dig. Ausgang 24V, 0.5A
3 0:3 PREOP + EL3104 4K. Ana. Eingang +/-10V Diff.
4 0:4 PREOP + EL4134 4K. Ana. Ausgang -10/+10V. 16bit
5 0:5 PREOP + EL3174 4K. Ana. Eingang +/-10V Diff., +/-20mA SingleEnded, 16bit

Above you see 6 slaves with ID’s 0 through 5 being detected. EtherCAT starts numbering of slaves at 0.

Check if all slaves are present. If slaves are missing, check the EtherCAT connection and if the slave is powered.

Create/update EtherCAT Topology

First make a copy of the current topology (via filezilla or via the terminal, see below)

cd /etc/motorcortex/config/io
cp topology.xml topology_backup_YYYY_MM_DD.xml

To write the new topology type the following in the terminal.

sudo ethercat xml > topology.xml

The exact content of the topology.xml file will not be discussed in this document, since it is complex and not needed for this document. If the user is curious, he is encouraged to open the file in a text editor and view the content. The file should not be modified by hand.

Careless changing of topology.xml can result that the whole application will not work anymore. Therefore always first make a backup before changes are made.

Linking EtherCAT Slaves to MOTORCORTEX signals

In this chapter the inputs and outputs of the EtherCAT devices will be linked to MOTORCORTEX parameters. These links are located in a PDO file (or more PDO files in case of multiple domains).

Creating slave configurations and linking signals to MOTORCORTEX (pdo.xml)

With the Slaves connected and the topology.xml file generated and installed, follow the following procedure to create a slave configuration:

Create a file called /etc/motorcortex/config/io/pdo.xml and copy the text below into it. The filename is determined in the MOTORCORTEX Application and depends on the programmer’s choice. This is the most basic version of a slave configuration file, where all inputs and outputs from all (most) slaves are mapped to the MOTORCORTEX application. The file first defines a Domain and links a topology file to this domain. topology.xml is the file generated in Scanning available slaves. The option MapAll=1 maps all the inputs and outputs of slave devices and generates default names. Devices that do not have simple inputs or outputs may not be mapped with MapAll.

<?xml version="1.0"?>
<Domain File="topology.xml" MapAll="1"></Domain>

Restart the MOTORCORTEX server application (sudo may require the user’s password)

sudo /etc/init.d/motorcortex restart

Go to MOTORCORTEX-Desk via your browser and log in:

http://192.168.2.100:8000
Server address: 192.168.2.100
Username: admin
Password: vectioneer

Go to the folder root/EtherCAT, here you will find subfolders of the EtherCAT devices.
The order of the devices is alphabetical.
The slave ID is the last part of the device name.

Adding information to slaves

As a reminder of which slaves are present it is handy to copy the slave list that was shown as part of the procedure in Scanning available slaves in your pdo.xml file. This way you can quickly look up which devices are present and what their ID is.

<!--
0 0:0 PREOP + EK1100 EtherCAT Coupler (2A E-Bus)
1 0:1 PREOP + EL1018 8K. Dig. Eingang 24V, 10�s
2 0:2 PREOP + EL2008 8K. Dig. Ausgang 24V, 0.5A
3 0:3 PREOP + EL3104 4K. Ana. Eingang +/-10V Diff.
4 0:4 PREOP + EL4134 4K. Ana. Ausgang -10/+10V. 16bit
5 0:5 PREOP + EL3174 4K. Ana. Eingang +/-10V Diff., +/-20mA SingleEnded, 16bit
-->

In the pdo.xml file, all devices can have their own section with configuration parameters. The devices are identified with a <Device Id="X"> tag, where the Id is the EtherCAT ID that refers to the device. Each device can be given a Group and a Name property. The Group specifies a subfolder when the device is created in MOTORCORTEX, and is optional. If the Group is omitted, the device will be created in the current Domain.

<?xml version="1.0"?>
<!--
0  0:0  PREOP  +  EK1100 EtherCAT Coupler (2A E-Bus)
1  0:1  PREOP  +  EL1018 8K. Dig. Eingang 24V, 10�s
2  0:2  PREOP  +  EL2008 8K. Dig. Ausgang 24V, 0.5A
3  0:3  PREOP  +  EL3104 4K. Ana. Eingang +/-10V Diff.
4  0:4  PREOP  +  EL4134 4K. Ana. Ausgang -10/+10V. 16bit
5  0:5  PREOP  +  EL3174 4K. Ana. Eingang  +/-10V Diff., +/-20mA SingleEnded, 16bit
-->

<Domain File="topology.xml">
    <!--device 0, EK1100-->
    <Device Id="1" Group="Group1" Name="01-EL1018-01" MapAll="1">
    </Device>
    <Device Id="2" Group="Group1" Name="02-EL2008-01" MapAll="1">
    </Device>
    <Device Id="3" Group="Group2" Name="03-EL3104-01" MapAll="1">
    </Device>
    <Device Id="4" Group="Group2" Name="04-EL4134-01" MapAll="1">
    </Device>
    <Device Id="5" Group="Group2" Name="05-EL3174-01" MapAll="1">
    </Device>
</Domain>

to check the result:

Save the file

/etc/MOTORCORTEX/config/io/pdo.xml, 

restart MOTORCORTEX

sudo/etc/init.d/motorcortex restart 

log in on MOTORCORTEX-Desk (http://192.168.2.100:8000)

See if you can already see the individual inputs and outputs.

Linking a digital input to a MOTORCORTEX parameter

Normally each Slave device has a number of Inputs or Outputs. These signals can be linked to a signal in the MOTORCORTEX Parameter Tree. EtherCAT inputs write data to the Parameter Tree and can only be linked to parameters that allow write access (Inputs and Parameters); it is not possible to link an EtherCAT input to an Output signal. Check the MOTORCORTEX-Desk to see what the type of the parameter is you would like to link to.

Consider the example pdo.xml below.

<!--
<?xml version="1.0"?>
<!--
0  0:0  PREOP  +  EK1100 EtherCAT Coupler (2A E-Bus)
1  0:1  PREOP  +  EL1018 8K. Dig. Eingang 24V, 10�s
2  0:2  PREOP  +  EL2008 8K. Dig. Ausgang 24V, 0.5A
3  0:3  PREOP  +  EL3104 4K. Ana. Eingang +/-10V Diff.
4  0:4  PREOP  +  EL4134 4K. Ana. Ausgang -10/+10V. 16bit
5  0:5  PREOP  +  EL3174 4K. Ana. Eingang  +/-10V Diff., +/-20mA SingleEnded, 16bit
-->

<Domain File="topology.xml">
    <!--device 0, EK1100-->

    <Device Id="1" Name="01-EL1018-01">
    <Pdo Entry="6000:01" Name="input_01">
       <Link>root/Control/dummyBool</Link>
    </Pdo>
    </Device>

    <Device Id="2" Name="02-EL2008-01">
    </Device>

    <Device Id="3" Name="03-EL3104-01">
    </Device>

    <Device Id="4" Name="04-EL4134-01">
    </Device>

    <Device Id="5" Name="05-EL3174-01">
    </Device>
</Domain>

In this example, the EtherCAT Slave with ID 1 is a digital input module EL1018, that has 8 digital inputs. The input is a Process Data Object (PDO) and can be configured with the <Pdo> tag. The Entry property specifies where the PDO can be found on the device. The Entry consist of the index (hex) and subindex (two digits, leading zeros). The indices and sub-indices of the signals can be found in the documentation of the device provided by the manufacturer or can be derived from the contents of the topology.xml file.

In the topology.xml file the index and subindex for this particular type of device can be found in the <Entry> section of the device.

...
    <Device>
        <Type ProductCode="#x03fa3052" RevisionNo="#x00120000">EL1018</Type>
        <Name><![CDATA[EL1018 8K. Dig. Eingang 24V, 10�s]]></Name>
        <Sm Enable="1" StartAddress="#x1000" ControlByte="#x0" DefaultSize="1" />
        <TxPdo Sm="0" Fixed="1" Mandatory="1">
            <Index>#x1a00</Index>
            <Name>Channel 1</Name>
            <Entry>
                <Index>#x6000</Index>
                <SubIndex>1</SubIndex>
                <BitLen>1</BitLen>
                <Name>Input</Name>
                <DataType>BOOL</DataType>
            </Entry>
        </TxPdo>
        <TxPdo Sm="0" Fixed="1" Mandatory="1">
            <Index>#x1a01</Index>
            <Name>Channel 2</Name>
...

In this case, the first input of this device is located at index 6000 and subindex 1. To set the index and subindex of the input we use the Entry property:

<Pdo Entry="6000:01" Name="input_01">

Using the name property, the input is named “input_01”. This name will be used when the device is added to the MOTORCORTEX Parameter Tree. In this case the input can be found in the tree: /root/EtherCAT/00-EL1018-01/input_01

To link a value to the MOTORCORTEX application use the <Link> tag. The path to link to can be found by opening the MOTORCORTEX-Desk and browsing to the appropriate value in the tree. How to create a MOTORCORTEX application see

!!TBD!! G0110-0200-01-MAN-[Developing Motorcortex Applications in C++ (Server)](#Developing Motorcortex Applications in C++ (Server)).


...
    <Device Id="1" Name="00-EL1018-01">
        <Pdo Entry="6000:01" Name="input_01">
            <Link>root/Control/dummyBool</Link>
        </Pdo>
    </Device>
...

to check the result:

Save the file

/etc/MOTORCORTEX/config/io/pdo.xml, 

restart MOTORCORTEX

sudo/etc/init.d/motorcortex restart 

log in on MOTORCORTEX-Desk (http://192.168.2.100:8000)

If now the input is made high, the value the input is linked to (in this case root/Control/dummyBool) will go to 1.

Linking a digital output

It is also possible to place a boolean value in an output. EtherCAT outputs can be linked to MOTORCORTEX Inputs, Outputs and Parameters.

<?xml version="1.0"?>
<!--
...
-->
<Domain File="topology.xml">
    <!--device 0, EK1100-->

    <Device Id="1" Name="01-EL1018-01">
    <Pdo Entry="6000:11" Name="input_01">
       <Link>root/Control/dummyBool</Link>
    </Pdo>
    </Device>

    <Device Id="2" Name="02-EL2008-01">

    <Pdo Entry="7000:01" Name="output_01">
       <Link Invert="1">root/Control/dummyBool</Link>
    </Pdo>

    <Pdo Entry="7010:01" Name="output_02">
       <Link>root/Control/module_state</Link>
    </Pdo>

    </Device>

    <Device Id="3" Name="03-EL3104-01">
    </Device>

    <Device Id="4" Name="04-EL4134-01">
    </Device>

    <Device Id="5" Name="05-EL3174-01">
    </Device>
</Domain>

Besides adding the dummyBool to the output, we also added Invert="1". This means when digital input 1 is 1/true, output 2 will be 0/false (and vice versa). Output 2 is selected by Entry="7010:01". This value already showed up when we used MapAll="1". For the correct entry, look in to the documentation of the EtherCAT slave, typically under the subheading input data or output data. Last to demonstrate that it is also possible to write an integer to a digital output, the state of the MOTORCORTEX Logic is written to output 3.

Analog inputs

Each analog device has it’s own measuring range and unit. This means that every device has its own conversion. Where for a PT100-temperature module as the EL3201, the temperature is passed through as a value x10 (thus 31.4°C is transmitted as 314), for many others it is a value of 2^x for the full range. The EL3104 for instance has a full range of -10..10V with 16 bits resolution. The EL3104 uses an UINT16 (unsigned integer) value to represent -10..10V, this means that 0 = -10V and 65536 = +10V. In the configuration file however we can map the UINT16 value to an INT16 value, which is signed. This means that now 0V = 0, 10V = 2¹⁵-1 (since we start at 0) and -10V is -2¹⁵.

<?xml version="1.0"?>
<!--
...
-->
<Domain File="topology.xml">
    <!--device 0, EK1100-->
    <Device Id="1" Name="01-EL1018-01">
    <Pdo Entry="6000:01" Name="input_01">
       <DataType>INT16</DataType>
       <Link>root/Control/dummyBool</Link>
    </Pdo>
    </Device>
    <Device Id="2" Name="02-EL2008-01">
    <Pdo Entry="7010:01" Name="input_02">
       <DataType>INT16</DataType>
       <Link Invert="1">root/Control/dummyBool</Link>
    </Pdo>
    </Device>
    <Device Id="3" Name="03-EL3104-01">
    <Pdo Entry="6020:11" Group="Analog Inputs" Name="analog_input_03">
       <DataType>INT16</DataType>
       <Link Divide="3276.8">root/Control/dummyDouble</Link>
    </Pdo>
    </Device>
    <Device Id="4" Name="04-EL4134-01">
    </Device>
    <Device Id="5" Name="05-EL3174-01">
    </Device>
</Domain>

The slave uses some datatype that is also specified in the topology.xml file. Using the <DataType> tag the datatype can be changed to a more convenient format. In general it is used to convert from unsigned integer values to signed integers. So the slave for instance uses UINT16 as a type, with values in the range 0..65536, using <DataType>INT16</DataType>, it can be converted to a INT16 with a range of -32768..32767. So the value of 0 corresponds to 0.00V for instance in a -10V..10V input card.

Above a -10…10V value will be read-in on slave 4 (id=3), input 4. Note the Divide="3276.8". This scales the ‑2¹⁵…2¹⁵-1 back to -10…10V. This is done to easy cross-check the incoming voltage in case of troubleshooting. Another item introduced over here is Group="Analog Inputs". Since this module has only analog inputs, the subgroup that is now created is rather useless, but in EtherCAT module that have multiple types of inputs and or outputs (like drives), it results in a organized structure that allows quicker navigation.

Note: it is good practice to first link the analog input of the sensor to an input double that has the measuring unit (in this case Volt).

Analog outputs

<?xml version="1.0"?>
<!--
...
-->

<Domain File="topology.xml">
    <!--device 0, EK1100-->

    <Device Id="1" Name="01-EL1018-01">
    <Pdo Entry="6000:11" Name="input_01">
       <DataType>INT16</DataType>
       <Link>root/Control/dummyBool</Link>
    </Pdo>
    </Device>
    <Device Id="2" Name="02-EL2008-01">
    <Pdo Entry="7010:01" Name="input_02">
       <DataType>INT16</DataType>
       <Link Invert="1">root/Control/dummyBool</Link>
    </Pdo>
    </Device>
    <Device Id="3" Name="03-EL3104-01">
    <Pdo Entry="6020:11" Name="analog input 03">
       <DataType>INT16</DataType>
       <Link Divide="3276.8">root/Control/dummyDouble</Link>
    </Pdo>
    </Device>
    <Device Id="4" Name="04-EL4134-01">
    <Pdo Entry="7030:01" Name="analog output 04">
       <DataType>INT16</DataType>
       <Link Gain="3276.8" GainOffset="3276.8">root/Control/dummyDouble</Link>
    </Pdo>
    </Device>
    <Device Id="5" Name="05-EL3174-01">
    </Device>
</Domain>

Above the value of root/Control/dummyDouble is used to write to an analog output. The value of ‑10…10V is scaled back to the appropriate INT16 value by using Gain="3276.8", but on top of that the voltage is increased with 1V by using GainOffset="3276.8".

Start-up files and SDOs

Some EtherCAT devices are configurable through Service Data Objects (SDO’s); depending on how they are configured, they have different behavior. For instance the Beckhoff EL3174 Analog input module can be configured for different input types, e.g. current or voltage.

These devices can be configured by adding a <MailBox> tag, that points to a startup file that contains the desired configuration of the device. These setting are applied when the device is started.

The format of the startup files is determined by the type of slave device. Some devices use CAN over EtherCAT (CoE) for configuration, others use SERCOS over EtherCAT (SoE).

<?xml version="1.0"?>
<!--
...
-->

<Domain File="topology.xml">
    <!--device 0, EK1100-->

    <Device Id="1" Name="01-EL1018-01">
    <Pdo Entry="6000:01" Name="input_01">
       <DataType>INT16</DataType>
       <Link>root/Control/dummyBool</Link>
    </Pdo>
    </Device>
    <Device Id="2" Name="02-EL2008-01">
    <Pdo Entry="7010:01" Name="input_02">
       <DataType>INT16</DataType>
       <Link Invert="1">root/Control/dummyBool</Link>
    </Pdo>
    </Device>
    <Device Id="3" Name="03-EL3104-01">
    <Pdo Entry="6020:11" Name="analog input 03">
       <DataType>INT16</DataType>
       <Link Divide="3276.7">root/Control/dummyDouble</Link>
    </Pdo>
    </Device>
    <Device Id="4" Name="04-EL4134-01">
    <Pdo Entry="7030:01" Name="analog output 04">
       <DataType>INT16</DataType>
       <Link Gain="3276.7" Gainoffset="1">root/Control/dummyDouble</Link>
    </Pdo>
    </Device>
    <Device Id="5" Name="05-EL3174-01">
    <Mailbox File="05-EL3174-01_startup.xml"/>
    <Pdo Entry="6000:11" Name="analog input 01">
       <DataType>INT16</DataType>
       <Link Divide="3051.8" Index="0">root/Control/dummyDoubleArray</Link>
    </Pdo>
    </Device>
</Domain>

Above you can see that Divide="3051.8" is smaller, due to the larger measuring range of the EL3174. Also is the value placed into the first index (Index="0") of the array dummyDoubleArray.

To create the startup file, create a file in /etc/MOTORCORTEX/config/io called 05-EL3174-01_startup.xml.

<?xml version="1.0" encoding="ISO-8859-1"?>
<EtherCATMailbox>
    <CoE>
    <InitCmds>

        <InitCmd>
            <Transition>PS</Transition>
            <Comment><![CDATA[Input Type]]></Comment>
            <Timeout>0</Timeout>
            <Ccs>1</Ccs>
            <Index>32781</Index>
            <SubIndex>17</SubIndex>
            <Data>0200</Data> <!-- -10..+10V  -->
<!--                <Data>0200</Data> <!-- -10..+10V  -->-->
<!--                <Data>0E00</Data> <!--   0..+10V  -->-->
<!--                <Data>1100</Data> <!-- -20..+20mA -->-->
<!--                <Data>1200</Data> <!--   0..+20mA -->-->
<!--                <Data>1300</Data> <!--   4..+20mA -->-->
<!--                <Data>1400</Data> <!--   4..+20mA (NAMUR) -->-->
        </InitCmd>

        <InitCmd>
            <Transition>PS</Transition>
            <Comment><![CDATA[Input Type]]></Comment>
            <Timeout>0</Timeout>
            <Ccs>1</Ccs>
            <Index>32797</Index>
            <SubIndex>17</SubIndex>
<!--                <Data>0200</Data> <!-- -10..+10V  -->-->
<!--                <Data>0E00</Data> <!--   0..+10V  -->-->
<!--                <Data>1100</Data> <!-- -20..+20mA -->-->
<!--                <Data>1200</Data> <!--   0..+20mA -->-->

            <Data>1300</Data> <!--   4..+20mA -->
<!--                <Data>1400</Data> <!--   4..+20mA (NAMUR) -->-->
        </InitCmd>

        <InitCmd>
            <Transition>PS</Transition>
            <Comment><![CDATA[Input Type]]></Comment>
            <Timeout>0</Timeout>
            <Ccs>1</Ccs>
            <Index>32813</Index>
            <SubIndex>17</SubIndex>
            <Data>0200</Data> <!-- -10..+10V  -->
<!--                <Data>0200</Data> <!-- -10..+10V  -->-->
<!--                <Data>0E00</Data> <!--   0..+10V  -->-->
<!--                <Data>1100</Data> <!-- -20..+20mA -->-->
<!--                <Data>1200</Data> <!--   0..+20mA -->-->
<!--                <Data>1300</Data> <!--   4..+20mA -->-->
<!--                <Data>1400</Data> <!--   4..+20mA (NAMUR) -->-->
        </InitCmd>

        <InitCmd>
            <Transition>PS</Transition>
            <Comment><![CDATA[Input Type]]></Comment>
            <Timeout>0</Timeout>
            <Ccs>1</Ccs>
            <Index>32829</Index>
            <SubIndex>17</SubIndex>
            <Data>0200</Data> <!-- -10..+10V  -->
<!--                <Data>0200</Data> <!-- -10..+10V  -->-->
<!--                <Data>0E00</Data> <!--   0..+10V  -->-->
<!--                <Data>1100</Data> <!-- -20..+20mA -->-->
<!--                <Data>1200</Data> <!--   0..+20mA -->-->
<!--                <Data>1300</Data> <!--   4..+20mA -->-->
<!--                <Data>1400</Data> <!--   4..+20mA (NAMUR) -->-->

        </InitCmd>

    </InitCmds>
    </CoE>
</EtherCATMailbox>

Mapping an SDO to the MOTORCORTEX Tree

It is also possible to map SDO’s to the MOTORCORTEX Parameter Tree, so they can be updated at runtime. For this to work, the SDO’s have to be configured using the <sdo> tag, so they are included in the EtherCAT communication. This is done by adding them to the device configuration in the pdo.xml.

<?xml version="1.0"?>
<!--\\
...
-->
<!--
<Domain File="topology.xml">
    <!--device 0, EK1100-->
<Device Id="1" Name="01-EL1018-01">
    <Pdo Entry="6000:01" Name="input_01">
       <DataType>INT16</DataType>
       <Link>root/Control/dummyBool</Link>
    </Pdo>
</Device>
<Device Id="2" Name="02-EL2008-01">
    <Pdo Entry="7010:01" Name="output_02">
       <DataType>INT16</DataType>
       <Link Invert="1">root/Control/dummyBool</Link>
    </Pdo>
</Device>
<Device Id="3" Name="03-EL3104-01">
    <Pdo Entry="6020:11" Name="analog input 03">
       <DataType>INT16</DataType>
       <Link Divide="3276.7">root/Control/dummyDouble</Link>
    </Pdo>
</Device>
<Device Id="4" Name="04-EL4134-01">
    <Pdo Entry="7030:01" Name="analog output 04">
       <DataType>INT16</DataType>
       <Link Gain="3276.7" Gainoffset="1">root/Control/dummyDouble</Link>
    </Pdo>
</Device>
<Device Id="5" Name="05-EL3174-01">
    <Mailbox File="05-EL3174-01_startup"/>
    <Pdo Entry="6000:11" Name="analog input 01">
       <DataType>INT16</DataType>
       <Link Divide="3051.8" Index="0">root/Control/dummyDoubleArray</Link>
    </Pdo>
    <Pdo Entry="6000:7" Name="Fault channel 1">
    </Pdo>
    <Pdo Entry="6010:7" Name="Fault channel 2">
    </Pdo>
    <Pdo Entry="6020:7" Name="Fault channel 3">
    </Pdo>
    <Pdo Entry="6030:7" Name="Fault channel 4">
    </Pdo>
    <Sdo Entry="800d:11" Size="2" Group="SDOs" Name="Input Type channel 1">          
       <DataType>INT16</DataType>
    </Sdo>
    <Sdo Entry="801d:11" Size="2" Group="SDOs" Name="Input Type channel 2"> 
       <DataType>INT16</DataType>
    </Sdo>

Now that the SDO is mapped it can be changed by using for instance the MOTORCOREX-Desk. IN case of the EL3174 analog input card, entering a value of 20 (decimal, it corresponds to hex 14), the module will use the 4…20mA input range. Changing the value to 2 (which is also hex 2), will change the input back to -10…10V. The values correspond to the content of the mailbox file. In the example configuration above the EL3174’s fault signals (PDO’s) are also mapped to MOTORCORTEX. When the channel is now configured for 4..20mA and no cable is connected to the input the “Fault channel 1” signal will become high (because when no cable is connected the input signal will be out of the sensor range). Also a red led will turn on the input module, indicating the fault.

Note that SDOs are still not updated cyclically. They only are updated via a mailbox command. MOTORCORTEX sends a mailbox update request package automatically when a SDO value is changed through the Parameter Tree. A read action of all SDOs can also be triggered by triggering the read_sdos input of the Domain in the Parameter Tree (setting it to a value of “1”). If this is done through the MOTORCORTEX-Desk, setting the read_sdos to 1 will not be visible; the server application immediately resets it back to “0” when the request is received.

If the recover_sdo parameter is set to 1, an SDO read request is automatically sent during startup and recovery of a lost connection.

Advanced EtherCAT configuration

EtherCAT Domain Errors

The MOTORCORTEX Parameter Tree also shows if a Domain has an error. The error output becomes true if there is an error. And error can be cause by a domain being disconnected or a problem with a slave in this domain.

There are two parameters that can be configured to change the behavior of the error output:

  • error_delay_sec; time is seconds before the error output becomes true (1) after an error is detected
  • no_error_delay_sec; time in seconds the error output becomes false (0) after the error is resolved.

EtherCAT slave Status

An EtherCAT slave module has different states. Every state allows different functions to be accessible or executable. The EtherCAT master can switch the slaves to different states.

The following EtherCAT Slave States are defined:

  • Init (INIT)
  • Pre-Operational (PREOP)
  • Safe-Operational (SAFEOP)
  • Operational (OP)
  • Bootstrap (BOOT)

For information on the meaning of the states see “EtherCAT and EtherCAT-P Slave Implementation Guide".

The slaves current state can be checked by issueing the following command on the controller:

ethercat slaves

The response of this command should be similar to:

0  0:0  OP  +  EK1100 EtherCAT Coupler (2A E-Bus)
1  0:1  OP  +  EL1018 8K. Dig. Eingang 24V, 10�s
2  0:2  OP  +  EL2008 8K. Dig. Ausgang 24V, 0.5A
3  0:3  OP  +  EL3104 4K. Ana. Eingang +/-10V Diff.
4  0:4  OP  +  EL4134 4K. Ana. Ausgang -10/+10V. 16bit
5  0:5  OP  +  EL3174 4K. Ana. Eingang  +/-10V Diff., +/-20mA SingleEnded, 16bit

where the third column shows the EtherCAT slave state.

When a MOTORCORTEX control application starts it will put all the slaves into Operational state.

!! TBD Distributed Clocks !!

!! TBD FsoE slaves !!

2.4 - Motorcortex-GRID

A explanation of how to work with Motorcortex Grid

Introduction

Motorcortex Grid is a web-based application that is used to create a custom GUI’s (graphical user interface) for your application. A GUI can be saved as a .grid file. Changing a .grid file has to be done using Motorcortex Grid with acces to motorcortex.io.

⚠ Using MotorCortex-grid all parameters of the running control system are accessible and may be modified. Changing parameters may cause unpredictable or unstable machine behavior and may cause danger to personnel or cause damage to the machine or its surroundings. The tool should only be used by system experts that have detailed knowledge of the system and that know what the impact of parameter changes is.

Quick Video - creating an HMI in under 2 minutes

Screen Layout

The Motorcortex-GRID build environment screen layout contains the following main elements:

  • Widget Library: In the Widget Library you can select the components (Widgets) you would like to add to your Screens.
  • Top Menu Bar In the Navigation bar you can open the library, preview your GUI and check your connection.
  • Properties Panel In the Properties Panel you set the properties of your Widgets and Screens.
  • Screens Area A user interface may have multiple screens. Each screen may contain Widgets.

2.4.1 - Top Menu Bar

A explanation of how to work with Motorcortex Grid

The Top Menu Bar

On the top of the application you can find The Top Menu Bar contains a couple of buttons that are used to create a GUI.

Button Description
Library Shows the Widget Library
Parameters Shows the Parameter Tree of your connected Machine. This button will not be available when you are not connected to a Machine.
Undo Undo your last action
Redo Redo your previous action
Deploy Deploy this GUI to a Machine. See Deploying a GUI
Preview Open the current GUI in Preview mode
Connection Here you can edit your current Machine connection. See Connection Pop-up

Deploying a GUI

If you press the Deploy button in the Top Menu Bar a new window is opened where you can enter the ip address of the Machine you would like to deploy this GUI to. Pressing the Deploy Button will start the deploy action. When the GUI is deployed, the system also checks of the current GRID release on the Machine is up-to-date. If a newer version of GRID is available, you have the option to update the GRID release on the Machine.

Deployment-Menu

Connection Pop-up

In the connection menu you can set up the connection with your Machine.

Connection-Menu

Bar Description
Host The Machine’s IP address.
Request Port to use for the Request/Reply connection (default 5568)
Subscribe Port ti use for the Subscribe connection (default 5567).
Username The User Name used to log in to the Machine
Password Your Passowrd
Secure Check this checkbox is you want to use secure connection (your browser will need the certificate that matches your Machine (server) certificate to be able to connect)

2.4.2 - Properties Panel

A explanation of how to work with Motorcortex Grid

The Properties Panel

On the right side of the application you will find the Properties Panel, this is where you configure all your grid elements. The Properties Panel also changes with each selected element in the grid. per default and by clicking the grid the Properties Panel will show the following menus:

Button Description
Client Connection Settings Will open and collapse Client connection settings menu.
Errors Will open and collapse Errors settings menu.
States Will open and collapse States settings menu.
Logs Will open and collapse Logs settings menu.
Screen Will open and collapse Screen settings menu.
Raster Will open and collapse Raster settings menu.

Client Connection Settings

In the Client Connection Settings menu you can set up the connection with your controller.

Client Connection Settings

Bar Description
IP address bar In the IP address bar you have to fill in your controllers local IP.
Request In the Request bar you fill in your Request/Reply channel port number by default this value is 5568.
Reveive In the Reveive bar you fill in your Publish/Subscribe channel port number by default this value is 5567.
Username In the User name bar you fill in your user name.
Password In the Password bar you fill in your password.
Secure With the Secure check box you can realize a secure connection.
Autologin With the auto-login check box you make the controller automatically re-login every time you connect.

Errors

In the Errors Settings menu you can manage the visualization of your errors. These settings are used in the Error handler located in The Grid.

Client Connection Settings

Bar Description
Errors Path Bar In the Path bar you select the path in the parameter tree to your error handler parameter. Per default this parameter is root/Logic/activeErrors.
Errors Acknowledge Bar In the Acknowledge bar you can select the path in the parameter tree to your acknowledge parameter. Per default this parameter is root/Logic/guiFaultAcknowledge.
Error Codes Bar In the Error codes bar you can select the .json file with your error codes.
Definitions Bar In the Definitions bar you can select the folder containing the error definitions.

Error Codes

The Error Parameter provides a Error number. This number can be linked to a file .json file created by the user to show text. Below is a template that gives an example of a errors.json file:

{
  "0": "SYSTEM_OK",
  "100": "WA_SYSTEM_WARNING",
  "101": "WA_REALTIME_VIOLATION",
  "500": "ES_SYSTEM_ERROR",
  "700": "SD_SYSTEM_ERROR",
}

This section will not cover how to set up a system error structure.
Learn how to create .json files in motorcortex.io here

Error Definitions

It is also possible to give definitions to errors. This can be done by putting .html files in the selected Errors folder. a template for the .html files inside this folder is given below:

{
<h1>100: Warning System Warning</h1>

<h2>Description</h2>
<p>Generic System Level Warning (used only for debug purposes)</p>
<!--
<h2>Cause</h2>
<ol>
<li>To Be Determined</li>
</ol>

<h2>Remedy</h2>
<ol>
<li>To Be Determined</li>
</ol>
-->
}

It is recommended to also put a deafault.html file inside the Errors folder for debugging purposes:

<h1>No error description available.</h1>
<p>Please consult the troubleshooting manual for more information.</p>

States

In the Client Connection Settings menu you can manage the visualization of your system states.

States

Bar Description
Path In the Path bar you select the path in the parameter tree to your state parameter. Per default this parameter is root/Logic/state.
State Codes In the State Codes bar you place the .json file with your state codes.

State Codes

The state parameter provides a state number. This number can be linked to a .json file file created by the user to show text. Below is a template that gives an example of a states.json file:

{
  "0": "INIT_S",
  "1": "OFF_S",
  "2": "DISENGAGED_S",
  "4": "ENGAGED_S",
  "7": "ESTOP_OFF_S",
}

This section will not cover how to set up a system state structure.
Learn how to create .json files in motorcortex.io here

Logs

the log keeps track of what is going on in the system and can be used for debugging purposes.

logs

Bar Description
Path In the Path bar you select the path in the parameter tree to your log parameter. Per default this parameter is root/Logic/logOut.

Screen

In the Screen Settings menu you can manage the visualization of your screens a GUI can have multiple screens.

Screen

Bar Description
Title In the Title bar you can change the title of your screen.
Start screen In the Start Screen bar you can choose the initial start screen.
delete With the Delete button you can delete a screen. A message will make you confirm deletion.
Visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your screen show up. Per default no path screen will always make a screen show up. It is not possible to change visibility for the start screen.
Slot
Freq divider In the frequency divider you can adjust the screen update rate. The initial value freq divider value is 100.
Group with a Group you can specify a group of parameters used for this screen. For you will find more information about this Here
W In the Width screen you can define the with of all screens. The initial value for the width is 800.
H In the Height screen you can define the with of all screens. The initial value for the Height is 600.
Foreground In the Foreground color you can select the color you want for the foreground of your grid in hex value. The initial value for the hex value is #323c4e.
Background in the Background color you can select the color you want for the Background of your grid in hex value. The initial value for the hex value is #28303e.

Raster

In the Raster Settings menu you can manage the visualization of your raster to aid in placing components.

Raster

Bar Description
Color In the Raster color you can select the color you want for the Raster of your grid in hex value. The initial value for the hex value is #3c475d. The raster does not show up in a finished GUI.
W In the Width bar you can define the width the raster. The initial value for the width is 30.
H In the Height bar you can define the Height the raster. The initial value for the Height is 30.
Show With the Show check box you can make the raster visual.
Snap With the Snap check box you can make the components inside the grid snap to the raster.

2.4.3 - Screens

Create highly interactive user interfaces.

Motorcortex-GRID is a tool to design and deploy highly interactive Human-Machine interfaces (HMI) for MOTORCORTEX applications. GRID has many visualization Widgets that can be placed on a Screen. A HMI can have multiple Screens, that are accessible via the top menu bar.

Screens

The User interface is organized into Screens. A Screen provides a canvas to place your Widgets on. Available Screens are shown in the Top Bar, you can click on the top bar to select the desired Screen.

Widgets can be dragged and dropped onto a Screen from the Library. Properties of the Screen or the selected widget are shown on the right.

Bar Description
Add Screen Button With the Add screen button you can add screens to your GUI.
Edit Screen Button With the Edit Screen Position button you can change the order of your screens.
Screen Button By clicking the screen button the selected screen will be shown.
Time Indicator The Time Indicator will show the controller time. You can find how to change the controller time here.
State Indicator The State Indicator will show the Machine State.
Error Handler Button The Error Handler button will Expand and Collapse the Error Handler screen.

Error Handler Screen

The Error Handler Screen will show the system errors and system logs.

Error Handler Screen

Bar Description
Errors System errors will show up here. Errors can be defined by the user. See Errors Codes to learn how to create your own error codes.
Acknowledge By pressing the acknowledge button the user has confirmed and resolved the error.
Logs Here you can see the system logs.

2.4.4 - Widget Library

A explanation of how to work with Motorcortex Grid

The Widget Library

On the left side of the grid application you will find the Widget Library.

Widget Description
vButton Will add a Button to the Grid
vSwitch Will add a Switch to the Grid
vLight Will add a Indicator Light to the Grid
vLabel Will add a Label to the Grid
box Will add a 3D image to the Grid
vMiniPlot Will add a mini plot to the Grid
vDataPlot Will add a data plot to the Grid
vDivider Will add a divider to the Grid
vOutput Will add a Output to the Grid
vRange Will add a Range slider to the Grid
vInput Will add a Input to the Grid
vImage Will add a Image to the Grid
vHtml Will add a HTML object to the Grid
vFileList Will add a File list to the Grid
vMeter Will add a Meter indicator to the Grid
vJoystick Will add a Joy-stick to the Grid
vGeometry Will add a Geometry to the Grid
vProgram Will add a menu to create a program to the Grid
vCamera Will add a camera screen to the Grid

Input Widgets

Input widgets are used to change parameters in the parameter tree to control your system.

⚠ Using Motorcortex-grid all parameters of the running control system are accessible and may be modified. Changing parameters may cause unpredictable or unstable machine behavior and may cause danger to personnel or cause damage to the machine or its surroundings. The tool should only be used by system experts that have detailed knowledge of the system and that know what the impact of parameter changes is.

Button

When a Button is selected the Inputbox on the right of the screen will start showing the button properties.

Button
Button Settings

Bar Description
PATH This is where you configure the linkage of the parameter you want to manipulate.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches. The raw parameter is called x
label The text inside the button can be changed by changing the label text.
value on The on value can be changed by the user to create a Binary button or set a parameter to a decimal number. Per default buttons are binary.
value Off The on value can be changed by the user to create a Binary button or set a parameter to a decimal number in the off position. Per default buttons are binary.
send Rate The Send Rate determines how many times per second a signal will be send from the button.
font Size The font size determines the size of the text inside the element. This also determines the height of the button.
background The color of the button can be changed by changing the background color.
sticky The Sticky check box makes it possible to create a button that can be only used when the parameter does not change this is handy if a reply of a action is needed.
width The Width of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Switch

When a switch is selected the Inputbox on the right of the screen will start showing the switch properties.

Switch
Switch Settings

Bar Description
PATH This is where you configure the linkage of the parameter you want to manipulate.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
value on The on value can be changed by the user to create a Binary button or set a parameter to a decimal number. Per default buttons are binary.
value Off The on value can be changed by the user to create a Binary button or set a parameter to a decimal number in the off position. Per default buttons are binary.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Range

When a Range is selected the Inputbox on the right of the screen will start showing the range properties.

Range
Range Settings

Bar Description
PATH This is where you configure the linkage of the parameter you want to manipulate.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
FILTER
gain With the gain you can define the gain for the range slider.
offset With the offset you can define a offset for the range slider.
unit Here you can define the units shown in the range slider.
label Here you can define the label/name of your range
min The Min Value is the minimum value that can be selected within the range.
max The Min Value is the maximum value that can be selected within the range.
step The Step size determines the size of steps within the range.
decimals The decimals you can choose how many decimals are shown within the range.
update on The update on options make it possible to update the selected value within the range directly on movement or on release.
width The Width of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Joystick

When a joystick is selected the Inputbox on the right of the screen will start showing the range properties.

Joystick
Joystick Settings

Bar Description
PATH HORIZONTAL This is where you configure the linkage of the parameter you want to manipulate.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
PATH VERTICAL This is where you configure the linkage of the parameter you want to manipulate.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
direction With the direction options you can select what kind of joystick you prefer: only horizontal, only vertical, or for both directions.
send Rate The Send Rate determines how many times per second a signal will be send from the Joystick.
nudge Horizontal A nudge is a arrow on the outside of the joystick. With this bar you can determine the value the joystick will send when pressing a horizontal nudge.
nudge Vertical A nudge is a arrow on the outside of the joystick. With this bar you can determine the value the joystick will send when pressing a vertical nudge.
deadzone The dead zone is the zone of the joystick were it will not respond when dragging it.
radius The radius of the joystick determines the size of the joystick.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Input

When a input is selected the Inputbox on the right of the screen will start showing the range properties.

Input
Input Settings

Bar Description
PATH This is where you configure the linkage of the parameter you want to manipulate.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
FILTER
gain With the gain you can define the gain for the input.
offset With the offset you can define a offset for the input.
unit Here you can define the units shown in the input.
step The step size determines the step size of the + and - button in the Input.
font Size The font size determines the size of the text inside the element.
font Weight The min value is the minimum value that can be selected within the range.
line Height The Line height determines the height of the input box.
decimals The amount of decimals shown can be determined by changing this value.
min The min value is the minimal value possible for this input. If no value is defined there is no minimal value.
max The max value is the maximum value possible for this input. If no value is defined there is no maximum value.
width The Width of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Output Widgets

Light

When a input is selected the Inputbox on the right of the screen will start showing the range properties.

Light
Light Settings

Bar Description
PATH This is where you configure the linkage of the parameter you want to manipulate.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
label The text shown in a element can be changed by changing the label.
font Size The text size of a label can be changed by the font size.
line Height The Line height determines the height of the light box.
color On The color when the light is on is determined in this color box.
color Off The color when the light is off is determined in this color box.
width The Width of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Meter

Meter
Meter Settings

Bar Description
PATH This is where you configure the linkage of the parameter you want to manipulate.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
orientation The meter can be oriented Horizontally or Vertically.
show Value The value inside of the meter can be shown continuously by checking the Show Value check box.
decimals The amount of Decimals of the shown value is determined here.
size The size of the meter can be defined here.
MIN
input For the input you can determine if it is either a static value or a path.
value Here you determine what the minimum value of the brake is.
color Here you determine the color of the meter brake.
show Label The show label check box makes it possible to show the minimum value of a brake.
BREAK 1
input For the input you can determine if it is either a static value or a path.
value Here you determine what the minimum value of the brake is.
color Here you determine the color of the meter brake.
show Label The show label check box makes it possible to show the minimum value of a brake.
BREAK 2
input For the input you can determine if it is either a static value or a path.
value Here you determine what the minimum value of the brake is.
color Here you determine the color of the meter brake.
show Label The show label check box makes it possible to show the minimum value of a brake.
BREAK 3
input For the input you can determine if it is either a static value or a path.
value Here you determine what the minimum value of the brake is.
color Here you determine the color of the meter brake.
show Label The show label check box makes it possible to show the minimum value of a brake.
BREAK 4
input For the input you can determine if it is either a static value or a path.
value Here you determine what the minimum value of the brake is.
color Here you determine the color of the meter brake.
show Label The show label check box makes it possible to show the minimum value of a brake.
BREAK 5
input For the input you can determine if it is either a static value or a path.
value Here you determine what the minimum value of the brake is.
color Here you determine the color of the meter brake.
show Label The show label check box makes it possible to show the minimum value of a brake.
Max
input For the input you can determine if it is either a static value or a path.
value Here you determine what the minimum value of the brake is.
color Here you determine the color of the meter brake.
show Label The show label check box makes it possible to show the minimum value of a brake.
x The X position of a element is defined here.
y The Y position of a element is defined here.
x The Z position of a element is defined here.

Miniplot

Button
Button Settings

Bar Description
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
frequency divider With the frequency divider you can reduce the rate at which the server publishes its data. The server update rate is divided by this value; e.g. if the server has an update rate of 1000 Hz, a frequency divider of 100 will make the publisher send only every 100th sample, resulting in an update rate of the received data of 10 Hz.
time range The Time Range of the mini plot can be defined here.
y min The minimum Y value is determined here.
y max The maximum Y value is determined here.
PATH 1
color Here you determine the color of your plot line.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
PATH 2
color Here you determine the color of your plot line.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
PATH 3
color Here you determine the color of your plot line.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
PATH 4
color Here you determine the color of your plot line.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
PATH 5
color Here you determine the color of your plot line.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
width The Width of the Mini plot can be defined here.
height The Height of the Mini plot can be defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Dataplot

Button
Button Settings

Bar Description
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
title The title of the Plot can be defined here.
data Here you can choose your .csv or .json file containing the data for the plot.
xcol In the xcol you determine the column-index from the .csv or .json file to be shown as the x-axis of the plot. E.g. 0
ycol In the ycol you determine the column-indices from the .csv or .json file to be used for the values on the y-axis of the plot. E.g. [1,2,3]
xlabel The text inside the button can be changed by changing the label text.
ylabel The min value is the minimum value that can be selected within the range.
autoscale Y The Auto scale check box makes it possible to automatically scale the Y axis of the plot.
rangeslider X The step size determines the size of steps within the range.
y min The minimum Y axis value for the plot is determined here.
y max The maximum Y axis value for the plot is determined here.
plotstyle See the documentation of Plotly https://plotly.com/javascript/reference/layout/
plotlayout See the documentation of Plotly https://plotly.com/javascript/reference/layout/
refresh every Here you select how many times the plot gets refreshed per seconds.
show legend The Show legend check box makes it possible to turn on or off the legend of the plot.
color Here you determine the color of your plot line.
width The Width of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Output

Button
Button Settings

Bar Description
PATH This is where you configure the linkage of the parameter you want to manipulate.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
map Here you can select the .json file that provides a mapping between the parameter value and a string.
unit Here you can define the output unit string.
decimals
color
font size The text size inside the output can be changed by changing the font size.
font weight The font weight can be changed here to: bold.
allign Here you can select the alignment of the output text to the left/center or right.
line height Here you can determine the line height of the output element.
hexadecimal By checking the hexadecimal box you can have the output shown as a hexadecimal number.
width The Width of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

3D

Button
Button Settings

Bar Description
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
frequency divider With the frequency divider you can reduce the rate at which the server publishes its data. The server update rate is divided by this value; e.g. if the server has an update rate of 1000 Hz, a frequency divider of 100 will make the publisher send only every 100th sample, resulting in an update rate of the received data of 10 Hz.
time range The Time Range of the mini plot can be defined here.
model Here you select your 3D file inside From your project inside Motorcortex.io
PAIR GEOMETRY Pair this widget with the geometry widget to visualize geometry items in this 3D widget.
width The Width of a element is defined here.
height The Height of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Image

Button
Button Settings

Bar Description
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
PATH This is where you configure the linkage of the parameter you want to manipulate.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here.
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
file Here you can choose the file you want to be shown in your user interface.
json index Here you can select the .json file that provides a mapping between the parameter value and a image.
width The Width of a element is defined here.
height The Height of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Camera

Button
Button Settings

Bar Description
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
subsctiption group In the Path bar you select the path in the parameter tree to link with this element.
Camera size
Camera resolution
Camera image
frequency divider The text inside the button can be changed by changing the label text.
use webcam Checking the Use Web cam box will make automatically use of the users web cam (make sure you allow your computer to do this.)
show FPS Checking the Show FPS box will how how much Frames Per Second are shown inside the Camera element.
width The Width of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Other Widgets

Divider

Button
Button Settings

Bar Description
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
horizontal In the Path bar you select the path in the parameter tree to link with this element.
color The color of the divider can be changed by clicking this box
size The Width of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

HTML

HTML
HTML Settings

Bar Description
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
html In the Path bar you select the path in the parameter tree to link with this element.
font size The text size inside the output can be changed by changing the font size.
font weight The font weight can be changed here to: bold.
line height Here you can determine the line height of the output element.
background Here you can define the background color of your HTML element.
color The text inside the button can be changed by changing the label text.
width The Width of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

File List

Button
Button Settings

Bar Description
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
folder Url The URL of the folder that contains the files to be shown in the list. The list must be provided by the web server in json format. In NGINX you specify this by adding the following attributed to the location section of your folder: location /log { autoindex on; autoindex_format json; }
show date If enabled, shows the creation date of the file
show size If enabled, shows the size of the file. If you specify the nginx attribute “autoindex_exact_size off;", the size will be shown in in compact form (e.g. “1.2 Mb”).
width The Width of a element is defined here.
height The Height of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Geometry

Button
Button Settings

Bar Description
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
pair program Pair this widget with the program widget to be able to add geometry point) to your program.
cart path Path to the actual Cartesian tool coordinates. When the Teach button of the widget is used these coordinates are sowed into the geometry point (usually: root/Control/actualToolCoordinates)
joint path Path to the actual joint coordinates. When the Teach button of the widget is used these coordinates are stored into the geometry point (usually: root/Control/actualJointPositionsFiltered)
mode command path Path to the mode command (usually: root/Logic/modeCommand)
semiAuto path Path to the signal to activate Semi-auto mode: (usually: root/Control/activateSemiAuto)
semiAuto target path Path where the Semi-auto move will move to, when using the MovoTo button. (usually: root/Control/semiAutoMotionGenerator/target)
background color The background color
width The Width of a element is defined here.
height The Height of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

Program

Button
Button Settings

Bar Description
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
PAIR GEOMETRY Pair this widget with the geometry widget to be able to add geometry point) to your program.
current command ID path The path to the current Motion Interpreter Command (usually: root/MotionJSInterpreter/currentCommandId)
current program ID path The path to the current Motion Interpreted Program (usually: root/MotionJSInterpreter/currentProgramId)
storage folder This is the location where Programs are stored relative to the current project path. (usually: /programs)
width The Width of a element is defined here.
height The Height of a element is defined here.
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

ColorPick

Button
Button Settings

Bar Description
PATH This is where you configure the linkage of the parameter you want to manipulate.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path In the Path bar you select the path in the parameter tree to link with this element.
channel If a selected parameter is a array you can select the desired channel of the array here
VISIBILITY This is where you configure the visibility of the this element.
visibility In the Visibility bar you can select the Parameter in the Parameter tree that will make this your element show up. Per default no path will always make a element show up.
prefix In the prefix you fill in the path of a parameter. A prefix is mainly useful for editing multiple paths of parameters.
path This Path manipulates the visibility of the element and can be selected from the parameter tree.
channel If a selected parameter is a array you can select the desired channel of the array here
expression With the expression you can manipulate the presentation of the output For example convert Meters to Inches (The raw parameter is called x).
x The X position of a element is defined here.
y The Y position of a element is defined here.
z The Z position of a element is defined here.

2.4.5 - Special Files

Introduction

It is possible to create complete custom GUI using motorcortex grids. To do this some special files are needed in the project folder to deploy to the Motorcortex controller. This section will show how to make and customize these special files.

2.4.5.1 - 3D-Models

Adding a 3D Model (Digital Twin) to GRID

Video Tutorial

See how easy it is to create and link a 3D model to a MOTORCORTEX application:

Introduction

The GRID 3D widget supports 3D models in GLTF format. GLTF is an open 3D format maintained by the Khronos Group. More information on the format can be found here: https://www.khronos.org/gltf/.

A lot of 3D modeling and CAD tools support exporting a model in GLTF format natively and these models can be use in the 3D widget directly.

A couple of guidelines are important to make the 3D model work properly:

  1. Binary output format (.glb) is preferred because of more efficient storage and smaller file sizes.
  2. Model size should be below 10 MB for optimal performance on lower end devices like tablets.
  3. Enabling shadows are expensive (cost a lot of computing power), especially when using complex scenes.
  4. Make sure your model has the Z-axis pointing up, also make sure the exporter keeps the z-axis up (some exporters make the y-axis point up). The 3D widgets camera navigation relies on this “z is up” convention to function properly.

Creating 3D models with Blender

Blender is an extremely capable open-source 3D modeler that is ideal for creating 3D models for use in GRID. You can download Blender for your favorite platform from the Blender website: https://www.blender.org/. Here you can also find excellent modeling tutorials that help you get started.

When modeling a Digital Twin in Blender there are some important guidelines:

  1. The GLTF exporter currently silently renames objects that contain spaces or other special character (like period (".")). This is a problem for objects that you want to link later to motorcortex parameters. Especially avoid putting spaces in Object names, since this will have unexpected results in the 3D view. Periods are okay, but you need to know that they are removed in the GLTF export; “Cube.001” will become Cube001 in the GLTF file.
  2. In GRID all transforms are done in the object’s local axis frame.
  3. You can connect your objects together by “parenting” them, the child has then a local axis frame that moves together with its parent object.
  4. Make sure your object Origin is located at the desired rotation point. One way to change an objects origin in Blender is to first position the 3D Cursor at the desired location and then “Origin to 3D Cursor” from the Object menu.
  5. Also make sure to “Apply Rotation” and “Apply Scale” to all your moving objects to avoid some strange behavior later.
  6. When exporting to GLTF from Blender, make sure the “+Y Up” in the “Transform” section of the exporter settings is Off.
  7. If you are using Object Modifiers, make sure you select “Apply Modifiers” in the “Geometry” section of the GLTF Exporter.

Using a GLTF file in GRID

To use a GLTF file in the GRID 3D Widget the following steps are required:

  1. Upload your GLTF file(s) in either .gltf or .glb format to your project. You can place you models in a subfolder if that is preferred.
  2. Create a new JSON configuration file, specifying some additional properties of the objects and linking object properties to MOTORCORTEX parameters. See below for an example. You can download the JSON schema here v-3d-schema.json. In the JSON you can add references to your model files that should be loaded by the 3D widget.
  3. In GRID, add a 3D widget to your canvas and in the “model” property select the JSON file.

Here is an example of a minimalistic JSON file:

{
  "files": [
    {
      "file": "cube.glb"
    }
  ],
  "objects": [
    {
      "name": "Cube",
      "links": [
        {
          "link": "root/Control/dummyDouble",
          "axis": "rz"
        }
      ]
    }
  ]
}

An example of a more complex JSON file:

{
  "files": [
    {
      "file": "scenery.glb",
      "name": "scenery"
    },
    {
      "file": "robot.glb",
      "name": "robot"
    }
  ],
  "camera": "Camera",
  "cameraLookAt": {
    "x": 0.0,
    "y": 0.0,
    "z": 0.5
  }
  "hemisphereLight": {
    "intensity": 0.8
  },
  "spotLight": {
    "x": 1,
    "y": 1,
    "z": 5.8,
    "castShadow": true,
    "angle": 0.5,
    "intensity": 0.2,
    "penumbra": 1.5
  },
  "traceLine": [
    {
      "link": "root/Control/actualToolCoordinates",
      "channel": 0,
      "axis": "x"
    },
    {
      "link": "root/Control/actualToolCoordinates",
      "channel": 1,
      "axis": "y"
    },
    {
      "link": "root/Control/actualToolCoordinates",
      "channel": 2,
      "axis": "z"
    }
  ],
  "objects": [
    {
      "name": "Floor",
      "receiveShadow": true,
      "castShadow": false
    },
    {
      "name": "Base",
      "receiveShadow": false,
      "castShadow": true
    },
    {
      "name": "Link1",
      "castShadow": true,
      "links": [
        {
          "link": "root/Control/dummyDoubleArray6",
          "channel": 0,
          "axis": "rz"
        },
        {
          "link": "root/Control/dummyDoubleArray6",
          "channel": 4,
          "axis": "opacity",
          "gain": 1,
          "value": 1
        },
        {
          "link": "root/Control/dummyBool",
          "axis": "visible"
        }
      ]
    },
    {
      "name": "Link2",
      "links": [
        {
          "link": "root/Control/dummyDoubleArray6",
          "channel": 1,
          "axis": "rz"
        }
      ],
      "castShadow": true
    }
  ]
}

2.4.5.2 - Output to Text Map

A file to map a value to text for an Output Widget

2.4.6 - GUI Example

A example for creating a Motorcortex GUI

A Motorcortex gui is loaded from a .grid file. you can create these files in Motorcortex Grids located in the Motorcortex.io portal.

3 - Developing Client Applications

Motorcortex is especially created to allow easy and high-performance data exchange and interaction with real-time control systems, from any operating system or device and using a programming language of your choice. Currently ready-made APIs are created for JavaScript, C++ and Python more languages will follow.

Using these API’s the user can create scripts to control a Motorcortex application . Doing this a user can create:

  • Robot control scripts
  • Data acquisition/analysis logs tools
  • Automatic test scripts/reports

In a Motorcortex application all Modules and variables are organized in a tree structure; the Parameter Tree. The Parameter Tree is used to communicate data between tasks and to the outside world in a thread-safe manner.

The Communication Server provided by Motorcortex has two parts:

  1. The first part is a Signaling Server which uses a Request/Reply reliable messaging pattern. A Signaling Server is required for Remote Procedure Calls and for managing the control application, for example updating parameter values. It is also responsible for managing the Publishing Server.
  2. The second part is a Publishing Server or Publisher which uses a Publish/Subscribe besteffort delivery messaging pattern. The Publishing Server can organize data into groups and publish them with the requested frequency. The Publisher is used to send Real-time data continuously.

3.1 - Python

3.1.1 - MCX-Python Installation

This chapter will explain how to install mcx-python. Please select the operating system you are u using:

Linux Linux Windows Windows Windows MacOS

Installing Motorcortex-Python for Linux

Installing Python 3.7 or lower

Python 3 should already be installed by default on your modern Linux distribution.

  1. Check if your version is Python 3.7 or lower.
python --version

If the version is 3.7 or below, you are good to go.

  1. If the version is 3.8 or higher, install Python 3.7 and set it as default. This is done by following the actions below.
sudo apt install python3.7
sudo update-alternatives --config python
  1. The last command will show you an error:
“update-alternatives: error: no alternatives for python”.
  1. Run the commands below, where instead of “3.x” you fill-in the version is you obtained when running python –version.
sudo update-alternatives --install /usr/bin/python python
/usr/bin/python**3.x** 1

sudo update-alternatives --install /usr/bin/python python
/usr/bin/python3.6 2
  1. After that run the command below and select python 3.7.
sudo update-alternatives --config python

Installing Motorcortex-Python

motorcortex-python can be installed by using the pip tool.

  1. To be able to use pip to install python packages this first needs to be installed:
sudo apt install python3-pip
  1. Then download, build and install the motorcortex-python package via pip.
sudo -H pip3 install motorcortex-python

This will install motorcortex-python for Python3 for all users.

Installation Instructions using virtual environment

MOTORCORTEX-python can also be installed inside a virtual environment. This can be useful if your system has a different python environment that the one required for MOTORCORTEX or if you would like to keep the MOTORCORTEX-python tools separate from the rest of the system for security reasons. A Virtual Environment, is an isolated working copy of Python which allows you to work on a specific project without worry of affecting other projects.

Installing Virtualenv

  1. Check if virtual environment is already installed on your system you can check this using the following command:
virtualenv --version
  1. If you see a version number for instance 1.6.1 it is already installed. If not you will have to install Vitrualenv:
sudo apt-get install virtualenv

Setting up Vitrualenv

  1. You will need a directory for your virtual enviroment. You may choose any location you desire:
mkdir ~/virtualenvironment
  1. To create a folder for your new app that includes a clean copy of Python3 run:
virtualenv -p python3 ~/virtualenvironment/mcx-env
  1. We have created this new folder called mcx-env. To begin cd into your new project:
cd ~/virtualenvironment/mcx-env/bin
  1. Now you are in your virtual environment folder you can activate your virtual environment:
source activate
  1. Notice your prompt will have a shell in this case (mcx-env). If you would like to leave your virtual environment type the following command:
deactivate

Installing Motorcotex-Python in Vitrualenv

  1. Motorcortex-python can be installed by using the “pip” tool. download, build and install the motorcortex-python package via pip.
pip3 install motorcortex-python

Motorcortex-python is now installed in your virtual environment.

3.1.2 - MCX-Python Examples

Getting Started with motorcortex-python

Using motorcortex-python a user can create:

  • Robot control scripts
  • Data acquisition/analysis logs tools
  • Automatic test scripts/reports

Connecting to a motorcortex server and logging in

Motorcortex now supports WebSocket Security (wss), which requires a certificate (public key) on the client, for it to be able to connect. In general every MOTORCORTEX server application should have its own certificate, such that access can be restricted to those clients that have a copy of the correct certificate installed. It is not recommended to share the same certificate between multiple servers or machines/robots.

Install the certificate that matches your server certificate (in the example below it is “motorcortex.crt”) to your client. When connecting, this certificate needs to be loaded.

The following code example shows how to connect an log-in to a motorcortex application:

# import the motorcortex library
import motorcortex
# Create a parameter tree object
parameter_tree = motorcortex.ParameterTree()
# Open request and subscribe connection
try:
  req, sub = motorcortex.connect("wss://localhost:5568:5567", motorcortex.MessageTypes(), parameter_tree,
                                   certificate="mcx.crt.pem", timeout_ms=1000,
                                   login="root", password="secret")
  tree = parameter_tree.getParameterTree()
  print(f"Parameters: {tree}")

except RuntimeError as err:
    print(err)

Getting the parameter tree

The first thing to do after a successful connection to the motorcortex server is to get a list of all the available parameters. Note that the availability of parameters depends on the user level of the connected user.

# Requesting the parameter tree
param_tree_reply = req.getParameterTree()
param_tree_reply_msg = param_tree_reply.get(10)
if param_tree_reply_msg:
 print("Parameter tree received")
else:
 print("Failed to receive parameter tree")
parameter_tree.load(param_tree_reply_msg)

Or using a more javascript like then/catch:

# Alternative method for requesting a parameter tree (javascript-like then/catch)
param_tree_reply = req.getParameterTree()
value = param_tree_reply.then(lambda x: print("Parameter tree received")).catch(
lambda g: print("Failed to receive parameter tree")).get()
# load parameter tree into the previously initialized (but empty) variable
parameter_tree.load(param_tree_reply_msg)

Request/Reply

To get a value for a certain parameter from the server use:

get_param_reply_msg = req.getParameter('path/to/variable').get()
print("nget_param_reply_msg:")
print(get_param_reply_msg)

The value is stored in get_param_reply_msg.value which is always a tuple of values, even if the value is a scalar (which can be accessed via get_param_reply_msg.value[0]).

To set a scalar value use:

set_param_reply_msg = req.setParameter('path/to/variable',
True).get()
print("nset_param_reply_msg:")
print(set_param_reply_msg)

To set an array of values use:

req.setParameter('path/to/array',
[1,2,3,4]).get()

To set a number of parameters at once:

paramlist_to_set = [{'path': 'root/Control/dummyBool',
'value': False},
 {'path': 'root/Control/dummyDoubleArray6', 'value': [4,3,2,1]}]
req.setParameterList(paramlist_to_set).get()

Subscribe to a datastream

To receive a continuous stream of values for a set of parameters as subscription can be created. The client application can bundle the desired parameters in a group. The complete group is sent by the server in a single packet and all signals in the group are therefore synchronized.

The client can create multiple subscriptions for different groups, for instance at different data-rates (by setting the “divider” parameter differently for different groups).

The group name is shared between clients and a group is published by the server once to all clients that have subscription to the group with that name. This way the communication can easily scale across large numbers of clients.

If a group name already exists on the server and another client requests a subscription to a set of signals with the same group name, the server adds any requested signals that are not already in the group to the group. The other clients using the same group name will then also receive the additional signals.

The motorcortex-python library makes it convenient to add subscriptions and handle the processing of the received data. Every subscription has a callback function associated with it, where the data can be processed and stored. Creating a subscription also created a new sub-process that handles the reception of data asynchronously to the main application.

Below is an example of how to create an handle a subscription.

# Define the callback function that will be called whenever a message is received
def messageReceived(parameters):
    for cnt in range(0, len(parameters)):
    param = parameters[cnt]
    timestamp = param.timestamp.sec + param.timestamp.nsec * 1e-9
    value = param.value
    # print the timestamp and value; convert the value to a string first
    # so we do not need to check all types before printing it
    print('%f %s' % (timestamp, str(value)))

# Open subscribe connection
sub = motorcortex.Subscribe(req, motorcortex_types)
if sub.connect("ws://192.168.2.100:5557"):
    print("Subscribe connection is etablished")
else:
    print("Failed to establish connection")
# define the paths to subscribe to
paths = ['path/to/variable1', 'path/to/variable2']
# define the frequency divider that tells the server to publish only every
# n-th sample. This depends on the update rate of the publisher.
divider = 10
# subscribe and wait for the reply with a timeout of 10 seconds
subscription = sub.subscribe(paths, 'group1', divider)
# set the callback function that handles the received data
# Note that this is a non-blocking call, starting a new thread that handles
# the messages. You should keep the application alive for a s long as you need to
# receive the messages
subscription.notify(messageReceived)
# the main application should wait or do something else while the subscription
# is active
import time # Should be at top of script)
time.sleep(10)
# close the subscription when done
sub.close()

Note: When testing with multiple users on a single application make sure to use different group names to avoid confusion between users.

Recovering a lost connection

The Motorcortex library handles temporary lost connections automatically. The client does not have to handle this. However, if the server is restarted, the client cannot automatically reconnect because the server has created a new session-id. The client may handle this case by discarding the old connection and creating a new connection and log-in again.

Closing a connection

req.close()

3.1.3 - MCX-Python API

motorcortex

statusToStr

statusToStr(motorcortex_msg, code)

Converts status codes to a readable message.

Arguments:

  • motorcortex_msg(Module) - refernce to a motorcortex module
  • code(int) - status code

Returns:

  • str - status message

Examples:

login_reply = req.login(“admin”, “iddqd”) login_reply_msg = login_reply.get() if login_reply_msg.status != motorcortex_msg.OK: print(motorcortex.statusToStr(motorcortex_msg, login_reply_msg.status))

motorcortex.motorcortex_pb2

motorcortex.subscription

timespec

Timestamp of the parameter

Arguments:

  • sec(int) - seconds
  • nsec(int) - nanoseconds

Parameter

Parameter value with a timestamp

Arguments:

  • timestamp(timespec) - Parameter timestamp
  • value(any) - Parameter value

Subscription Objects

class Subscription(object)

Subscription class represents a group of parameters.

It returns the latest values and a timestamp of the group.

Subscription class could be used as an observer, which notifies on every update or could be used as polling.

id

 | id()

Returns:

  • int - subscription identifier

alias

 | alias()

Returns:

  • str - group alias

read

 | read()

Read the latest values of the parameters in the group.

Returns:

  • list(Parameter) - list of parameters

layout

 | layout()

Get a layout of the group.

Returns:

  • list(str) - ordered list of the parameters in the group

done

 | done()

Returns:

  • bool - True if the call was successfully cancelled or finished running.

Examples:

subscription = sub.subscribe(“root/logger/logOut”, “log”) while not subscription.done(): time.sleep(0.1)

get

 | get(timeout_sec=1.0)

Returns:

  • bool - StatusMsg if the call was successfully, None if timeout happened.

Examples:

subscription = sub.subscribe(“root/logger/logOut”, “log”) done = subscription.get()

then

 | then(subscribed_clb)

JavaScript-like promise, which is resolved when subscription is completed.

Arguments:

  • subscribed_clb - callback which is resolved when subscription is completed.

Returns:

self pointer to add ‘catch’ callback

Examples:

subscription = sub.subscribe(“root/logger/logOut”, “log”) subscription.then(lambda val: print(“got: %s”%val)).catch(lambda d: print(“failed”))

catch

 | catch(failed)

JavaScript-like promise, which is resolved when subscription has failed.

Arguments:

  • failed - callback which is resolved when subscription has failed

Returns:

self pointer to add ‘then’ callback

Examples:

subscription = sub.subscribe(“root/logger/logOut”, “log”) subscription.catch(lambda d: print(“failed”)).then(lambda val: print(“got: %s”%val))

notify

 | notify(observer_list)

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

Arguments:

  • observer_list - a callback function (or list of callback functions) to notify when new values are available

Examples:

def update(parameters): print(parameters) list of Parameter tuples

data_sub.notify(update)

motorcortex.subscribe

Subscribe Objects

class Subscribe()

Subscribe class is used to receive continuous parameter updates from motorcortex server.

Subscribe class simplifies creating and removing subscription groups.

Arguments:

  • req(Request) - reference to a Request instance
  • protobuf_types(MessageTypes) - reference to a MessageTypes instance

connect

 | connect(url, **kwargs)

Open a subscribe connection.

Arguments:

  • url(str) - motorcortex server URL

Returns:

  • bool - True - if connected, False otherwise

close

 | close()

Close connection to the server

subscribe

 | subscribe(param_list, group_alias, frq_divider=1)

Create a subscription group for a list of the parameters.

Arguments:

  • param_list(list(str)) - list of the parameters to subscribe to
  • group_alias(str) - name of the group
  • frq_divider(int) - frequency divider is a downscaling factor for the group publish rate

Returns:

  • Subscription - 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.

unsubscribe

 | unsubscribe(subscription)

Unsubscribe from the group.

Arguments:

  • subscription(Subscription) - subscription handle

Returns:

  • Reply - Returns a Promise, which resolves when the unsubscribe operation is complete, fails otherwise.

motorcortex.parameter_tree

ParameterTree Objects

class ParameterTree(object)

This class represents a parameter tree, obtained from the server.

Reference to a parameter tree instance is needed for resolving parameters, data types and other information to build a correct request message.

load

 | load(parameter_tree_msg)

Loads a parameter tree from ParameterTreeMsg received from the server

Arguments:

  • parameter_tree_msg(ParameterTreeMsg) - parameter tree message from the server

Examples:

parameter_tree = motorcortex.ParameterTree() parameter_tree_msg = param_tree_reply.get() parameter_tree.load(parameter_tree_msg)

getParameterTree

 | getParameterTree()

Returns:

  • list(ParameterInfo) - a list of parameter descriptions

getInfo

 | getInfo(parameter_path)

Arguments:

  • parameter_path(str) - path of the parameter

Returns:

  • ParameterInfo - parameter description

getDataType

 | getDataType(parameter_path)

Arguments:

  • parameter_path(str) - path of the parameter

Returns:

  • DataType - parameter data type

motorcortex.request

Request Objects

class Request(object)

login

 | login(login, password)

Send a login request to the server

Arguments:

  • login(str) - user login

  • password(str) - user password

    Results:

  • Reply(StatusMsg) - A Promise, which resolves if login is successful and fails otherwise. Returned message has a status code, which indicates a status of the login.

Examples:

login_reply = req.login(‘operator’, ‘iddqd’) login_msg = login_reply.get() if login_msg.status == motorcortex_msg.OK print(‘User logged-in’)

getParameterTreeHash

 | getParameterTreeHash()

Request a parameter tree hash from the server.

Returns:

  • Reply(ParameterTreeMsg) - A Promise, which resolves when parameter tree hash is received or fails otherwise. ParameterTreeHashMsg message has a status field to check the status of the operation.

Examples:

param_tree_hash_reply = req.getParameterTreeHash() value = param_tree_hash_reply.get()

getParameterTree

 | getParameterTree()

Request a parameter tree from the server.

Returns:

  • Reply(ParameterTreeMsg) - A Promise, which resolves when parameter tree is received or fails otherwise. ParameterTreeMsg message has a status field to check the status of the operation.

Examples:

param_tree_reply = req.getParameterTree() value = param_tree_reply.get() parameter_tree.load(value)

save

 | save(path, file_name)

Request a server to save a parameter tree to file.

Arguments:

  • path(str) - path where to save
  • file_name(str) - file name

Returns:

  • Reply(StatusMsg) - A promise, which resolves when save operation is completed, fails otherwise.

setParameter

 | setParameter(path, value, type_name=None)

Set new value to a parameter with given path

Arguments:

  • path(str) - parameter path in the tree
  • value(any) - new parameter value
  • type_name(str) - type of the value (by default resolved automatically)

Returns:

  • Reply(StatusMsg) - A Promise, which resolves when parameter value is updated or fails otherwise.

Examples:

reply = req.setParameter(“root/Control/activateSemiAuto”, False) reply.get() reply = req.setParameter(“root/Control/targetJointAngles”, [0.2, 3.14, 0.4]) reply.get()

setParameterList

 | setParameterList(param_list)

Set new values to a parameter list

Arguments:

  • param_list([{'path'-str,'value'-any}]) - a list of the parameters which values update

Returns:

  • Reply(StatusMsg) - A Promise, which resolves when parameters from the list are updated, otherwise fails.

Examples:

req.setParameterList([ {‘path’: ‘root/Control/generator/enable’, ‘value’: False}, {‘path’: ‘root/Control/generator/amplitude’, ‘value’: 1.4}])

getParameter

 | getParameter(path)

Request a parameter with description and value from the server.

Arguments:

  • path(str) - parameter path in the tree.

Returns:

  • Reply(ParameterMsg) - Returns a Promise, which resolves when parameter message is successfully obtained, fails otherwise.

Examples:

param_reply = req.getParameter(‘root/Control/actualActuatorPositions’) param_full = param_reply.get() # Value and description

getParameterList

 | getParameterList(path_list)

Get description and values of requested parameters.

Arguments:

  • path_list(str) - list of parameter paths in the tree.

Returns:

  • Reply(ParameterListMsg) - A Promise, which resolves when list of the parameter values is received, fails otherwise.

Examples:

params_reply = req.getParameter([‘root/Control/joint1’, ‘root/Control/joint2’]) params_full = params_reply.get() # Values and descriptions print(params_full.params)

overwriteParameter

 | overwriteParameter(path, value, force_activate=False, type_name=None)

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.

Arguments:

  • path(str) - parameter path in the tree
  • value(any) - new parameter value
  • force_activate(bool) - forces new value to stay active. (by default is set to ‘False’)
  • type_name(str) - type of the value (by default resolved automatically)

Returns:

  • Reply(StatusMsg) - A Promise, which resolves when parameter value is updated or fails otherwise.

Examples:

reply = req.overwriteParameter(“root/Control/dummyBool”, False, True) reply.get()

releaseParameter

 | releaseParameter(path)

Deactivate overwrite operation of the parameter.

Arguments:

  • path(str) - parameter path in the tree

Returns:

  • Reply(StatusMsg) - A Promise, which resolves when parameter value is released or fails otherwise.

Examples:

reply = req.releaseParameter(“root/Control/dummyBool”) reply.get()

createGroup

 | createGroup(path_list, group_alias, frq_divider=1)

Create a subscription group for a list of the parameters.

This method is used inside Subscription class, use subscription class instead.

Arguments:

  • path_list(list(str)) - list of the parameters to subscribe to
  • group_alias(str) - name of the group
  • frq_divider(int) - frequency divider is a downscaling factor for the group publish rate

Returns:

  • Reply(GroupStatusMsg) - A Promise, which resolves when subscription is complete, fails otherwise.

removeGroup

 | removeGroup(group_alias)

Unsubscribe from the group.

This method is used inside Subscription class, use subscription class instead.

Arguments:

  • group_alias(str) - name of the group to unsubscribe from

Returns:

  • Reply(StatusMsg) - A Promise, which resolves when the unsubscribe operation is complete, fails otherwise.

motorcortex.reply

Reply Objects

class Reply(object)

Reply handle is a JavaScript-like Promise.

It is resolved when reply is received with successful status and fails otherwise.

get

 | get(timeout_ms=None)

A blocking call to wait for the reply and returns a value.

Arguments:

  • timeout_ms(integer) - timeout for reply in milliseconds

Returns:

A protobuf message with a parameter description and value.

Examples:

param_tree_reply = req.getParameterTree() value = param_tree_reply.get()

done

 | done()

Returns:

  • bool - True if the call was successfully cancelled or finished running.

then

 | then(received_clb, *args, **kwargs)

JavaScript-like promise, which is resolved when reply is received.

Arguments:

  • received_clb - callback which is resolved when reply is received.

Returns:

self pointer to add ‘catch’ callback

Examples:

param_tree_reply.then(lambda reply: print(“got reply: %s”%reply)) .catch(lambda g: print(“failed”))

catch

 | catch(failed_clb, *args, **kwargs)

JavaScript-like promise, which is resolved when receive has failed.

Arguments:

  • failed_clb - callback which is resolved when receive has failed

Returns:

self pointer to add ‘then’ callback

Examples:

param_tree_reply.catch(lambda g: print(“failed”)).then(lambda reply: print(“got reply: %s”%reply))

motorcortex.message_types

ParameterMsg

Data type which represents parameter description and value

ParameterListMsg

Data type which represents a list of parameters with descriptions and values

MessageTypes Objects

class MessageTypes(object)

Class for handling motorcortex data types, loads proto files 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.

motorcortex

 | motorcortex()

Returns default motorcortex messages, provided with the package. System messages could be replaced at runtime with a newer version, by load([{‘proto’: ‘path to the new message proto’, ‘hash’: ‘path to the new message hash’}])

Returns:

returns motorcortex messages

load

 | load(proto_hash_pair_list=None)

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

Arguments:

  • proto_hash_pair_list([{'hash'-str,'proto'-str}]) - list of hash and proto messages

Returns:

  • list(Module) - list of loaded modules with protobuf messages.

Examples:

motorcortex_msg, motionsl_msg = motorcortex_types.load( # motorcortex hashes and messages [{‘proto’: ‘./motorcortex-msg/motorcortex_pb2.py’, ‘hash’: ‘./motorcortex-msg/motorcortex_hash.json’}, # robot motion hashes and messages {‘proto’: ‘./motorcortex-msg/motionSL_pb2.py’, ‘hash’: ‘./motorcortex-msg/motionSL_hash.json’}])

createType

 | createType(type_name)

Returns an instance of the loaded data type given type name.

Arguments:

  • type_name(str) - type name

Returns:

an instance of the requested type.

getTypeByHash

 | getTypeByHash(id)

Returns a data type given its hash.

Arguments:

  • id(int) - type hash

Returns:

requested data type.

getTypeByName

 | getTypeByName(name)

Returns a data type given its name.

Arguments:

  • name(str) - type name

Returns:

requested data type.

getNamespace

 | getNamespace(name)

Returns a module/namespace with data types.

Arguments:

  • name(str) - module name

Returns:

requested module

Examples:

loading module motion_spec

MotionSpecType = motorcortex_types.getNamespace(“motion_spec”)

instantiating a motion program from the module

motion_program = MotionSpecType.MotionProgram()

decode

 | decode(wire_data)

Decodes data received from the server

encode

 | encode(proto_data)

Encodes data to send to the server

motorcortex.setup_logger

3.1.4 - MCX-Python-Tools

3.1.4.1 - Data Analysis Tools

Motorcortex is capable of providing huge amounts of data. It can be very convinient using python tools to proces this data and create plots for example.

Installing required Python Libraries

To use the Motorcortex analysis tools some Python libraries are required. The following steps will show how to install the required libraries.

Installing Matplotlib

The Motorcortex-python-tools package requires matplotlib (https://matplotlib.org/) to manipulate data and create plots.

  1. Install via apt (recommended):
sudo apt install python3-matplotlib

or Install via pip:

sudo pip3 install matplotlib

Installing Motorcortex-Python-Tools

Motorcortex-python-tools is distributed as an archive file (https://git.vectioneer.com/pub/motorcortex-python-tools/tree/master/dist).

  1. Save the archive into a folder you have access to. Navigate to that folder and run the following command in a terminal.
sudo pip3 install motorcortex-python-tools-1.2.zip

This will install the library files to /usr/local/lib/… an python executables to /usr/local/bin/

  1. To check if everything works start python3:
python
import motorcortex
print (motorcortex)
  1. The output should look like this:
module 'motorcortex' from '/usr/local/lib/python3.7/dist-packages/motorcortex/__init__.py'

Using motorcortex-python-tools

Running Python scripts

Depending on the platform and shell you use, there are slightly different ways to execute the scripts. In the different methods mcx-datalogger.py --help is used as example to execute.

in command line (terminal/cmd) go to the right folder with the terminal and write the following.

python mcx-datalogger.py --help

using python shells (Anaconda/miniconda/pycharm) make sure you are in the right folder and type the line below in the command window of the shell.

mcx-datalogger.py --help

Command line tools

mcx-datalogger

mcx-datalogger is a command-line tool that can connect to a motorcortex server and record a list of signals. It is also capable to be run as a daemon, creating a new datatrace whenever it is triggered by some signal on the server. The list of signals to be recorded is presented in JSON format, and can be conveniently created by motorcortex-desk.

!!!!!!!! See the motorcortex-desk documentation on how to create a signal-list file. !!!!!!!!!!!!!!!!

“Under construction”

To get help about the mcx-datalogger command, type:

mcx-datalogger.py –help

> mcx-datalogger.py --help

usage: mcx-datalogger.py [-h] -p PARAMETERFILE [-f FILE] [-F FOLDER]
                         [-c COMMENT [COMMENT ...]] [-u URL] [-s CERTIFICATE]
                         [-d DIVIDER] [--trigger TRIGGER]
                         [--triggerinterval TRIGGERINTERVAL]
                         [--triggervalue TRIGGERVALUE]
                         [--triggerop {==,<,>,<=,>=,!=}] [-C] [--noparamdump]

Log data from a MOTORCORTEX Server to a CSV file.

optional arguments:
  -h, --help            show this help message and exit
  -p PARAMETERFILE, --parameterfile PARAMETERFILE
                        JSON file that contains a list of parameters to log.
                        The JSON file shall have the following format:
                        [{"path":"root/signal1"}, {"path":"root/signal2"},
                        ...]
  -f FILE, --file FILE  Specify the filename that the data will be saved to.
                        By default the filename is created based on the
                        current date and time
  -F FOLDER, --folder FOLDER
                        Folder where output files are placed
  -c COMMENT [COMMENT ...], --comment COMMENT [COMMENT ...]
                        Comment to append to filename
  -u URL, --url URL     URL to connect to (Default:
                        wss://192.168.2.100:5568:5567)
  -s CERTIFICATE, --certificate CERTIFICATE
                        Certificate to use when connecting securely. (Default:
                        mcx.cert.pem)
  -d DIVIDER, --divider DIVIDER
                        Frequency Divider; specifies the amount of
                        downsampling that occurs at the server. The server
                        only then sends every N-th sample. Setting the
                        Frequency Divider to 1 will send at the maximum rate
                        that the server supports. (Default: 10)
  --trigger TRIGGER     Path to the signal that is monitored at the given
                        TRGGERINTERVAL. The logger is started whenever the
                        trigger condition is met.
  --triggerinterval TRIGGERINTERVAL
                        Trigger interval in seconds; the interval at which the
                        trigger parameter is checked. (default: 0.500 s)
  --triggervalue TRIGGERVALUE
                        Trigger value; the value the trigger is compared to.
  --triggerop {==,<,>,<=,>=,!=}
                        Trigger operator; the operator that is used for
                        comparison.
  -C, --compress        Compress the traces on the fly using the LZMA
                        algorithm. It creates files with the xz extension.
  --noparamdump         Do not dump parameters to file for each trace.

Some examples of how to use the mcx-dataloger:

mcx-datalogger.py -p parameters.json

This starts recording the signals listed in parameters.json using default values. This creates two files: e.g. 2019-04-30_11-16-06.csv and 2019-04-30_11-16-06.csv.params.

The .params file contains a record of all the “parameter” parameters of the control application (so it does not contain “input” or “output” type parameters), and should be a good representation of the conditions under which the trace has been made.

The .csv file contains the trace data, where the first row is the list of signals that are recorded.

The CSV file can be directly opened in tools like spreadsheet programs, Python or Matlab for further analysis. Or it can be inspected by using the mcx-dataplot tool (see the next section).

mcx-dataloger can also compress the output file on the fly using the --compress option. It may be that the resulting file gets truncated when the mcx-datalogger process is killed in the middle of logging (for instance when the power is switched off); in that case the compressed file may be incomplete and cannot be extracted using the regular unxz command. In this case use the xzcat command to extract the file:

> xzcat file.csv.xz &gt; file.csv
xzcat: file.csv.xz: Unexpected end of input

although xzcat reports an error the file will be extracted completely (up until the point where the logging process was killed). The file can then still be processed further.

mcx-dataplot

The mcx-dataplot is a command-line tool that can conveniently plot data that is recorded by mcx-datalogger and either display it on screen, or output the plot to a file.

To get help at the command line type:

> mcx-dataplot.py --help
usage: mcx-dataplot [-h] [-l] [--output OUTPUT] [-s SIGNALS [SIGNALS ...]]
                    [-x XAXIS] [--drawstyle DRAWSTYLE]
                    [--yrange YRANGE [YRANGE ...]] [--nodateconv]
                    FILENAME

mcx-dataplot

positional arguments:
  FILENAME              Inputfile in CSV format or xv (LZMA) compressed CSV.
                        First line is a list of signal names. First column is
                        interpreted as x-axis by default.

optional arguments:
  -h, --help            show this help message and exit
  -l, --list            List the signals contained in the file and exit
  --output OUTPUT       filename of the output plot file
  -s SIGNALS [SIGNALS ...], --signals SIGNALS [SIGNALS ...]
                        List of signals to plot. Example: -s 1,2:3 4:5. Where
                        "," adds the next signal to the same axis. ":"
                        indicates creation of an additional y-axis in the same
                        plot and <SPACE> creates a new subplot.
  -x XAXIS, --xaxis XAXIS
                        Column to use as x-axis
  --drawstyle DRAWSTYLE
                        interpolation type. One of "default", "steps", "steps-
                        pre", "steps-mid", "steps-post"
  --yrange YRANGE [YRANGE ...]
                        Range of the y-axis
  --nodateconv          Do not convert the first column to a date.

Below are some common examples of how to use the mcx-dataplot tool.

To get a list of signals available for plotting use the -l option

> mcx-dataplot.py 2019-02-17_21-45-18_file.csv -l
 0 time
 1 root/Control/systemTimeMicroS
 2 root/Control/allPunchesClear
 3 root/Control/materialPositionEncoderTicks
 4 root/Control/materialPositionFiltered
 5 root/Control/materialPosition
 6 root/Control/punchControl01/atMeasureAccuracy
 7 root/Control/punchControl01/atTargetBot
 8 root/Control/punchControl01/atTargetTop
 9 root/Control/punchControl01/PunchControlBot/actualPosition
10 root/Control/punchControl01/PunchControlBot/actualPressureA

To generate a plot on-screen, plotting columns 2 and 4 in the same plot use:

mcx-dataplot.py 2019-02-17_21-45-18_file.csv -s 2,4

This will display the two signals in the same plot on the same axes.

To plot the second signal on a separate y-axis in the same plot use:

mcx-dataplot.py 2019-02-17_21-45-18_file.csv -s 2:4

To plot the second signal in a separate subplot, sharing the same x-axis, use:

mcx-dataplot.py 2019-02-17_21-45-18_file.csv -s 2 4

Zooming in one subplot will also change the range of the x-axis in all other subplots.

Using motorcortex-python-tools in your own Python code

To use the datalogger in your own python scripts you first need to import the module

# import the DataLogger module
from motorcortex_tools import DataLogger
# import numpy
import numpy as np
# import matplotlib (optional)
import matplotlib.pyplot as plt
# import time module (required to use sleep())
import time

Then create a DataLogger object. In the example below the DataLogger object is connected to the controller on ip address ‘192.168.2.100’ and subscribes to ‘path/to/param’ with frequency divider of 10.

# Create a DataLogger object and set the options
logger = DataLogger('192.168.2.100', ['path/to/param'], divider=10)
# Start the logger
logger.start()

While the logger is running you can interact with the system by setting some parameters or waiting until you see some response or some time has elapsed.

# do something, like setting a parameter to True
req.setParameter('path/to/another/param', True).get()
# wait a bit
time.sleep(10)
# Stop the logger
logger.stop()
# Close the connection to the server
logger.close()

Now the logger object contains the time traces of the recorded parameters. These traces can be accessed and converted into NumPy Arrays for instance. The time traces are stored in a Dictionary where each trace can be accessed by its path. The time of a trace is stored under the “t” key, the value of the parameter in the “y” key.

# get the time as a vector
t = np.array(logger.traces['path/to/param']["t"]).transpose()
# get the first column of the corresponding values of the parameter
y = np.array(logger.traces['path/to/param']["y"][0]).transpose()

The NumPy arrays can then be processed by NumPy or Matplotlib or PyLab tools. Here is an example of plotting the trace in Matplotlib.

plt.plot(t,y)
plt.show()

3.1.4.2 - Automated Testing Tools

Installing Python Libraries required for reporting examples

To use the automatic reporting examples also jinja2 (http://jinja.pocoo.org/docs/2.10/) and pdfkit (https://pypi.org/project/pdfkit/) is required:

  1. Install via apt (reommended):
sudo apt install python3-jinja2 python3-pdfkit

Install via pip:

sudo pip3 install jinja2 pdfkit
  1. PDFKit also requires wkhtmltopdf (https://wkhtmltopdf.org/).
sudo apt install wkhtmltopdf

3.1.5 -

This chapter will explain how to install mcx-python. please select the operating system you are u using:

Linux Linux Windows Windows Macos MacOS

Installing Motorcortex-Python for Windows

Installing Python 3.7 or lower

  1. Download Python 3 from the python website: https://www.python.org/downloads/windows/. Choose the appropriate installer for your system. Make sure you choose Python 3.7.

  2. Launch the installer and choose Customize installation.

  1. All options are selected by default (documentation and test suite are actually optional).

  1. Click Next.
  2. Under the Advanced Options select Add Python to environment variables.

  1. Click Install.

Python 3 is now installed.

Installing Motorcortex-Python

motorcortex-python is the core library required for any motorcortex application. It provides convenient ways to communicate with Motorcortex-based applications.

motorcortex-python can be installed by using the “pip” tool. You have to be connected to the internet to install packaged using pip.

  1. Open a Command Prompt by pressing the Windows key and typing “cmd”.

Note: It may be necessary to use “Run as administrator” if installation commands fail.

  1. In the Command Prompt window type:
python -m pip install motorcortex-python

This will download and install the motorcortex-python package for the current user.

Alternative Installation Instructions

Alternatively the user can use the miniconda package management and environment management system.

Install Miniconda Python3

  1. Download Miniconda Python 3 from the conda website: https://docs.conda.io/en/latest/miniconda.html. Choose the appropriate installer for your system.

  2. Launch the installer and use the defaults on each screen to install.

  1. Click Next.

  1. Click I Agree.

  1. Select for who the instalation is designated and click Next.

  1. Choose your desired Destination Folder and click Next.

  1. Select Register Anaconda as my default Python -- and click Install.

  1. Click Finish to finish the instalation.

Tip: It is very convienient to use the miniconda cheatsheet when using miniconda https://docs.conda.io/projects/conda/en/latest/user-guide/cheatsheet.html.

Create environment

Open an Anaconda Prompt by pressing the windows key, type anaconda in the search field and select appropriate.

  1. In the Anaconda Prompt window, to create the mcx-env environment, type:
conda create -n mcx-env python=3.7

To remove an environment use ”conda env remove -n

ENV_NAME”

Activate environment

  1. Activate the environment:
conda activate mcx-env

Note: To access this environment a next time open an Anaconda Prompt window and type conda activate mcx-env. To deactivate an environment type conda deactivate.

3.2 - C++

3.2.1 - C++ Installation

Documentation for the C++ client has not been finished yet at the moment.

Client Library Source Code can be grabbed from our public GIT repository. Have a look at the examples in the test folder.

Library Documentation can be found here:

3.2.2 - C++ Examples

Documentation for the C++ client has not been finished yet at the moment.

Client Library Source Code can be grabbed from our public GIT repository. Have a look at the examples in the test folder.

Library Documentation can be found here:

3.2.3 - C++ API

Documentation for the C++ client has not been finished yet at the moment.

Client Library Source Code can be grabbed from our public GIT repository. Have a look at the examples in the test folder.

Library Documentation can be found here:

3.3 - Protocol Description

Table of Contents

Top

motorcortex.proto

Description of the motorcortex-core message.

All core data types, enumerators and RPC messages are defined here.

Version 1.0.0

ConsoleCmdListMsg

Request to execute a list of commands on the server.

User's request to execute a list of commands on the server (console mode).

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

(Note: Currently not implemented).

Field Type Label Description
header Header optional Frame counter and actual time.
cmds ConsoleCmdMsg repeated List of commands

ConsoleCmdMsg

Request to execute command on the server.

User's request to execute a command on the server (console mode).

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

(Note: Currently not implemented).

Field Type Label Description
header Header optional Frame counter and actual time.
value string required Console command

CreateGroupMsg

Request to create a publisher group.

User's request to start publishing specified parameters. Several users may subscribe to the same group. This mechanism reduces the load on the server and allows more clients to get frequent updates.

User may choose a scale factor for the publishing rate of the group.

Server's reply: GroupStatusMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::PERMISSION_DENIED - Permission denied because the user has no access rights.

StatusCode::FAILED_TO_SET_REQUESTED_FRQ - operation successful, but failed to change publisher's frequency, because the group has already existed.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
frq_divider uint32 required Requested frequency divider, to scale down publisher rate.
alias string required Name of the group.
paths string repeated List of the parameters.

Error

Error description.

System type, which describes an error.

Field Type Label Description
timestamp fixed64 required System time, when error occurred.
error_number fixed32 required Error code.
error_level fixed32 required Error level.
subsystem fixed32 required Subsystem, for example 1 is 1st actuator of the system.
info fixed32 required Additional error code, provided by hardware.

ErrorList

List of errors.

Error messages are sent to the client as a list of N active errors.

Field Type Label Description
errors Error repeated List of active errors.
number_of_errors fixed32 required Number of errors in the list.
update_counter fixed32 required An update couter changes everytime the list of active errors is updated.

GetParameterListMsg

Request to get a list of parameters with info and values.

Server's reply: ParameterListMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
params GetParameterMsg repeated List of requested parameter.

GetParameterMsg

Request to get a parameter info and its value.

Server's reply: ParameterMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
path string required Path of the requested parameter.

GetParameterTreeHashMsg

Request to get a parameter tree hash.

Instead of requesting a complete parameter tree, a client might request only a tree hash to compare it against the cached tree to detect if the tree on the server has been changed. The difference between hashes indicates the changes in the tree structure. Note: Changes in parameter values do not result in a different tree hash.

Server's reply: ParameterTreeHashMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.

GetParameterTreeMsg

Request to get a parameter tree message

Server's reply: ParameterTreeMsg, with following status codes:

StatusCode::OK - user is logged out,

StatusCode::FAILED - operation failed.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.

GetSessionTokenMsg

Request a session token.

After user is logged-in it can request a session token for re-login.

Server's reply: SessionTokenMsg with the token status code.

Field Type Label Description
header Header optional Frame counter and actual time.

GroupMsg

Group message, used by the publisher. (Note: currently is not used, since publisher is not using protobuf)

Field Type Label Description
header Header optional Frame counter and actual time.
params ParameterMsg repeated List of published parameters.

GroupParameterInfo

Parameters' group information.

This data type represents the subscription information, required to decode parameters from the group message.

Field Type Label Description
index uint32 required Index of the subscribed parameter.
offset uint32 required Offset in the group message.
size uint32 required Size of the parameter.
info ParameterInfo required Parameter information.
status StatusCode required Status code.

GroupStatusMsg

Group package description.

Reply for 'CreateGroupMsg', with the package structure.

Message can have following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed,

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::FAILED_TO_SET_REQUESTED_FRQ - operation successful, but failed to change publisher's frequency, because the group has already existed.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
id uint32 required Unique id of the group.
alias string required Name of the group.
params GroupParameterInfo repeated List of parameters' info.
status StatusCode required Status code.

Generic message header, included in the request/reply messages.

Field Type Label Description
frameCounter fixed32 required Frame counter counts number of parameter updates.
timestamp fixed64 required Current server time in the format: microseconds from 1 Jan 2000.

LoadMsg

Request to load parameter values from the disk.

User's request to load parameter values from XML file.

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::USER_LOGGED_IN_NO_CONTROL - User is in read-only mode.

StatusCode::FAILED_TO_OPEN - Failed to create/open a file.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
path string required Path to config file.
file_name string required File name.

LoginMsg

Login request.

User request to get access to the parameter tree.

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - user is logged in,

StatusCode::READ_ONLY_MODE - user is logged in, read only mode,

StatusCode::WRONG_PASSWORD - login failed, wrong login or password.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
login string required User's login.
password string required User's password.

LogoutMsg

Logout request.

User request to exit. Logout will happen automatically if user is disconnected.

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - user is logged out,

StatusCode::FAILED - operation failed,

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.

OverwriteParameterMsg

Request to overwrite/force a parameter value.

User's request to force a parameter value. For the Input and Parameter types the input value will be overwritten, for the Output type, the output value will be overwritten.

By enabling flag 'activate', overwrite value will be active until the flag is disabled, by ether commanding ReleaseParameterMsg or OverwriteParameterMsg with 'activate' - false.

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::USER_LOGGED_IN_NO_CONTROL - User is in read-only mode.

StatusCode::WRONG_PARAMETER_PATH - Wrong parameter path.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
offset ParameterOffset optional Offset of the parameter value.
activate bool required Flag to enable/disable permanent overwrite.
path string required Path of the requested parameter.
value bytes required New values.

ParameterInfo

Parameter information fields.

Active state of the parameter in the tree, including its name, size, data type, io type and active flags.

Field Type Label Description
id uint32 required Unique id, assigned by parameter server.
data_type uint32 required Tag of the data type.
data_size uint32 required Size of one data element.
number_of_elements uint32 required Number of the elements.
flags uint32 required Parameter flags (overwrite, link etc…).
permissions uint32 required Access permissions.
param_type ParameterType required I/O type of the parameter.
group_id UserGroup required Group ID of the owner.
unit Unit required SI unit of the parameter.
path string required Path (including name) of the parameter.

ParameterListMsg

List of parameters with info values.

Reply for 'GetParameterListMsg', with the list of parameters info and values.

Message can have following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
params ParameterMsg repeated List of parameters.
status StatusCode required Status code.

ParameterMsg

Parameter info and its value.

Reply for 'GetParameterMsg', with the parameter info and a value.

Message can have following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
value bytes required Parameter value.
header Header optional Frame counter and actual time.
info ParameterInfo optional Parameter information.
status StatusCode required Status code.

ParameterOffset

ParameterOffset description.

An offset can be applied when setting a new value of the parameter array

Field Type Label Description
type OffsetType required Type of the offset. Default: OFFSET_ELEMENTS
offset uint32 required Starting point.
length uint32 required Length from starting point.

ParameterTreeHashMsg

Parameter tree hash.

Hash of the parameter tree.

Message can have following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
hash uint32 required Hash of the tree.
status StatusCode required Status code.

ParameterTreeMsg

Parameter tree data, which contains information about tree structure and available parameters. Message can have following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
params ParameterInfo repeated Array with available parameters.
hash uint32 required Hash value of the parameter tree stored in 'repeated ParameterInfo params'.
status StatusCode required Status code.

ReleaseParameterMsg

Request to release an overwrite/force.

User's request to cancel overwrite of a parameter value.

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::USER_LOGGED_IN_NO_CONTROL - User is in read-only mode.

StatusCode::WRONG_PARAMETER_PATH - Wrong parameter path.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
path string required Path of the requested parameter.

RemoveGroupMsg

Request to remove a publisher group.

User's request to unsubscribe from the group.

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed,

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
alias string required Name of the group.

RestoreSessionMsg

Restore session request.

User request to restore the old session to access to the parameter tree.

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - user is logged in,

StatusCode::READ_ONLY_MODE - user is logged in, read only mode,

StatusCode::PERMISSION_DENIED - login failed, token expired,

StatusCode::FAILED - operation failed,

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
token string required Session token.

SaveMsg

Request to save parameter values to the disk.

User's request to save parameter values to XML file.

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::USER_LOGGED_IN_NO_CONTROL - User is in read-only mode.

StatusCode::FAILED_TO_OPEN - Failed to create/open a file.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
path string required Path to a config file.
file_name string required File name.i

SessionTokenMsg

Session token.

A token with current session id. The toke is used for re-logging if the connection is lost.

Server's reply: SessionTokenmsg with the token and one of the following status codes:

StatusCode::OK - token is granted,

StatusCode::PERMISSION_DENIED - user has no permission,

StatusCode::FAILED - operation failed,

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
token string required Session token.
status StatusCode required Status code.

SetParameterListMsg

Request to set a list of parameters values.

User's request to update a list of parameters values.

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::USER_LOGGED_IN_NO_CONTROL - User is in read-only mode.

StatusCode::WRONG_PARAMETER_PATH - Wrong parameter path.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
params SetParameterMsg repeated List of parameter set messages.

SetParameterMsg

Request to set a parameter value.

User's request to update a parameter value.

Server's reply: StatusMsg, with following status codes:

StatusCode::OK - operation successful,

StatusCode::FAILED - operation failed.

StatusCode::PERMISSION_DENIED - Permission denied because user has no access rights.

StatusCode::USER_LOGGED_IN_NO_CONTROL - User is in read-only mode.

StatusCode::WRONG_PARAMETER_PATH - Wrong parameter path.

StatusCode::FAILED_TO_DECODE - failed to decode request message.

Field Type Label Description
header Header optional Frame counter and actual time.
offset ParameterOffset optional Offset of the parameter value.
path string required Path of the requested parameter.
value bytes required New values has to be encoded according to the data type, which is provided in the parameter info.

StatusMsg

Status code message.

Reply with a status code for various request messages.

Field Type Label Description
header Header optional Frame counter and actual time.
status StatusCode required Return status of the request.

DataType

Available data types.

Data types supported by a parameter server.

User data types can be added after the tag USER_TYPE.

Name Number Description
data_type_undefined 0
INT8 1 integer 1 byte
UINT8 2 unsigned integer 1 byte
INT16 3 short int
UINT16 4 unsigned short int
INT32 5 int
UINT32 6 unsigned int
INT64 7 long
UINT64 8 unsigned long
BOOL 9 boolean
FLOAT 257 float
DOUBLE 258 double
CHAR 513 char
STRING 514 C-string
BYTES 1177 bytes array
USER_TYPE 1280 end of the system types

ErrorLevel

Available error levels.

Generic user levels generated by the logic. (Note: Check examples of the state machine.)

Name Number Description
error_level_undefined 0
INFO 1 Information message.
WARNING 2 Warning message.
FORCED_DISENGAGE 3 Graceful software stop, caused by a hardware malfunction or a wrong user actions.
SHUTDOWN 4 More abrupt software stop, caused by a hardware malfunction.
EMERGENCY_STOP 5 Abrupt software and hardware stop, caused by a hardware malfunction.

OffsetType

Avaliable offset types.

When setting a parameter value user can specify an offset and length

Name Number Description
offset_type_undefined 0
OFFSET_ELEMENTS 1 Offset and length is calculated in the elements. For example update an array starting from the element number 3.
OFFSET_BYTES 2 Offset and length is calculated in bytes.
OFFSET_BITS 3 Offset and length is calculated in bits.

ParameterFlag

System parameter's flag

Parameter can have various system flags, which shows that it is been overwritten or linked. (Note: This list will grow in future)

Name Number Description
LINK_IS_ACTIVE 1 Parameter is linked to another parameter.
OVERWRITE_IS_ACTIVE 2 Parameter is being overwritten.

ParameterType

Parameter's IO types.

Each parameter in the tree can be an INPUT, an OUTPUT or a PARAMETER.

PARAMETER type is both an input and output, it can be saved and loaded from the disk.

Value of a parameter with OUTPUT type cannot be set, but can be overwritten (forced). Force operation on the OUTPUT will only change the parameter value on everything that is linked to it. It will NOT change the internal value of the block to which the output belongs.

Name Number Description
param_type_undefined 0
INPUT 1 Input parameter.
OUTPUT 16 Output parameter.
PARAMETER 256 Input/output parameter, which is saved and loaded from the disk on request.
PARAMETER_VOLATILE 257 Input/output parameter, which is valotile, not saved or loaded from the disk.
PARAMETER_PERSISTENT 258 Input/output parameter, which is persistent, continuously saved and loaded from the disk.

Permission

Available parameters' permissions. Different users/groups may require access to different and/or protected parts of the parameter tree. Permission flags allow fine-tuning access levels of the groups.

The Motorcortex permissions structure is similar to that of Unix file permissions. Permissions are represented either in symbolic notation or in octal notation. (Note: User rights are not yet implemented, instead use Group rights)

For example:

———- (0000): no permission

-rwx—— (0700): read, write, & execute only for owner (Note: currently not implemented, user group flags instead)

-rwxrwx— (0770): read, write, & execute for owner and group (Note: execute flag is used as a permission to open folders)

-rwxrwxr-x (0775): read, write, & execute for owner and group, read & execute for all others.

-rwxrwxrwx (0777): full access

Name Number Description
permission_undefined 0
USER_READ 256 owner user read -r——–
USER_WRITE 128 owner user write –w——-
USER_EXECUTE 64 owner user execute —e——
GROUP_READ 32 owner group read —-r—–
GROUP_WRITE 16 owner group write —–w—-
GROUP_EXECUTE 8 owner group execute ——e—
OTHERS_READ 4 other users read ——-r–
OTHERS_WRITE 2 other users write ——–w-
OTHERS_EXECUTE 1 other users ———e

StatusCode

Return status codes.

Return status codes are included in the reply for every user's request. Using these codes user can verify if request was successful or there was a failure.

Name Number Description
OK 0 Request was processed successfully.
READ_ONLY_MODE 1 Login is successful, but user has read-only right.
FAILED 65280 Generic failure mask.
FAILED_TO_DECODE 4096 Failed to decode request message.
SUB_LIST_IS_FULL 4352 Failed to subscribe for a parameter, because subscription list is full. Create new parameter group.
WRONG_PARAMETER_PATH 4608 Failed to find parameter, because requested path is wrong.
FAILED_TO_SET_REQUESTED_FRQ 4864 When several clients share the same publisher's group, original publishing frequency is preserved.
FAILED_TO_OPEN_FILE 5120 Failed to open/save/load a file.
WRONG_PASSWORD 8448 Login failed, wrong login or password.
USER_NOT_LOGGED_IN 8704 Operation not permitted, because user is not logged in.
PERMISSION_DENIED 8960 Permission denied because user has no access rights.

Unit

Some SI units.

Name Number Description
unit_undefined 0
Length 15 Length mask 0xf
mm 1 millimeters 0x1
m 2 meters 0x2
Angle 241 Angle mask 0xf1
rad 49 radians 0x31
deg 65 degrees 0x41
Time 242 Time mask 0xf2
nanosec 18 nanoseconds 0x12
microsec 34 microseconds 0x22
millisec 50 milliseconds 0x32
sec 66 seconds 0x42
Weight 243 Weight mask 0xf3
gram 19 grams 0x13
kg 35 kilograms 0x23
Velocity 244 Velocity mask 0xf4
m_sec 20 linear velocity, meters per second 0x14
rad_sec 36 angular velocity, radians per second 0x24
Acceleration 245 Acceleration mask 0xf5
m_sec2 21 linear acceleration meters per second^2 0x15
rad_sec2 37 angular acceleration radians per second^2 0x25
Force 246 Force mask 0xf6
N 22 force, newtons 0x16
Nm 38 torque, newton-metres 0x26
percent 23 percentages 0x17

UserGroup

Available user groups.

Group determines an access level of the user. Users can belong to one group: Administrator, Operator or Guest. System is reserved for internal motorcortex-core use. By default Operator cannot read or write Administrator's related parameters. The administrator has a full access to the Operator's data.

Group access can be reconfigured in C++ server code or in the server configuration file. Furthermore, parameterization of the access can be done by setting permission level (Permission) of the parameter.

Name Number Description
user_group_undefined 0
SYSTEM 1 System group has full access. It is not available for the users.
ADMINISTRATOR 3 Administrator group has full access, except for system-level parameters.
OPERATOR 7 Operator has limited write access and read access.
GUEST 2147483647 Guest has read access.

Scalar Value Types

.proto Type Notes C++ Java Python Go C# PHP Ruby
double double double float float64 double float Float
float float float float float32 float float Float
int32 Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead. int32 int int int32 int integer Bignum or Fixnum (as required)
int64 Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead. int64 long int/long int64 long integer/string Bignum
uint32 Uses variable-length encoding. uint32 int int/long uint32 uint integer Bignum or Fixnum (as required)
uint64 Uses variable-length encoding. uint64 long int/long uint64 ulong integer/string Bignum or Fixnum (as required)
sint32 Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s. int32 int int int32 int integer Bignum or Fixnum (as required)
sint64 Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s. int64 long int/long int64 long integer/string Bignum
fixed32 Always four bytes. More efficient than uint32 if values are often greater than 2^28. uint32 int int uint32 uint integer Bignum or Fixnum (as required)
fixed64 Always eight bytes. More efficient than uint64 if values are often greater than 2^56. uint64 long int/long uint64 ulong integer/string Bignum
sfixed32 Always four bytes. int32 int int int32 int integer Bignum or Fixnum (as required)
sfixed64 Always eight bytes. int64 long int/long int64 long integer/string Bignum
bool bool boolean boolean bool bool boolean TrueClass/FalseClass
string A string must always contain UTF-8 encoded or 7-bit ASCII text. string String str/unicode string string string String (UTF-8)
bytes May contain any arbitrary sequence of bytes. string ByteString str []byte ByteString string String (ASCII-8BIT)

3.4 - Javascript

3.4.1 - JavaScript Installation

Documentation for the JavaScript client has not been finished yet at the moment.

Client Library Source Code can be grabbed from our public GIT repository. Have a look at the examples in the examples folder.

Library Documentation can be found here:

3.4.2 - JavaScript Examples

Documentation for the JavaScript client has not been finished yet at the moment.

Client Library Source Code can be grabbed from our public GIT repository. Have a look at the examples in the examples folder.

Library Documentation can be found here:

3.4.3 - MCX-JavaScript API

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

Functions

encode(msg)Uint8Array

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

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
}

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.

Example

let connectionData = new ConnectionData ('192.168.2.100', 5568, 5567, false, 1000, 10000, 1000, 100)

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

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));

encode(msg) ⇒ Uint8Array

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

Kind: global function
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);

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.

4 - Developing Control Applications

Developing Control Applications

MOTORCORTEX provides out of the box solution to develop Hard-Realtime Control Applications in C++ with an integrated high-speed and secured communication for distributed systems. It supports popular industrial buses, like EtherCAT.

The Parameter Tree

In a Motorcortex application all Modules and variables are organized in a tree structure; the Parameter Tree. The Parameter Tree is used to communicate data between tasks and to the outside world in a thread-safe manner. In the tree the modules are represented as subtrees (folder) and variables are represented as leafs.

The Parameter Tree contains a snapshot of all the registered inputs, outputs and internal data of the modules at the current time. Each Task or Module can create its own subtrees (folder) in the Parameter Tree. Modules can be nested and register their own parameters in the Tree.

The Parameter Tree always starts from the root node, which is passed to the modules and tasks that then can register their own parameters or create submodules that register their own data.

The Communication Server

The Communication Server provided by Motorcortex has two parts:

  1. the first part is a Signaling Server which uses a Request/Reply reliable messaging pattern.
  2. The second part is a Publishing Server or Publisher which uses a Publish/Subscribe best-effort delivery messagin pattern.

A Signaling Server is required for Remote Procedure Calls and for managing the control application, for example updating parameter values. It is also responsible for managing the Publishing Server.

The Publishing Server can organize data into groups and publish them with the requested frequency. The Publisher is used to send Real-time data continuously.

The Signaling Server is set up in the main(…) function and runs until a terminating signal is received.

Because the Publisher has a cyclic behavior, it is added to a Task that executes it with the given update rate. An example how the publisher is created is shown below:

4.1 - Setting-up your Developement Environment

The main tool of use for building, testing and deploying software is CMake Cmake is widely accepted and supported by many IDEs, which means that the user is free to choose his/her own development environment.

To make things more convenient, there are Motorcortex plugins for CLion (https://www.jetbrains.com/clion). CLion is an advanced IDE (Integrated Development Environment) that has many tools that makes programming easy, is available across platforms and is capable to cross-compile and deploy Motorcortex applications straight to the controller with a click of a button. This section is a guide, how to install CLion and the Motorcortex plugins from the CLion Marketplace and get started quickly with developing Motorcortex applications.

Setting up your development environment for creating control applications is different for every machine. Please select the operating system you are u using:

Linux Windows MacOS

Install Build Tools

Before Installing Clion it is important to install build-essential tools

   sudo apt-get install build-essential

Installing CLion For Linux

Installing CLion has be done by downloading Clion directly from the Jetbrains website Download CLion from: www.jetbrains.com/clion/download

How to Install CLion is explained in their documentation: www.jetbrains.com/help/clion/installation-guide.html#standalone

To use Clion you will have to create a Jetbrains account and start with a free trail.

Installing Motorcortex Templates Plugin (for clion)

After installing Clion the first step is to install a the Motorcortex Templates plugin. This plugin will provide you the option to create a new Motorcortex project.

  1. In the Main Menu on the top left corner open: File → Settings, then find the Plugins menu.

  2. In the plugins menu search for Motorcortex.

  1. Install the Motorcortex Templates plugin and Restart IDE.

After installing the Motorcortex templates and restarting the Clion, you can create new Motorcortex projects in the main menu.

  1. In the main menu open: File → New Project, in the pop-up under C++ choose C++ Motorcortex select the location where you want to save your project and press the Create.

  1. Congratulations now you can start developing your Motorcotex application.

The Motorcortex development toolchain

There are two options when developing Motorcortex applications:

  • Use remote development and compile the application on the Motorcortex Target System;
  • Cross-compile on your development PC and deploy the executable to the Motorcortex Target System

The first method is easy to set up, it does not require additional dependencies however the downside is that a compile time for the large projects may be significant. The second method overcomes this problem, but requires a cross-compilation tool-chain to be set up.

Set-up Cross Compilation (In Clion)

For cross compilation you use … (with remote device libraries).

Install Motorcortex toolchain on your system

For Cross compilation you will need a Motorcortex SDK you can download the SDK (Software Developement Kit) from the motorcortex.io store by pressing the download button below.

  1. Extract the archive and place the .sh file in a folder of your preference.

  2. In the terminal browse to the folder and run the .sh file from the terminal, for example:

   sh ./motorcortex-glibc-x86_64-motorcorcortex-image-dev-corei7-64-toolchain-X.X.X.sh
  1. You will be asked to enter the target directory where to install the SDK to. It is a good idea to keep the SDK in the home folder, where administrative rights are not required for example:
   ~/mcx-sdk

Mounting Sysroot on your system

The first step to Cross Compilation is to mount a Sysroot directory to your system that is used for cross-compilation. A `Sysroot is a directory which is considered to be the root directory for the purpose of locating headers and libraries of your application.

  1. Generate a new key pair with the following command.
   ssh-keygen -t rsa

  1. Use ssh-copy-id to provide a temporary access without a password to the remote Motorcortex host. If you are asked to fill in a password use vectioneer.
   ssh-copy-id admin@192.168.2.100

  1. Create a folder to mount the remote Motorcortex file system on with the following command.
   mkdir ~/mcx-sysroot
  1. Ensure that sshfs is installed with the following command:
   sudo apt-get install sshfs
  1. Mount the Motorcortex file system with the following command:
   sshfs admin@192.168.2.100:/ ~/mcx-sysroot/

Configure toolchain in clion.

Configure the compiler paths to use the Motorcortex cross-compilation toolchain.

  1. Open File → Settings → Build Execution Deployment → Toolchains.

  2. Create a new System Toolchain with the name motorcortex.

  3. Fill in Make, C Compiler and C++ Compiler paths to point the Motorcortex SDK as shown below.

  • Make:
   /home/ubuntu/mcx-sdk/sysroots/x86_64-pokysdk-linux/usr/bin/make
  • C Compiler:
   /home/ubuntu/mcx-sdk/sysroots/x86_64-pokysdk-linux/usr/bin/x86_64-poky-linux/x86_64-poky-linux-gcc
  • C++ Compiler
   /home/ubuntu/mcx-sdk/sysroots/x86_64-pokysdk-linux/usr/bin/x86_64-poky-linux/x86_64-poky-linux-g++

  1. Press Apply to save the changes.

Setup toolchain plugin

Configure sysroot path to use the headers and libraries from the remote host.

  1. Open File → Settings → Build, Execution, Deployment → **Motorcortex SDK and fill in the Sysroot path path the mounted folder (mcx-sysroot).
   home/ubuntu/mcx-sysroot

Add deployment connection to remote host (IS THIS STILL NEEDED IN THE NEW VERSION ALEXEY!!??)
  1. Add the connection to the remote Motorcortex host. Open Tools → Deployment → Configuration, add a new SFTP connection named mcx-host.

  2. select or add ssh configuration.

Press the Test Connection button to make sure that the filled data is correct.

Press the Autodetect button to set the root path. Uncheck the Visible only for this project checkbox make this host visible in all the projects.

press ok

Cross-compiling Motorcortex applications.

edit configurations.

select mcx dingie

save password checkbox

name cross-mcx-example

deployment profile to mxc-host

press ok

  1. In CLion open the project configuration menu.

  1. Click on + and select Motorcortex Remote Application. In the deployment profile field select Motorcortex remote host.

copy config folder

  1. In the Run/Debug configuration select the just created cross-compiled application with CrossDebug/CrossRelease build profile.

  2. Press the hammer button to cross-compile, play to copy and run on the remote Motorcortex host and the bug button to start a remote debug session.

Note if CMake CrossDebug/CrossRelease don’t work remove the “Motorcortex Remote Application” from Run/Debug Configurations and try again

4.2 - Setup Development Environment

The main tool of use for building, testing and deploying software is CMake Cmake is widely accepted and supported by many IDEs, which means that the user is free to choose his/her own development environment.

To make things more convenient, there are Motorcortex plugins for CLion (https://www.jetbrains.com/clion). CLion is an advanced IDE (Integrated Development Environment) with many tools that make programming a Motorcortex application more easy, this IDE is available across platforms and is capable to cross-compile and deploy Motorcortex applications straight to the controller with a click of a button. This guide will show you how to install CLion, Motorcortex plugins from the CLion Marketplace and get started with developing Motorcortex applications.

The Motorcortex development toolchain

There are two options when developing Motorcortex applications:

  • Use remote development and compile the application on the Motorcortex Target System;
  • Cross-compile on your development PC and deploy the executable to the Motorcortex Target System

The first method is easy to set up, it does not require additional dependencies however the downside is that a compile time for the large projects may be significant. The second method overcomes this problem, but requires a cross-compilation tool-chain to be set up.

4.2.1 - Install Development Environment

Installing your development environment for creating control applications is different for every PC. Please select the operating system you are u using:

Linux Windows MacOS

Install Build Tools

Before Installing Clion it is important to install build-essential tools

   sudo apt-get install build-essential

Installing CLion For Linux

Installing CLion has be done by downloading Clion directly from the Jetbrains website Download CLion from: www.jetbrains.com/clion/download

How to Install CLion is explained in their documentation: www.jetbrains.com/help/clion/installation-guide.html#standalone

To use Clion you will have to create a Jetbrains account and start with a free trail.

Installing Motorcortex Templates Plugin (for clion)

After installing Clion the first step is to install a the Motorcortex Templates plugin. This plugin will provide you the option to create a new Motorcortex project.

  1. In the Main Menu on the top left corner open: File → Settings, then find the Plugins menu.

  2. In the plugins menu search for Motorcortex.

  1. Install the Motorcortex Templates plugin and Restart IDE.

After installing the Motorcortex templates and restarting the Clion, you can create new Motorcortex projects in the main menu.

  1. In the main menu open: File → New Project, in the pop-up under C++ choose C++ Motorcortex select the location where you want to save your project and press the Create.

  1. Congratulations now you can start developing your Motorcotex application.

4.2.2 - Setup Remote Development

Set-up Remote Development (In CLion)

The most simple way to develope control applications is to use remote development. With remote development you compile the application and put it on your controller.

Check Connection

Connect your controller to your PC and make sure you have a connection. If you don’t know to connect to a Motorcortex controller make sure to check out Connect your PC.

  1. Before we start we have to make sure our connection works. open the Terminal located on the bottom of your IDE or press Alt+F12.

  1. In the terminal ping to your controller with the following command.
   ping 192.168.2.100 -c 3
  1. The terminal should look something similar to this.

If you are unable to ping your controller make sure to check out Connection troubleshooting before you continue. If you have a connection with your controller it is time to setup your toolchain.

  1. In the Main Menu open File → Settings under Build, Execution, Deployment you will find the Toolchains menu.

  2. Add a new toolchain by pressing the + button and select Remote Host.

  1. In the Credentials press the ⚙️ button to enter the SSH configuration menu. Add a new configuration by pressing the + button and fill in the following data:
  • Host: 192.168.2.100
  • Port:22
  • User name: admin
  • Password: vectioneer

  1. Press the Test Connection button to make sure your connection is ok. If not re-check your controller connection.

  2. If the connection is good you can press OK to close the SSH Configurations menu.

  3. Wait for Make and the C/C++ Compiler to be detected then press the Apply button to save the Toolchain settings.

  4. Go CMake in the Settings menu and press the + button.

  1. Set the Build type to Debug and Toolchain to Remote Host.

  1. Press the OK button to save the CMake settings and close the settings window.

  2. Wait for +/- 20 seconds while a connection is being established, data is transferred and cmake is configured.

  3. Make sure that your controller is not running a Motorcortex application. Open the Terminal in Clion and run the the following command.

   ssh admin@192.168.2.100 'echo vectioneer | sudo -S motorcortex stop'
  1. In Clion set your Run/Debug Configuration to Debug-Remote Host.

  1. Press play to build and run the application.

  1. Congratulations you are now ready to start remote developing your Motorcortex application.

4.2.3 - Setup Cross Compilation

Set-up Cross Compilation (In Clion)

For cross compilation you use … (with remote device libraries).

Install Motorcortex toolchain on your system

For Cross compilation you will need a Motorcortex SDK you can download the SDK (Software Developement Kit) from the motorcortex.io store by pressing the download button below.

  1. Extract the archive and place the .sh file in a folder of your preference.

  2. In the terminal browse to the folder and run the .sh file from the terminal, for example:

   sh ./motorcortex-glibc-x86_64-motorcorcortex-image-dev-corei7-64-toolchain-X.X.X.sh
  1. You will be asked to enter the target directory where to install the SDK to. It is a good idea to keep the SDK in the home folder, where administrative rights are not required for example:
   ~/mcx-sdk

Mounting Sysroot on your system

The first step to Cross Compilation is to mount a Sysroot directory to your system that is used for cross-compilation. A `Sysroot is a directory which is considered to be the root directory for the purpose of locating headers and libraries of your application.

  1. Generate a new key pair with the following command.
   ssh-keygen -t rsa

  1. Use ssh-copy-id to provide a temporary access without a password to the remote Motorcortex host. If you are asked to fill in a password use vectioneer.
   ssh-copy-id admin@192.168.2.100

  1. Create a folder to mount the remote Motorcortex file system on with the following command.
   mkdir ~/mcx-sysroot
  1. Ensure that sshfs is installed with the following command:
   sudo apt-get install sshfs
  1. Mount the Motorcortex file system with the following command:
   sshfs admin@192.168.2.100:/ ~/mcx-sysroot/

Configure toolchain in clion.

Configure the compiler paths to use the Motorcortex cross-compilation toolchain.

  1. Open File → Settings → Build Execution Deployment → Toolchains.

  2. Create a new System Toolchain with the name motorcortex.

  3. Fill in Make, C Compiler and C++ Compiler paths to point the Motorcortex SDK as shown below.

  • Make:
   /home/ubuntu/mcx-sdk/sysroots/x86_64-pokysdk-linux/usr/bin/make
  • C Compiler:
   /home/ubuntu/mcx-sdk/sysroots/x86_64-pokysdk-linux/usr/bin/x86_64-poky-linux/x86_64-poky-linux-gcc
  • C++ Compiler
   /home/ubuntu/mcx-sdk/sysroots/x86_64-pokysdk-linux/usr/bin/x86_64-poky-linux/x86_64-poky-linux-g++

  1. Press Apply to save the changes.

Setup toolchain plugin

Configure sysroot path to use the headers and libraries from the remote host.

  1. Open File → Settings → Build, Execution, Deployment → **Motorcortex SDK and fill in the Sysroot path path the mounted folder (mcx-sysroot).
   home/ubuntu/mcx-sysroot

Add deployment connection to remote host (IS THIS STILL NEEDED IN THE NEW VERSION ALEXEY!!??)
  1. Add the connection to the remote Motorcortex host. Open Tools → Deployment → Configuration, add a new SFTP connection named mcx-host.

  2. select or add ssh configuration.

Press the Test Connection button to make sure that the filled data is correct.

Press the Autodetect button to set the root path. Uncheck the Visible only for this project checkbox make this host visible in all the projects.

press ok

Cross-compiling Motorcortex applications.

edit configurations.

select mcx dingie

save password checkbox

name cross-mcx-example

deployment profile to mxc-host

press ok

  1. In CLion open the project configuration menu.

  1. Click on + and select Motorcortex Remote Application. In the deployment profile field select Motorcortex remote host.

copy config folder

  1. In the Run/Debug configuration select the just created cross-compiled application with CrossDebug/CrossRelease build profile.

  2. Press the hammer button to cross-compile, play to copy and run on the remote Motorcortex host and the bug button to start a remote debug session.

Note if CMake CrossDebug/CrossRelease don’t work remove the “Motorcortex Remote Application” from Run/Debug Configurations and try again

4.2.4 - Install Integrated Development Environment

4.2.5 - Install Integrated Development Environment

4.2.6 - Setup Cross Compilation

4.2.7 - Setup Cross Compilation

4.2.8 - Setup Remote Development

4.2.9 - Setup Remote Development

4.3 - Motorcortex Application Template

This section will explain you how to create a new poject and how the Motorcortex project template works.

In Clion there is a template avaiable to create a new C++ Motorcortex project. This template provides you a structure to get started creating a control application and will consist of the following ellements:

  • The config folder includes saved values of the module’s parameters and EtherCAT configuration.
  • The control folder contains a template of the main control loop Module. This where all the control computation happens.
  • The logic folder (optional) contains a template of the Finite State Machine to build advanced logic.
  • A main.cpp file, where all system and task configuration and linking of parameters happens. The generated main.cpp already has all the required code, necessary to run a Hard-Real Time application and communication server.

This section will explain how to create a new C++ Motorcortex project, and explain the elements provided by the template.

Creating a new C++ Motorxortex Project

  1. In the CLion main menu select File → New → C++ Motorcortex. Then enter a new location for you project and projectname. If your project requires a logic Tasks, check the box to generate a Logic template.

The generated template provided the following structure:

  • The config folder
  • The control folder
  • The logic folder (optional)
  • A main.cpp file

When developing remotely you will have to set your toolchain to remote host when creating a new project. When you use crosscomplilation ignore steps 2 and 3.

  1. In the Main Menu open go to File → Settings.

  1. go to CMake toolchain select remote host.

The Config Folder

Configuring your C++ Motorcortex project has to be done in the config folder. Here you can configurate EtherCAT-devices, Controller Configuration in the config.json file and manage your certificate.

control

In the control folder you will find the control.xml in this xml file you can.

io

In the io folder you can configurate your io devices. this has to be done configuring the master.xml and topology.xml

master.xml

topology.xml

config.json

demo-cert.pem

The Control Folder

The Logic Folder

Main.cpp

The main.cpp is

Programming Concepts

Modules and Tasks

A Motorcortex application is built around the concept of Modules and Tasks. A Module is an object that performs calculations based on inputs and internal variables and produces outputs. Inputs are either set directly from a higher level Module (via a setter function) or are set via the Parameter Tree.

Below a template for a Module header file is shown.

//Module header
#ifndef MAINCONTROLLOOP_H
#define MAINCONTROLLOOP_H
#include <mcx/mcx_core.h>

class MainControlLoop : public mcx::container::Module {
public:
  MainControlLoop() = default;
  ~MainControlLoop() override = default;
private:
  void create_(const char* name, mcx::parameter_server::Parameter* parameter_server, uint64_t dt_micro_s) override;
  bool initPhase1_() override;
  bool initPhase2_() override;
  bool startOp_() override;
  bool stopOp_() override;
  bool iterateOp_(const mcx::container::TaskTime& system_time, mcx::container::UserTime* user_time) override;
  double myDouble_{0};
};

#endif /* MAINCONTROLLOOP_H */

The module is a passive object, which means that it does not have an execution thread and must be executed by a Task object. A Task plays the role of an execution thread. Modules can be registered in the Task, which will allocate required resources, like CPU, scheduler policy, priority and start to execute modules sequentially in a loop.

The Module State Machine

All Motorcortex modules have a certain structure, which describes the life-cycle of the module. Modules go through different phases of the life-cycle during startup according to the schematic below.

   Module:                                        Task:
   ┌──────────────────────────────┐                        
   │   Not Initialized            │                 
   └───┬──────────────────────────┘               ┌─────────────────────────────────────┐    
       │ (Event: create)                          │ Creates modules and submodules.     │
   ┌───v───────┐                                  └───┬─────────────────────────────────┘
   │   Phase0  │                                      │ (Event: configure)
   └───┬───────┘                                  ┌───v─────────────────────────────────┐
       │ (Event: initPhase1)                      │ Add parameters to the tree          │  
       │                                          │                                     │           
   ┌───v───────┐                                  └───┬─────────────────────────────────┘
   │   Phase1  │                                      │ (Event: start)  
   └───┬───────┘                                  ┌───v─────────────────────────────────┐  
       │ (Event: initPhase2)                      │ Parameter tree is ready,            │
       │                                          │                                     │
   ┌───v──────────────────────────┐               └───┬─────────────────────────────────┘           
   │   Phase2                     │                   │    
   └───┬──────────────────────^───┘               ┌───v─────────────────────────────────┐
       │ (Event: startOp)     │ (Event: stopOp)   │  Real-time event loop is            │ 
       │                      │                   │  ready to start.                    │
   ┌───v──────────────────────┴───┐               └─────────────────────────────────────┘
   │   Operation                  │                  
   └───┬──────────────────────────┘  
       │ (Event: exit)
   ┌───v───────┐
   │ Destroyed │
   └───────────┘

Modules are first created by calling the Module’s create function. This in turn calls the create method of all sub-modules to register all the Modules in the Parameter Tree.

Then the Modules are added to a Task and the Task’s configure method is called. This calls initPhase1 of all the (sub-)modules. In initPhase1 all (sub-)modules shall add their Parameters to the Parameter Tree.

Now that the Tree is complete and running (Phase1), Parameter values can be loaded from a file.

Then the Task can be started by calling it’s start method. This calls the initPhase2 methods of all (sub-)modules and then startOp, just before the task switches to realtime mode.

In operation state, the system cyclically calls the Module’s iterateOp method that calculates the new state in each timestep. In the iterateOp method all submodules also need to be iterated.

Creating submodules (create)

Submodules are created in the create method of their parent Module, like shown below. The submodule then registers its own parameters and submodules in the tree.

void MainControlLoop::create_(const char* name,
  mcx::parameter_server::Parameter* parameter_server,
  uint64_t dt_micro_s) {
  createSubmodule(&mySubmodule, "mySubmodule");
}

Registering Parameters (initPhase1)

In initPhase1 the Module’s parameters need to be registered into the Parameter Tree.

bool MainControlLoop::initPhase1_() {
  using ParameterType = mcx::parameter_server::ParameterType;
  addParameter("input", ParameterType::INPUT,&input_);
  addParameter("gain", ParameterType::PARAMETER, &gain_);
  addParameter("output", ParameterType::OUTPUT, &output);
  return true;
}

The ParameterType can be set to one of the types as specified in paragraph Parameter Types in Motorcortex.

Optional callbacks for special cases (initPhase2, startOp, stopOp)

The initPhase2 method is in general not used. In special cases, it can be used for additional initializations, memory allocations, validations of the loaded parameters.

The startOp and stopOp methods can be used to set and reset module state during start/stop routine.

It is not recommended to put any delays or blocking calls in these callbacks, because they can cause a significant delay during module startup.

Iterating (iterateOp)

Calculations shall be done in the Module’s iterateOp method. The iterateOp method of the top-level Module is called cyclically by the corresponding Task. The top-level module then iterates submodules from its own iterateOp method. For instance:

bool MainControlLoop::iterateOp_(const container::TaskTime& system_time, container::UserTime* user_time) {
   submodule.setInput(input);
   submodule.iterate(system_time, user_time);
   double subOutput = submodule.getOutput();
   output_ = gain_ * input_ + subOutput * getDtSec();
   return true;
}

Usually, for a submodule, first the inputs are set, then the module is iterated, then the outputs are read.

For a lot of digital control systems the step size is required in calculations (e.g. for calculating filters or integrators). The application cycle time in seconds can be obtained by calling the getDtSec() function. The getDtSec function returns the configured cycle time of the Task, not the actual cycle time (which may vary a small amount each cycle).

Overriding inputs and outputs

If the Module’s inputs are set via the Parameter Tree, the inputs can be overridden (forced) at runtime. Outputs can also be overridden before they are updated into the Parameter Tree. The output overrides have no effect on the actual variable value of the module. Also a parameter tree input might have no effect if its associated variable is set directly via a setter function.

Application Configuration.

Tasks

Tasks provide the execution environment of Motorcortex Modules. Each Task can manage multiple Modules. A Task also switches the Modules through the Module State Machine.

The iterate methods of all the Modules inside a Task are called cyclically with the update rate that was specified when the Task is created. The Modules are iterated sequentially in the order they were added to the Task.

 // creates a Module
 mcx::log::Module myModule();
 myModule.create("myModule", &param_server, rt_dt_micro_s);
 // create and configure the task
 mcx::container::Task myTask("myTask", &param_server);
 myTask.add(&myModule);
 myTask.configure();
 ...
 myTask.start(rt_dt_micro_s, container::TaskSched::REALTIME, {0}, 80);

The Logger Task

The Logger is a standard Module that provides logging functions for other Modules to write messages to certain log-levels. The standard log levels are:

  • LOG_DEBUG
  • LOG_INFO
  • LOG_WARNING
  • LOG_ERROR

The log is accessible from inside any module by calling the respective log function. E.g. LOG_INFO(“%d red balloons”,99). The LOG_* functions provide similar syntax to the standard C function printf. An example how the logger Task is created is shown below:

 // creates log output to a file
 mcx::log::Module logger(path_log);
 logger.create("logger", &param_server, rt_dt_micro_s);
 // create and configure log output task
 mcx::container::Task logger_task("Logger_task", &param_server);
 logger_task.add(&logger);
 logger_task.configure();

4.4 - Realtime Configuration

Introduction

MOTORCORTEX is designed for running Tasks with hard-realtime deadlines. It does this without using special hypervisors that execute code within their own environment and scheduler. MOTORCORTEX uses the realtime capabilities of the latest standard Linux kernels, which makes it possible to run userspace applications with very stringent hard-realtime deadlines. For optimal performance, Vectioneer provides specially tuned Linux distributions that have been tested on a wide range of hardware, like the CX range of industrial embedded computers from Beckhoff, Compulab’s Fitlet2, the Aaeon UP², Siemens Simatic IPC127E IOT gateways and even System-On-Chips (SoC) like the Raspberry Pi or NanoPi.

Since MOTORCORTEX applications are user-space applications they can also be compiled to run in non-realtime on any platform that supports Linux. This may be sufficient for a lot of applications that only need soft-realtime.

In this chapter it will be shown how to configure a MOTORCORTEX application for hard-realtime and give some pointers how to get the best possible performance and what to avoid.

The do’s and don’ts of hard-realtime

Hard-realtime is very difficult to achieve in a general purpose operating systems, especially on modern CPUs or systems that have a lot of features that may interrupt the realtime process. Especially hardware interrupts always have been a problem for realtime, like interacting with USB devices or video cards. Modern systems are generally tuned for speed (or responsiveness) and not for realtime (deterministic) behavior; snappy response to user inputs for instance is then prioritized over calculations done in the background.

Luckily, in Linux this realtime or low-latency requirement has been taken very seriously by Kernel developers and a lot of development has already gone into making Linux a general purpose operating system with uncompromised real-time capability. This originated with the PREEMPT_RT patch that was originally published by Thomas Gleixner and Ingo Molnar, which currently has reached maturity to be included into the standard (Vanilla) Linux Kernel.

Currently, with a tuned Linux kernel the same performance can be achieved as with dedicated Realtime Operating Systems or hypervisors.

In general, to make a realtime Task run such that it never misses a beat, follow the following rules:

  • (De-)Allocate memory before realtime is needed. Reduce or better eliminate dynamic memory allocations during an iterate task (e.g. avoid using new in C++). Do not use blocking calls; for example for IO calls. Be careful with using external libraries in your code that are not designed to be real-time-capable.
  • Reduce the amount of page-faults as much as possible.
  • Do not use the CPU’s C-States. C-States are there to put system into (partial) sleep or reduce clock speeds when the system load allows this. When this happens probably realtime performance will be badly affected. Disable C-States in the BIOS. The negative consequence of this is that the system will consume more power and generate more heat than usual. Check if the system is sufficiently cooled.
  • Some CPUs throttle their throughput when the temperature rises above some point. Make sure there is adequate cooling for the task, and test realtime performance under full load in a worst-case environment.

The good news is that MOTORCORTEX already takes care of a lot of tuning and configuration for you.

Assigning Tasks to CPUs

To run tasks in realtime, the CPUs that are going to be used for realtime must be isolated, so other processes cannot use these CPUs.

// start low latency, isolate CPU 0 and 1
utils::startRealTime({0, 1});

As soon as these CPU cores are isolated, other tasks are pushed off these CPUs onto other CPUs. Make sure that not all CPUs are isolated, Linux itself needs at least one CPU to run.

Tasks can be configured to run with different schedulers. Currently the following scheduler policies are supported:

enum class TaskSched {
 NORMAL = SCHED_OTHER, // Default non-realtime policy.
 REALTIME = SCHED_FIFO, // Default realtime policy.
 REALTIME_FIFO = SCHED_FIFO, // Realtime FIFO policy.
 REALTIME_RR = SCHED_RR // Realtime Round-Robin policy.
};

When a task is started it can be assigned to a scheduler, to a number of CPUs, with a certain priority. In general, for non-realtime tasks the NORMAL scheduler is used and for realtime tasks the REALTIME scheduler is used:

// start logger and communication with non-realtime scheduler
logger_task.start(rt_dt_micro_s,
container::TaskSched::NORMAL);
comm_task.start(rt_dt_micro_s, container::TaskSched::NORMAL);
// start control and ethercat with realtime scheduler,
// attach to isolated CPUs 0 and 1, set priorities to 80
controls_task.start(rt_dt_micro_s,
container::TaskSched::REALTIME, {0}, 80);
ethercat_task.start(rt_dt_micro_s,
container::TaskSched::REALTIME, {1}, 80);

Adjusting timing with secaligned

Each task has a secaligned parameter that can be modified through the MOTORCORTEX Parameter Tree. The secalign parameter aligns the Task’s execution cycle with respect to the system monotonic timer. The secaligned value can be set in the normalized range of [0..1], where 1 corresponds to a full cycle time of the task.

In general, changing secaligned from its default value is not required.

TBD: Diagram & further explanation

Parallelizing execution; splitting the load into Workers

MOTORCORTEX has a special active container to run callable targets asynchronously. This can be used to parallelize heavy computations inside the control blocks or perform blocking calls asynchronously (without blocking the control loop). The advantage of the MOTORCORTEX Worker is that it can be setup to run on a specific CPU with specific priority and scheduler, by default the Worker inherits these properties from the calling task. It is good practice to create the worker in the startOp phase, when the calling task has all its Realtime related properties set.

bool MainControlLoop::startOp_() {
  // creates the Worker with the same priority and CPU affinity as the calling task
  worker1.create(std::string("worker1");
  // creates the Worker with the Normal priority on the non-isolated CPUs
  worker2.create("worker2", mcx::container::TaskSched::NORMAL, mcx::utils::getAvailableCpu());
  return true;
}
bool MainControlLoop::iterateOp_(const container::TaskTime& system_time, container::UserTime* user_time) {
  // moving half of the control loops to the worker
  unsigned int split_the_work = number_of_control_loops / 2;
  for (unsigned int cnt = 0; cnt < split_the_work; cnt++) {
    worker1.start([&, cnt]() {
      punchControl_[cnt].iterate(system_time, user_time);
    });
  }
  // computing the other half in the task
  for (unsigned int cnt = split_the_work; cnt < number_of_control_loops; cnt++) {
    punchControl_[cnt].iterate(system_time, user_time);
  }
  // Important: wait for the worker to finish
  worker1.join(0);
}

4.5 - Debugging

Cycletime and utilization

Cycle Time and Utilization

MOTORCORTEX Tasks show statistical information in the Parameter Tree that can indicate problems with performance:

  • absolute_cycle_max; maximum cycle time in microseconds since the last reset
  • actual_cycle_max; maximum cycle time over the last second
  • desired_cycle_time_micro_s; the target cycle time in microseconds
  • reset_absolute_cycle_max; if set to 1 the absolute_cycle_max is reset to zero
  • utilization_max; the amount of time the task takes in percentage of the desired_cycle_time_micro_s

Linux debugging tools

There are a number of Linux tools that can deep-dive into your application and the system:

4.6 - Motorcortex APIs

Motorcortex provides a number of libraries with different features:

  • mcx-core;
    the mcx-core library is required as a minimum for a Motorcortex application, it provides a convenient abstraction for Hard-Realtime applications, EtherCAT and secure Communication Middleware.

  • mcx-math;
    mcx-math provides common math objects suitable for use in realtime applications, like a matrix class, rotation, 6DOF pose and helper functions to convert between reference frames

  • mcx-control;
    mcx-control provides object for control systems, such as filters, limiters, switches, PID controller, faders, signal generators

  • mcx-mechanics;
    the mcx-mechanics library provides mechanical function blocks, like serial and parallel forward and inverse kinematics and dynamics, rigid body simulation

  • mcx-electrics;
    mcx-electrics provides currently simulation blocks to simulate an encoder, an electric motor and a emergency stop relay.

  • mcx-hydraulics;
    mcx-hydraulics provides function blocks for hydraulic systems, like accurate simulation of hydraulic valves and actuators and control blocks like a hydraulic control loop, valve correction

  • mcx-motion;
    mcx-motion provides a path planner and a motion interpreter used for robot control

4.7 -

Developing Motorcortex Applications in CPP

Introduction

MOTORCORTEX provides out of the box solution to develop Hard-Realtime Control Applications in C++ with an integrated high-speed and secured communication for distributed systems. It supports popular industrial buses, like EtherCAT.

The Parameter Tree

The MOTORCORTEX Parameter Tree

In a MOTORCORTEX application all control Modules are organized in a tree structure. The Parameter Tree contains a snapshot of all the inputs, outputs and internal data of the control objects at the current time.

Each control Module is represented as a subtree (folder). Modules can be nested. In a general control application there is usually a “Logic”, “Control” and also an “EtherCAT” folder that represents the data of the corresponding tasks.

Inside the folders the data of the associated Module is contained. MOTORCORTEX currently supports the following datatypes in the Tree: boolean, integer, double or binary (e.g. a C-struct). Also arrays of a single datatype are supported. Array elements start at index 0 (zero).

The MOTORCORTEX-Desk web-application can be used to connect to a MOTORCORTEX application

Parameter Types in MOTORCORTEX

This subsection shortly describes how the different parameter types can be used in combination with EtherCAT.

The MOTORCORTEX structure has the following parameter types:

  • Input: In this parameter type a value can be written. In MOTORCORTEX-Desk an input is depicted as .
  • Output: this parameter type is read-only. In MOTORCORTEX-Desk an output is depicted as .
  • Parameter: This is parameter type that is used to configure the system. Typical uses are parameters and system constants. Parameters are retrieved from the parameter list during start-up. If the user changes a value and wants to use in the future, he has to save the list before rebooting/switching off the controller. A parameter can be read and written. In MOTORCORTEX-Desk an parameter is depicted as .
  • Persistent: these are values that contain process data that is continuously updated and will be retained through application restarts. Typical applications are running ours or amount of produced products. In MOTORCORTEX-Desk an persistent is depicted as .

Setting up a development environment

Introduction

Vectioneer uses CMake (https://cmake.org/) as its main tool for building, testing and deploying software. Also MOTORCORTEX itself is built using CMake. CMake is widely accepted and supported by many IDEs, which means that the user is free to choose his/her own development environment.

To make things more convenient, Vectioneer has developed plugins for CLion (https://www.jetbrains.com/clion). CLion is an advanced Integrated Development Environment that has many tools that make programming easy, is available across platforms and is capable to cross-compile and deploy MOTORCORTEX applications straight to the controller with a click of a button.

This chapter is a guide, how to install CLion and the MOTORCORTEX plugins from the CLion Marketplace and get started quickly with developing MOTORCOREX applications.

Installing CLion

Download CLion for your platform from: https://www.jetbrains.com/clion/download;

Run the install script.

Installing the MOTORCORTEX Templates plugin

Start CLion.

In the Main Menu open: File → Settings, then find the Plugins menu.

CLion plugins menu

In the search section type motorcortex, then click Install.

Motorcortex Templates Plugin

The MOTORCORTEX development toolchain

There are two options how to develop MOTORCORTEX applications:

  • use remote development and compile the application on the MOTORCORTEX Target System;
  • cross-compile on your development PC and deploy the executable to the MOTORCORTEX Target System

The first method is easy to set up, it does not require additional dependencies however the downside is that a compile time for the large projects may be significant. The second method overcomes this problem, but requires a cross-compilation tool-chain to be set up.

Setting up remote development in CLion

In the Main Menu open: File → Settings, find the Toolchains menu.

CLion Toolchains menu

Select Environment type: Remote Host. Enter the remote host credentials and press OK, wait for a few seconds to let CLion find all the necessary tools.

Configure Remote Credentials

The remote toolchain is now ready to use.

Setting up cross-compilation in CLion (Linux)

Download the development toolchain from our public git repository:

https://git.vectioneer.com/pub/motorcortex-sdk

To download latest snapshot, click on the button marked with red colour.

Extract downloaded archive to the local folder. Open the Terminal and execute:

motorcortex-glibc-x86_64-motorcorcortex-image-dev-corei7-64-toolchain-X.X.X.sh

Enter the target directory where to install the SDK to. It is a good idea to keep the SDK in the home folder, where administrative rights are not required: (for example ~/mcx-sdk):

Start CLion and install the MOTORCORTEX Toolchain plugin. To install the plugin, open File → Settings → Plugins. Then, in the Marketplace section, type “motorcortex”. Install the plugin and restart CLion.

Installing the MOTORCORTEX Toolchain plugin

Before working with a remote MOTORCORTEX host, make sure that the host is connected and reachable.

Use ssh-copy-id to provide a temporary access without a password to the remote MOTORCORTEX host.

ssh-copy-id <admin@192.168.2.100>

If there is an error: No identities found, run ssh-keygen to **generate a new key pair and run ssh-copy-id command again.

ssh-keygen -t rsa

Open Terminal and create a folder to mount the remote MOTORCORTEX file system on.

mkdir \~/mcx-sysroot

Mount MOTORCORTEX file system with the following command:

sshfs admin@192.168.2.100:/ \~/mcx-sysroot/

Configure the compiler paths to use the MOTORCORTEX cross-compilation toolchain.

Open File → Settings → Build, Execution, Deployment → Toolchains. Create a new System Toolchain with the name motorcortex.

Fill in Make, C Compiler and C++ Compiler paths to point the MOTORCORTEX SDK as shown below.

Configure sysroot path to use the latest MOTORCORTEX libraries from the remote host.

Open File → Settings → Build, Execution, Deployment → Motorcortex SDK and fill in the path to the mounted folder (mcx-sysroot) in the field “Sysroot path”. The other field on this screen are left empty.

Add the connection to the remote MOTORCORTEX host. Open Tools → Deployment → Configuration menu, add a new SFTP connection and fill in the details (see below). Press the Test Connection button to make sure that the filled data is correct. Press the Autodetect button to set the root path. Uncheck the Visible only for this project checkbox make this host visible in all the projects.

Cross-compiling MOTORCORTEX applications.

In CLion open the project configuration menu.

Click on + and select Motorcortex Remote Application. In the deployment profile field select MOTORCORTEX remote host.

In the Run/Debug configuration select the just created cross-compiled application with CrossRelease or CrossDebug build profile. Press the hammer button to cross-compile, play to copy and run on the remote MOTORCORTEX host and the bug button to start a remote debug session.

Deployment and Auto-start of applications.

TBD

Alternative build environments and IDEs

Since the MOTORCORTEX development environment uses CMake as its main tool, development can also easily be setup in other IDEs like Eclipse, NetBeans or Microsoft Visual Code. Also CMake can be used from the command line if one wishes. Refer to your IDE’s documentation on how to setup your environment to work with CMake.

Code can always be compiled on the Vectioneer Linux Target System, since that has everything on-board to compile MOTORCORTEX projects. In general you can build the application by using the default vuild method of clion:

Copy your project onto the Target System (e.g. /home/admin/myProject/).

Then login to the Target system via SSH (on a Windows system you can use Putty).

Navigate to the Project folder:

cd /home/admin/myProject

Make an empty build folder and enter it:

mkdir build
cd build

Run cmake, compile and install:

cmake ..
make
sudo make install

Generating a template for a MOTORCORTEX Application

It easy to create a new MOTORCORTEX application from the existing template.

In the CLion main menu select File → New → C++ Motorcortex. Then enter a new location for you project. If your project requires a logic Task, check the box to generate a Logic template.

Generating a Motorcortex application from a template

The generated template has the following structure:

  • A main.cpp file, where all system and task configuration and linking of parameters happens. The generated main.cpp already has all the required code, necessary to run a Hard-Real Time application and communication server.
  • the control folder contains a template of the main control loop Module. This where all the control computation happens.
  • the logic folder (optional) contains a template of the Finite State Machine to build advanced logic.
  • the config folder includes saved values of the module’s parameters and EtherCAT configuration.

Source tree structure

Programming Concepts

Modules and Tasks

A MOTORCORTEX application is built around the concept of Modules and Tasks. A Module is an object that performs calculations based on inputs and internal variables and produces outputs. Inputs are either set directly from a higher level Module (via a setter function) or are set via the Parameter Tree.

Below a template for a Module header file is shown.

//Module header
#ifndef MAINCONTROLLOOP_H
#define MAINCONTROLLOOP_H
#include <mcx/mcx_core.h>

class MainControlLoop : public mcx::container::Module {
public:
  MainControlLoop() = default;
  ~MainControlLoop() override = default;
private:
  void create_(const char* name, mcx::parameter_server::Parameter* parameter_server, uint64_t dt_micro_s) override;
  bool initPhase1_() override;
  bool initPhase2_() override;
  bool startOp_() override;
  bool stopOp_() override;
  bool iterateOp_(const mcx::container::TaskTime& system_time, mcx::container::UserTime* user_time) override;
  double myDouble_{0};
};

#endif /* MAINCONTROLLOOP_H */

The module is a passive object, which means that it does not have an execution thread and must be executed by a Task object. A Task plays the role of an execution thread. Modules can be registered in the Task, which will allocate required resources, like CPU, scheduler policy, priority and start to execute modules sequentially in a loop.

The Module State Machine

All MOTORCORTEX modules have a certain structure, which describes the life-cycle of the module. Modules go through different phases of the life-cycle during startup according to the schematic below.

   Module:                                        Task:
   ┌──────────────────────────────┐                        
   │   Not Initialized            │                 
   └───┬──────────────────────────┘               ┌─────────────────────────────────────┐    
       │ (Event: create)                          │ Creates modules and submodules.     │
   ┌───v───────┐                                  └───┬─────────────────────────────────┘
   │   Phase0  │                                      │ (Event: configure)
   └───┬───────┘                                  ┌───v─────────────────────────────────┐
       │ (Event: initPhase1)                      │ Add parameters to the tree          │  
       │                                          │                                     │           
   ┌───v───────┐                                  └───┬─────────────────────────────────┘
   │   Phase1  │                                      │ (Event: start)  
   └───┬───────┘                                  ┌───v─────────────────────────────────┐  
       │ (Event: initPhase2)                      │ Parameter tree is ready,            │
       │                                          │                                     │
   ┌───v──────────────────────────┐               └───┬─────────────────────────────────┘           
   │   Phase2                     │                   │    
   └───┬──────────────────────^───┘               ┌───v─────────────────────────────────┐
       │ (Event: startOp)     │ (Event: stopOp)   │  Real-time event loop is            │ 
       │                      │                   │  ready to start.                    │
   ┌───v──────────────────────┴───┐               └─────────────────────────────────────┘
   │   Operation                  │                  
   └───┬──────────────────────────┘  
       │ (Event: exit)
   ┌───v───────┐
   │ Destroyed │
   └───────────┘

Modules are first created by calling the Module’s create function. This in turn calls the create method of all sub-modules to register all the Modules in the Parameter Tree.

Then the Modules are added to a Task and the Task’s configure method is called. This calls initPhase1 of all the (sub-)modules. In initPhase1 all (sub-)modules shall add their Parameters to the Parameter Tree.

Now that the Tree is complete and running (Phase1), Parameter values can be loaded from a file.

Then the Task can be started by calling it’s start method. This calls the initPhase2 methods of all (sub-)modules and then startOp, just before the task switches to realtime mode.

In operation state, the system cyclically calls the Module’s iterateOp method that calculates the new state in each timestep. In the iterateOp method all submodules also need to be iterated.

Creating submodules (create)

Submodules are created in the create method of their parent Module, like shown below. The submodule then registers its own parameters and submodules in the tree.

void MainControlLoop::create_(const char* name,
  mcx::parameter_server::Parameter* parameter_server,
  uint64_t dt_micro_s) {
  createSubmodule(&mySubmodule, "mySubmodule");
}

Registering Parameters (initPhase1)

In initPhase1 the Module’s parameters need to be registered into the Parameter Tree.

bool MainControlLoop::initPhase1_() {
  using ParameterType = mcx::parameter_server::ParameterType;
  addParameter("input", ParameterType::INPUT,&input_);
  addParameter("gain", ParameterType::PARAMETER, &gain_);
  addParameter("output", ParameterType::OUTPUT, &output);
  return true;
}

The ParameterType can be set to one of the types as specified in paragraph Parameter Types in MOTORCORTEX.

Optional callbacks for special cases (initPhase2, startOp, stopOp)

The initPhase2 method is in general not used. In special cases, it can be used for additional initializations, memory allocations, validations of the loaded parameters.

The startOp and stopOp methods can be used to set and reset module state during start/stop routine.

It is not recommended to put any delays or blocking calls in these callbacks, because they can cause a significant delay during module startup.

Iterating (iterateOp)

Calculations shall be done in the Module’s iterateOp method. The iterateOp method of the top-level Module is called cyclically by the corresponding Task. The top-level module then iterates submodules from its own iterateOp method. For instance:

bool MainControlLoop::iterateOp_(const container::TaskTime& system_time, container::UserTime* user_time) {
   submodule.setInput(input);
   submodule.iterate(system_time, user_time);
   double subOutput = submodule.getOutput();
   output_ = gain_ * input_ + subOutput * getDtSec();
   return true;
}

Usually, for a submodule, first the inputs are set, then the module is iterated, then the outputs are read.

For a lot of digital control systems the step size is required in calculations (e.g. for calculating filters or integrators). The application cycle time in seconds can be obtained by calling the getDtSec() function. The getDtSec function returns the configured cycle time of the Task, not the actual cycle time (which may vary a small amount each cycle).

Overriding inputs and outputs

If the Module’s inputs are set via the Parameter Tree, the inputs can be overridden (forced) at runtime. Outputs can also be overridden before they are updated into the Parameter Tree. The output overrides have no effect on the actual variable value of the module. Also a parameter tree input might have no effect if its associated variable is set directly via a setter function. Application Configuration

Tasks

Tasks provide the execution environment of MOTORCORTEX Modules. Each Task can manage multiple Modules. A Task also switches the Modules through the Module State Machine.

The iterate methods of all the Modules inside a Task are called cyclically with the update rate that was specified when the Task is created. The Modules are iterated sequentially in the order they were added to the Task.

 // creates a Module
 mcx::log::Module myModule();
 myModule.create("myModule", &param_server, rt_dt_micro_s);
 // create and configure the task
 mcx::container::Task myTask("myTask", &param_server);
 myTask.add(&myModule);
 myTask.configure();
 ...
 myTask.start(rt_dt_micro_s, container::TaskSched::REALTIME, {0}, 80);

The Parameter Tree

In a MOTORCORTEX application all Modules and variables are organized in a tree structure; the Parameter Tree. The Parameter Tree is used to communicate data between tasks and to the outside world in a thread-safe manner. In the tree the modules are represented as subtrees (folder) and variables are represented as leafs.

The Parameter Tree contains a snapshot of all the registered inputs, outputs and internal data of the modules at the current time. Each Task or Module can create its own subtrees (folder) in the Parameter Tree. Modules can be nested and register their own parameters in the Tree.

The Parameter Tree always starts from the root node, which is passed to the modules and tasks that then can register their own parameters or create submodules that register their own data.

  parameter_server::Parameter param_server;
  // creates root of the parameter tree
  param_server.create("root", nullptr);
  // creates log output to a file
  mcx::log::Module logger(path_log);
  logger.create("logger", &param_server, rt_dt_micro_s);
  // create and configure log output task
  mcx::container::Task logger_task("Logger_task", &param_server);
  logger_task.add(&logger);
  logger_task.configure();

The Communication Server

The Communication Server provided by MOTORCORTEX has two parts:

  1. the first part is a Signaling Server which uses a Request/Reply reliable messaging pattern.
  2. The second part is a Publishing Server or Publisher which uses a Publish/Subscribe best-effort delivery messaging pattern.

A Signaling Server is required for Remote Procedure Calls and for managing the control application, for example updating parameter values. It is also responsible for managing the Publishing Server.

The Publishing Server can organize data into groups and publish them with the requested frequency. The Publisher is used to send Real-time data continuously.

The Signaling Server is set up in the main(…) function and runs until a terminating signal is received.

  // creates req/rep server
  comm::RequestReply reqrep;
  // when all modules are configured req/rep caches the parameter tree
  reqrep.configure(&param_server, path_control_dir);
  bool is_connected = reqrep.start(cmd_args.conn_data);
  ASSERT(is_connected, "Failed to start Req/Rep server");
  // running until terminate signal is received
  while (utils::running()) {
    reqrep.iterate();
  }

Because the Publisher has a cyclic behavior, it is added to a Task that executes it with the given update rate. An example how the publisher is created is shown below:

 // creates the req/rep server
 comm::RequestReply reqrep;
 // creates the publisher module
 comm::Publisher publisher(reqrep, cmd_args.conn_data);
 publisher.create("ParamPub", &param_server, rt_dt_micro_s);
 // creates and configures the communication task
 container::Task comm_task("Comm_task", &param_server);
 comm_task.add(&publisher);
 comm_task.configure();
 // when all modules are configured req/rep caches the parameter tree
 reqrep.configure(&param_server, path_control_dir);
 comm_task.start(rt_dt_micro_s, container::TaskSched::NORMAL);
 ... // start other tasks
 bool is_connected = reqrep.start(cmd_args.conn_data);
 ASSERT(is_connected, "Failed to start Req/Rep server");
 // req/rep server is used to create the main loop because it is blocking
 while **(utils::running()) {
   reqrep.iterate();
 }
 // stop req/reply server
 reqrep.stop();
 // stop all tasks
 comm_task.stop();
 ...

The Logger Task

The Logger is a standard Module that provides logging functions for other Modules to write messages to certain log-levels. The standard log levels are:

  • LOG_DEBUG
  • LOG_INFO
  • LOG_WARNING
  • LOG_ERROR

The log is accessible from inside any module by calling the respective log function. E.g. LOG_INFO(“%d red balloons”,99). The LOG_* functions provide similar syntax to the standard C function printf.

An example how the logger Task is created is shown below:

 // creates log output to a file
 mcx::log::Module logger(path_log);
 logger.create("logger", &param_server, rt_dt_micro_s);
 // create and configure log output task
 mcx::container::Task logger_task("Logger_task", &param_server);
 logger_task.add(&logger);
 logger_task.configure();

Configuring Realtime and Performance

Introduction

MOTORCORTEX is designed for running Tasks with hard-realtime deadlines. It does this without using special hypervisors that execute code within their own environment and scheduler. MOTORCORTEX uses the realtime capabilities of the latest standard Linux kernels, which makes it possible to run userspace applications with very stringent hard-realtime deadlines. For optimal performance, Vectioneer provides specially tuned Linux distributions that have been tested on a wide range of hardware, like the CX range of industrial embedded computers from Beckhoff, Compulab’s Fitlet2, the Aaeon UP², Siemens Simatic IPC127E IOT gateways and even System-On-Chips (SoC) like the Raspberry Pi or NanoPi.

Since MOTORCORTEX applications are user-space applications they can also be compiled to run in non-realtime on any platform that supports Linux. This may be sufficient for a lot of applications that only need soft-realtime.

In this chapter it will be shown how to configure a MOTORCORTEX application for hard-realtime and give some pointers how to get the best possible performance and what to avoid.

The do’s and don’ts of hard-realtime

Hard-realtime is very difficult to achieve in a general purpose operating systems, especially on modern CPUs or systems that have a lot of features that may interrupt the realtime process. Especially hardware interrupts always have been a problem for realtime, like interacting with USB devices or video cards. Modern systems are generally tuned for speed (or responsiveness) and not for realtime (deterministic) behavior; snappy response to user inputs for instance is then prioritized over calculations done in the background.

Luckily, in Linux this realtime or low-latency requirement has been taken very seriously by Kernel developers and a lot of development has already gone into making Linux a general purpose operating system with uncompromised real-time capability. This originated with the PREEMPT_RT patch that was originally published by Thomas Gleixner and Ingo Molnar, which currently has reached maturity to be included into the standard (Vanilla) Linux Kernel.

Currently, with a tuned Linux kernel the same performance can be achieved as with dedicated Realtime Operating Systems or hypervisors.

In general, to make a realtime Task run such that it never misses a beat, follow the following rules:

  • (De-)Allocate memory before realtime is needed. Reduce or better eliminate dynamic memory allocations during an iterate task (e.g. avoid using new in C++). Do not use blocking calls; for example for IO calls. Be careful with using external libraries in your code that are not designed to be real-time-capable.
  • Reduce the amount of page-faults as much as possible.
  • Do not use the CPU’s C-States. C-States are there to put system into (partial) sleep or reduce clock speeds when the system load allows this. When this happens probably realtime performance will be badly affected. Disable C-States in the BIOS. The negative consequence of this is that the system will consume more power and generate more heat than usual. Check if the system is sufficiently cooled.
  • Some CPUs throttle their throughput when the temperature rises above some point. Make sure there is adequate cooling for the task, and test realtime performance under full load in a worst-case environment.

The good news is that MOTORCORTEX already takes care of a lot of tuning and configuration for you.

Assigning Tasks to CPUs

To run tasks in realtime, the CPUs that are going to be used for realtime must be isolated, so other processes cannot use these CPUs.

// start low latency, isolate CPU 0 and 1
utils::startRealTime({0, 1});

As soon as these CPU cores are isolated, other tasks are pushed off these CPUs onto other CPUs. Make sure that not all CPUs are isolated, Linux itself needs at least one CPU to run.

Tasks can be configured to run with different schedulers. Currently the following scheduler policies are supported:

enum class TaskSched {
 NORMAL = SCHED_OTHER, // Default non-realtime policy.
 REALTIME = SCHED_FIFO, // Default realtime policy.
 REALTIME_FIFO = SCHED_FIFO, // Realtime FIFO policy.
 REALTIME_RR = SCHED_RR // Realtime Round-Robin policy.
};

When a task is started it can be assigned to a scheduler, to a number of CPUs, with a certain priority. In general, for non-realtime tasks the NORMAL scheduler is used and for realtime tasks the REALTIME scheduler is used:

// start logger and communication with non-realtime scheduler
logger_task.start(rt_dt_micro_s,
container::TaskSched::NORMAL);
comm_task.start(rt_dt_micro_s, container::TaskSched::NORMAL);
// start control and ethercat with realtime scheduler,
// attach to isolated CPUs 0 and 1, set priorities to 80
controls_task.start(rt_dt_micro_s,
container::TaskSched::REALTIME, {0}, 80);
ethercat_task.start(rt_dt_micro_s,
container::TaskSched::REALTIME, {1}, 80);

Adjusting timing with secaligned

Each task has a secaligned parameter that can be modified through the MOTORCORTEX Parameter Tree. The secalign parameter aligns the Task’s execution cycle with respect to the system monotonic timer. The secaligned value can be set in the normalized range of [0..1], where 1 corresponds to a full cycle time of the task.

In general, changing secaligned from its default value is not required.

TBD: Diagram & further explanation

Parallelizing execution; splitting the load into Workers

MOTORCORTEX has a special active container to run callable targets asynchronously. This can be used to parallelize heavy computations inside the control blocks or perform blocking calls asynchronously (without blocking the control loop). The advantage of the MOTORCORTEX Worker is that it can be setup to run on a specific CPU with specific priority and scheduler, by default the Worker inherits these properties from the calling task. It is good practice to create the worker in the startOp phase, when the calling task has all its Realtime related properties set.

bool MainControlLoop::startOp_() {
  // creates the Worker with the same priority and CPU affinity as the calling task
  worker1.create(std::string("worker1");
  // creates the Worker with the Normal priority on the non-isolated CPUs
  worker2.create("worker2", mcx::container::TaskSched::NORMAL, mcx::utils::getAvailableCpu());
  return true;
}
bool MainControlLoop::iterateOp_(const container::TaskTime& system_time, container::UserTime* user_time) {
  // moving half of the control loops to the worker
  unsigned int split_the_work = number_of_control_loops / 2;
  for (unsigned int cnt = 0; cnt < split_the_work; cnt++) {
    worker1.start([&, cnt]() {
      punchControl_[cnt].iterate(system_time, user_time);
    });
  }
  // computing the other half in the task
  for (unsigned int cnt = split_the_work; cnt < number_of_control_loops; cnt++) {
    punchControl_[cnt].iterate(system_time, user_time);
  }
  // Important: wait for the worker to finish
  worker1.join(0);
}

Debugging

Cycletime and utilization

Cycle Time and Utilization

MOTORCORTEX Tasks show statistical information in the Parameter Tree that can indicate problems with performance:

  • absolute_cycle_max; maximum cycle time in microseconds since the last reset
  • actual_cycle_max; maximum cycle time over the last second
  • desired_cycle_time_micro_s; the target cycle time in microseconds
  • reset_absolute_cycle_max; if set to 1 the absolute_cycle_max is reset to zero
  • utilization_max; the amount of time the task takes in percentage of the desired_cycle_time_micro_s

Linux debugging tools

There are a number of Linux tools that can deep-dive into your application and the system:

5 -

configure_AX5805_AX5806
configure-twinsafe_single_channel
create-twinsafe-project
link-twinsafe-project
upload-safety-project-TwinCAT
upload-safety-project-TwinSAFEloader

Motorcortex makes it possible to run Safety over EtherCAT. Here the user can find how to get going using Beckhoffs TwinCAT to upload and develope safety software.

5.1 -

Link TwinSAFE single channel devices

TwinSAFE SC (single channel) is an extension on TwinSAFE that allows Safe Single Channel data to be combined with non-safe modules, where a continuous cross-check of two signals checks the validity of the signals. Considering the price difference between safe terminals and non-safe terminals this can be interesting. Another (even bigger) advantage is that with TwinSAFE SC terminals, TwinSAFE was extended with the possibility to read-in safe analog signals, bringing new capabilities.

Introduction

This chapter gives an example how TwinSAFE Single Channel©® components can integrated in a TwinSAFE projet with help of TwinCAT©®. This is a different, since opposite to standard TwinSAFE components, TwinSAFE SC components do not have DIP-switches/Dials to set the FSoE address and the FSoE address is assigned via TwinCAT, which needs to be uploaded to the device during EtherCAT initialization.

Configuring a TwinSAFE Single Channel device in TwinCAT

Requirements programming computer

Requirements:

  • TwinCAT 3 on a computer
  • Ethernet port on the computer

Steps:

  • Connecting to EtherCAT devices and scan EtherCAT bus in TwinCAT
  • Set-up the TwinSAFE SC devices in TwinCAT
  • Link the TwinSAFE SC devices within TwinSAFE environment of TwinCAT
  • Setup TwinSAFE SC in MotorCortex

Connecting to EtherCAT devices and scan EtherCAT bus in TwinCAT

See create-twinsafe-project.md

Set-up the TwinSAFE SC devices in TwinCAT

Check project and upload

Setup TwinSAFE SC in MotorCortex

  1. link index as normal
  2. add start-up file

5.2 -

Link TwinSAFE single channel devices

Introduction

This chapter gives an example how TwinSAFE Single Channel©® components can integrated in a TwinSAFE projet with help of TwinCAT©®. This is a different, since opposite to standard TwinSAFE components, TwinSAFE SC components do not have DIP-switches/Dials to set the FSoE address and the FSoE address is assigned via TwinCAT, which needs to be uploaded to the device during EtherCAT initialization.

Configuring a TwinSAFE Single Channel device in TwinCAT

Requirements programming computer

Requirements:

  • TwinCAT 3 on a computer
  • Ethernet port on the computer

Steps:

  • Connecting to EtherCAT devices and scan EtherCAT bus in TwinCAT
  • Set-up the TwinSAFE SC devices in TwinCAT
  • Link the TwinSAFE SC devices within TwinSAFE environment of TwinCAT
  • Setup TwinSAFE SC in MotorCortex

Connecting to EtherCAT devices and scan EtherCAT bus in TwinCAT

See create-twinsafe-project.md

##Hardware Installation of Safety Card into the drive

  • have the drive system switched off both for both AC as 24VDC Up an Us.
  • Wait until the DC bus is below 50V or for 5 minutes
  • remove the dummy card from the safety slot
  • set the correct FSoE address with the dip-switches
  • install the AX5805/AX5806
  • switch on the system

TwinCAT configuration

  • scan the topology in TwinCAT

  • select the amount of axes (1 or 2) from your drive

  • at the AX5000 → dirve manager → Device → Safety Option and select in P-0-0200 option 2: AX5805/AX5806

  • Go to your safety project → safety Devices → right mouse → import alias device

  • Go to drive manager → Channel A/B → configuration → Motor and Feedback → copy Motor type, NOT Order code

  • Go to your safety project → safety Devices → AX5805 and double click. On screen that opens, click on “General AX5805 settings” and fill in the exact name. Otherwise the drive will not work.

  • follow the Beckhoff AX5805/AX5806 manual (3.7, page 92-97), copy is saved as PDF (in case of changes in the PDF in the future)

When linking the ESTOP/STO, you need to link all unused functions (not the error-acknowledge of courese), otherwise they will be triggered and eventually trigger the STO function. DO NOT FORGET TO ALSO TO ADD THE SSR that is not in the Beckhoff example If you have only 1 axis, the AX5805 starts bitching about the amount of poles or axis 2, even if Axis2 is disabled on the AX52XX. This is solved by setting Axis 2 in STO mode (in this mode all other things safety things are ignored and it just looks at the STO input (I also linked Axis2 ErrAck and STO, but think it is not needed) upload the safety configuration activate the configuration

p.s. if things do not work, go to IO → Devices → … → AX5805 and double click, go in the opened window to the tab “online” and go all the way to bottom and look at the error at uC1 and uC2. With those error codes, you can search in the documentation for the reason of your error.

##Add safe limited speed calculate the maximum speed (use the spread sheet if needed) in [increments/ms] Go to your safety project → safety Devices → AX5805 and double click. On screen that opens, click on Safety parameters”. Fill in the correct values in the parameters: max speed in [increments/ms] in 0x6693 (axis1), 0x66E3 (axis1), (maybe also t_SLS :001 (0x6691 resp 0x6E91) and t_L SLS :001 (0x6694 resp.0x6E94) Go to your safety project → safety Devices → AX5805 and double click. On screen that opens, click on ”Process Image”. Click on the inputs – below “Axis1 error” and click on “edit”. Select “Axis 1 SLS”, increment “1” and add it. Optionally add the signal also to outputs if you want the feedback of it (and yes, you want that) Below that, do the same for “Axis 1 SLS” increment 2 (for us it contains the maximum speed). Repeat that for axis 2 and for both input as output settings. Save everything upload the safety configuration (I do not know the order, but I think at this step the extra safety parameters (SLS) will become available to the safety editor. Before this, you could not select the SLS and it will be continously active , since the value = 0 (I experienced that) activated configuration link the new SLS in the safety (do not link SLS(2), because then it will receive a 1, and is not continuously active anymore) upload the safety configuration

##Preparation Motorcortex in TwinCAT Per AX5805 save the start-up list, this list will contain all safety parameters. Go to I/O → devices → Drive… → AX5805 and double click. Select the top right tab “startup”. Select all items in the list and right click → export XML description Save the XML on the Motorcortex Controller in the config/IO folder

##Implementation in Motorcortex: Link all FSoE Make sure that you also upload the start-up XML file and linked it

5.3 -

Create TwinSAFE project

Introduction

MOTORCORTEX is especially designed to allow easy and high-performance interaction with real-time control systems from any platform.

For safety it is possible to use existing solutions, like safety PLCs or Safety over EtherCAT (FSoE), developped by Beckhoff. Beckhoff safety modules are called TwinSAFE©® and compatible with EtherCAT.

This chapter describes how to configure TwinSAFE©® components with TwinCAT©® and set-up the FSoE structure in MOTORCORTEX.

Configuring a TwinSAFE project in TwinCAT

Requirements programming computer

Requirements:

  • TwinCAT 3 on a computer
  • Ethernet port on the computer

Steps:

  • Connecting to EtherCAT devices
  • Scan EtherCAT bus in TwinCAT
  • Create a safety project
  • Add physical inputs and outputs and select target system
  • Create logic
  • Adding inputs and outputs to MOTORCORTEX
  • Verify project and uploading it
  • Restarting MOTORCORTEX and setting FSoE up in MOTORCORTEX

Connecting to EtherCAT devices

There are two ways to connect to the EtherCAT devices:

  1. Physically remove the EtherCAT cable from the MOTORCORTEX controller. This has the downside that in most cases the cabinet/enclosure has to be removed, hence option 2

  2. Set MOTORCORTEX in pass-through mode: This option will make the MOTORCORTEX controller act like “dumb” hub, passing the EtherCAT-packages from TwinCAT running on your computer via the ENET port directly to EtherCAT devices. In this means that the cabinet/enclosure does not have to be opened.

Directly connecting the computer to the EtherCAT devices

  1. Remove the EtherCAT connector from the MOTORCORTEX controller and put it in the network adapter of the computer that runs TwinCAT.

Set MOTORCORTEX in pass-through mode

  1. —————————–TBD———————————–

Create EtherCAT topology in TwinCAT

There are two ways to create a topology in TwinCAT:

  1. Scan the EtherCAT bus
  2. Create a topology yourself by selecting components

Scan the EtherCAT bus

NOTE: before scanning, make sure the dip-switches of the safety address are set to the right position on all your safety devices.

NOTE: in some case it is needed to set-up TwinCAT is no real-time network device is found. How to do this can be find in LINK.

  1. Go to the Solution Explorer, IOdevices, right click and select Scan. TwinCAT will show an overview of all available device. Select the ones with “EtherCAT” in the name and continue.

  1. After the scan is completed, you will have an overview like below.

Add the components yourself

If the physical devices are not available, it is also possible to create the topology yourself.

NOTE: This means that the ESI files of the used components should be in the TwinCAT library. TwinCAT per default only has Beckhoff components.

  1. Go to the Solution Explorer, IOdevices, right click and select Add New Item. TwinCAT will show an overview of all devices it has in its library.

  1. Select the device you want to add. Repeat the steps above until you topology is complete.

Create a safety project

The next step is to create the TwinSAFE project.

  1. Go to the Solution Explorer, SAFETY, right click and select Add New Item.

  1. TwinCAT will show an overview of all possible types of projects, select TwinCAT Safety Project Preconfigured Inputs. MOTORCORTEX works by default with this configuration, since it already includes an Error Acknowledge and a Run signal, that will be needed.

  1. Choose as Target System Hardware Safety PLC and as Programming Language Graphical Editor.

  1. Give it a name. In our example GCC_Safety_V01 will be used.

Add physical inputs and outputs and select target system

Next step is too add the physical safety inputs and safety outputs that come from the EtherCAT devices.

  1. Go to Solution Explorer, GCC_Safety_V01GCC_Safety_V01 ProjectTwinSafeGroup1Alias Devices.

  1. Right click and select import Alias-Device.(s)

  1. Select the safety devices you want to add to this project.

  2. After the EtherCAT safety module is added, double click on the device in the Solution Explorer. Check if the FSoE safety address is correct. To take over the dip-switch address, click on the refresh icon left of the field Dip Switch and press on the green left-pointing arrow next to FSoE address to copy it there.

  3. Last, check the Linking Mode:

  • In case that safety device is not the safety PLC (FSoE master) where the project is stored, select Automatic.

  • Some Beckhoff safety devices have integrated TwinSAFE logic (e.g. EL1918), which means that you do not need an additional safety PLC (e.g. EL6910), but you can let the logic also run locally on that device. In that case, select “local” for Linking Mode.

NOTE: the other safety devices will have that particular device as Safety Master and will need “Automatic” for Linking Mode.

  1. Last step is to select the Target System, which is another name for the Safety PLC, which is also the FSoE Master.
  2. First select the go and open the tab Target System which can be found in the safety tree.
  3. Select the Target System which is the type of safety module where the safety logic will run on.
  4. After that, select the Physical Device, where you select which Safety device in the EtherCAT topology will be used as Safety PLC.
  5. Last select the options Map Serial Number Map Project CRC and Take over Standard Alias Device names.

Main Logic

The main logic can be found in TwinSafeGroup1.sai. It can be opened by going to the Solution Explorer, in the Safety Tree and double clicking on TwinSafeGroup1.sai

Safety blocks can be added by opening the Toolbox (ViewToolbox) and dragging safety blocks into the tab of TwinSafeGroup1.sai.

Inputs and outputs can be connected by clicking on an input or output and than dragging a line to the desired output or input.

User Defined Blocks and logic

TwinSAFE has the option to use UFBs: User Defined Blocks. In these block the user can make his own custom logic and integrate the block in the main safety project.

The advantage of using UFBs is that they can be reused in other projects and that improve readability of the main safety project by splitting up the (more complex) logic in sub-blocks.

  1. Go to Solution Manager, SafetyGCC_Safety_V01GCC_Safety_V01 ProjectUser FBs.
  2. Right click on the folder icon and select addexisting item to import a UFB from another location to the TwinSAFE project. It is also possible to make a new UFB by selecting new.
  3. UFBs can be changed by double clicking on them in the folder User FBs.

  1. To import an UFB to the main safety project, go to the tab of TwinSafeGroup1.sai and right click on an empty spot.
  2. Click on User FB HandlingAdd and choose the block you want to insert.

Naming signals and adding inputs and outputs to MOTORCORTEX

It is possible to send data to and receive data from the Safety PLC. This can be done via so-called standard variables. These signals will also be available to MOTORCORTEX.

  1. Go to the Solution Explorer, go to the folder SAFETY and right click on Alias Devices. Choose the option Add multiple standard variables.

  1. Add 2 inputs and 3 outputs.

  1. Now in the folder Alias Devices, 2 inputs and 3 outputs are added. An input will have a small yellow square in its symbol, an output a red square. The standard inputs have a grey icon, since they are not safe. Safe inputs and outputs (like the EK1914, which has two of both), will have a yellow icon.
  2. Optionally, it is possible to place the inputs and outputs in seperate folders. This is done by right clicking on Alias DevicesAddNew Folder. This has no influence, but can be more clear.

NOTE: It is important to keep track of the order of the variables, since otherwise they might be in the wrong order in MOTORCORTEX. If you delete a variable, all will shift one up. It is not possible to add a new one and rename it.

  1. Rename them in as below:

| Original Name | New Name | Order in TwinCAT | Order in MOTORCORTEX | |———————————-|—————————-|———————————————-| | ErrorAcknowledgement.sds | ErrorAcknowledgement.sds | Input byte 0, bit 0 | Output byte 0, bit 0 | | Run.sds | Run.sds | Input byte 0, bit 1 | Output byte 0, bit 1 | | Digital Input (standard)_1.sds | iNoEstop.sds | Input byte 0, bit 2 | Output byte 0, bit 2 | | Digital Input (standard)_2.sds | iWatchdogPulse.sds | Input byte 0, bit 3 | Output byte 0, bit 3 | | Digital Output (standard)_1.sds | oEStopNotActive.sds | Output byte 0, bit 0 | Input byte 0, bit 0 | | Digital Output (standard)_2.sds | oSTONotActive.sds | Output byte 0, bit 1 | Input byte 0, bit 1 | | Digital Output (standard)_3.sds | oWatchdogOk.sds | Output byte 0, bit 2 | Input byte 0, bit 2 |

  1. Next step is to define names to signals in the TwinSafeGroup1.sai Naming can be done by clicking on left of the input or right output and by starting to type.
  2. Following the name of the image below.

The names will be linked to the inputs and outputs, standard as well as physical safety inputs and outputs.

  1. Double click on TwinSafeGroup1.sai to open it in as a tab in the middle. Go to the bottom and click on the tab variable mapping. In the top click on the tab Variables. You can drag the window up to make it bigger. On the left of the table are the variables that are used in TwinSafeGroup1.sai. Some of them are already linked (GroupPort_ErrAck and GroupPort_RunStop) because of the predefined project that was chosen in section 2.4.

  2. Start linking the variables to the inputs and outputs. If an variable cannot be found, it might already be used: click on “Used and unused” to find it.In order to link multiple inputs/outputs to a variable, use the Ctrl button.

Verify project

Now the everything is in the project, it needs to be verified. This can be checked by going to the top bar of TwinCAT, select TwinSAFE and click on Verify Safety Project.

In the pictures below are some errors:

  • Order of Execution not unique: The function blocks are executed in a order defined by the user. Normally this goes from input via blocks to outputs, otherwise it can be that your output will only be updated one clock cycle later. The order of execution of the block is in the top right. In order to change the execution order, click on the function block, open the properties tab and fill-in the desired number.
  • Another error you might get is that input is not connected. In the example it happened with the variable “iErrorAcknowledge” that was not given to UFB Watchdog100ms.

When all errors are fixed, only 2 warnings remain, linked to UFB an always true signal. See section AlwaysTrue.ufb for more details.

Last step is to go to TwinSAFE and Verify Complete Safety Project.

Typical errors there are:

  • Dip-switches not matching the FSoE address
  • Double FSoE addresses
  • Target system not reachable/not found in case your EtherCAT devices are not connected

Uploading the project

————-TBD——————-

Setting up MOTORCORTEX

————-TBD——————-

Vectioneer Pre-defined User Function Blocks

————-TBD——————-

AlwaysTrue.ufb

The Safety PLC receives several non-safe signals from the Motion Controller (directly via EtherCAT, not via any physical inputs). Two of those are used to trigger STOs (watchdog and E-Stop from the motion Controller) , although because of their non-safe character do not improve the safety ratings (however due to their implementation it also does not make it worse).

In order to implement a non-safe signal into the safety software, it has to be combined with a safe signal. This could e.g. be Emergency Stop. This has as downside that all internal safety PLC signals that are used for diagnosis are also triggered in case of the Emergency Stop. In order to prevent confusion, an “AlwaysTrue” block is created to create the mandatory safe signal that can be combined with the non-safe signal.

NOTE: the non-safe signal is implement in such a way that it can never overwrite the outcome of the safe signals. Therefor there is no impact on the MTTFd on in implementing these extra signals.

NoEstop.ufb

In case the Motion Controller detects a situation that is not safety-critical (and therefor can be implemented on the non-safe Motion Controller), but does desire switching off of the drives, it can trigger an Emergency Stop. It does that with input signal “iNoESTop”. In order to combine this non-safe signal, it has to be joined by a safe signal, that is provided by the output of “AlwaysTrue.ufb”.

Watchdog100ms.ufb

The Watchdog is implemented in case of task freezing on the Motion Controller. FSoE has a built-in watchdog timer, however this one is only triggered if the EtherCAT master stops/is too slow in sending packages. For cases where the EtherCAT task will keep running, but e.g. the logic task freezes, the FSoE watchdog will not respond. For this case a separate watchdog is created.

Watchdog100ms.ufb expects a pulsed signal with a maximum time of 100ms for a 0 or 1. Beyond that time, the output of this block will go to 0. The 250ms Ton delay and ErrorAcknowledgementBlock is implemented to prevent cases where the watchdog is border stable and otherwise could lead to a quick switching of the output (no relays are connected in this application to the output, but in case it would, it would significantly reduce the lifetime). Also here the AlwaysTrue signal is used to decouple status of the watchdog timer from any safety inputs.

5.4 -

Link TwinSAFE project

5.5 -

Upload existing TwinSAFE project

Introduction

MOTORCORTEX is especially designed to allow easy and high-performance interaction with real-time control systems from any platform.

For safety it is possible to use existing solutions, like safety PLCs or Safety over EtherCAT (FSoE), developped by Beckhoff. Beckhoff safety modules are called TwinSAFE and compatible with EtherCAT.

This manual describes how to configure an existing TwinSAFE project can be downloaded to FSoE master and how the FSoE structure in used with MOTORCORTEX.

Downloading a TwinSAFE project with TwinCAT to FSoE Master

Requirements programming computer

Requirements:

  • TwinCAT 3.1 Engineering Edition on a computer (full install,including XAE shell option).
  • Ethernet port on the computer (either integrated or via external USB device)

Connecting to EtherCAT devices

There are two ways to connect to the EtherCAT devices:

  1. Physically remove the EtherCAT cable from the MOTORCORTEX controller. For the Generic Control Case this means that the enclosure has to be removed.
  2. Set MOTORCORTEX in pass-through mode: This option will make the MOTORCORTEX controller act like “dumb” hub, passing the EtherCAT-packages from TwinCAT running on your computer via the ENET port directly to EtherCAT devices. This means that the cabinet/enclosure does not have to be opened.

Directly connecting the computer to the EtherCAT devices

Open the cabinet, remove the EtherCAT connector from the MOTORCORTEX controller and put it in the network adapter of the computer that runs TwinCAT.

Set MOTORCORTEX in pass-through mode

** !!TBD To be written when function is integrated in MOTORCORTEX.!! **

Open safety project project in TwinCAT and update the EtherCAT topology

Open the project

Go File→Open→Project/Solution and open the desired TwinCAT project.

Remove EtherCAT topology

Details like the device adapter number in the EtherCAT topology can be different to your current situation. Therefore it is recommended to first remove the EtherCAT topology and rescan it.

To remove the topology go to the Solution Explorer, IO → devices, right click on Device # and select Remove.

Install Realtime Ethernet drivers

The first time you start-up TwinCAT, your ethernet device is most likely not yet configured for use with EtherCAT. TwinCAT tell that no real-time network device is found. To install the drivers, in the top bar go to TwinCAT→ Show Realtime Ethernet Compatible Devices. This will open a system window. Go to the Ethernet Device you want to use and click on Install. Make sure to choose the right device (and not e.g. your Wifi adpater). More information can be found in the Beckhoff Information System.

Scan EtherCAT topology

NOTE: before scanning the EtherCAT bus, make sure the dip-switches of the safety address are set to the right position on all your safety devices.

  1. Go to the Solution Explorer, IO → devices, right click and select Scan.

  1. Next TwinCAT will show an overview of all available devices. Select the ones with EtherCAT in the name and continue.

  1. Last TwinCAT Free Run has to be activated.

  1. After the scan is completed, you will have an overview like below. In Solution Explorer→ Devices, you will get a folder with Device # (EtherCAT) with in there your EtherCAT topology.

Configure Safety Devices


The next step is to check the correct settings of the Safety Devices.

Selecting Target System

  1. Go to the Solution Explorer → SAFETY, go into the safety project, and double click on Target System. This is the device where the safety logic runs.
  2. Click on the icon behind Physical Device.

  1. Select the matching device from the EtherCAT topology (TwinCAT will only show devices with the same description).

  1. Check the FSoE address by clicking on the icon behind Hardware Address.
  2. Store it as Safe Address (=FSoE address) by clicking on the icon.
  3. Safe the settings of the Target System (Ctrl+S).

Configure Safety IOs

  1. Go to the Solution Explorer → SAFETY, go into the safety project, all the way to Alias Devices.
  2. Double click on the Physical Safety devices (they start by default with “Term”). This will open a screen in the middle. Select the tab Linking.
  3. In case your Input/output Device also acts as Target System (safety PLC where the safety project runs and was selected as thus in section Selecting Target System, linking mode shall be automatic or local. Continue with the other devices. In case your Device is not used as Target System, continue below.
  4. Click on the icon behind Physical Device.

  1. Select the matching device form the EtherCAT topology (TwinCAT will only show devices with the same description).

  2. Check the FSoE address: Click on the icon behind Dip Switch,

  3. After this press on icon the behind FSoE Address to store the dip switch address as FSoE address.
    NOTE: every device shall have an unique FSoE address.

  4. Repeat above steps for all Physical devices in the Alias Devices folder.

Verify project

Last step is to go to TwinSAFE → Verify Complete Safety Project.

Typical errors are:

  • Dip-switches not matching the FSoE address (set the correct values)
  • Double used FSoE addresses (set the correct values)
  • Target system not reachable/not found in case your EtherCAT devices are not connected (connect TwinCAT to the EtherCAT devices again)

Note: In Vectioneers generic application, you will always get 2 warnings:
The parameter value of “Safe Inputs After Disc Error” of the function block FBEstop1 is always true in this selected target system logic.". This is correct and the motivation for it can be found in Chapter [Appendix A: Vectioneer Pre-defined User Function Blocks].

Uploading the project

  1. Go to the Solution Explorer → SAFETY, go into the safety project, and double click on Target System.
  2. Copy the value of the Serial Number field. If there is no value available, this is most times because there is/was no connection. Connect to the Target Device again by clicking on the icon behind Physical Device and select the device again.

  1. Now we will download the project to the project to the device. Go to TwinSAFE → Download Safety Project.

  1. Check once again that the FSoE address match and that you upload the correct project.

  1. You will get a login screen. Fill in the
    username: Administrator,
    the serial number you copied in step 2
    and password: TwinSAFE.
    Click Next to continue.

  1. Next you have to select the project data that will Download to the target device. Note: once a program has already been uploaded to the Target System, the view might differ from the picture below.

  2. Next TwinCAT will give you the feedback if the download of the project data was successful.

  3. Next step is to verify that the checksums (CRCs) of the project, calculated in TwinCAT match the CRCs that the new program on the target system has.If all Online CRCs match to the Calculated CRCs, you can tick the box.


By ticking the box you acknowledge that the CRCs are correct and you shall perform a Safety Acceptance Test verifying that the Safety Project is performing correctly. Not performing the safety test can lead to injuries and casualties. You will be responsible and accountable for this!


  1. Last step is to activate the safety project by filling in the username and password of step 5.

  1. In case you in switched the EtherCAT cables in order to connect to the etherCAT, Unplug the cable from your network adapter and put it back in the Motion Controller. In case you put the Motion Controller in bridge mode, deactivate the mode by restarting the system (power the system off, wait for the indicator to dim and switch power on again).
  2. Switch back to the MotorCortex environment to configure the system. It might be that you will need to restart your computer, since TwinCAT reconfigured your network adapter for EtherCAT.

Setting up MOTORCORTEX configuration

Safety Warnings


NEVER shall the NoEStop signal originating from MOTORCORTEX be used as replacement of safety critical signal. E.g. triggering Emergency Stop signals via a touchscreen instead of a physical Emergency Stop button is FORBIDDEN.



The NoEStop signal coming from the Motion Controller is an extra input to generate an EStop when Motion Controller detects an undesired situation and cutting the power is best solution (e.g. the motor is overheating). However it is not a safety signal and has no safety rating! If overheating is considered a human safety signal, it shall be read-in by a safety device and be incorporated in the safety project with safety devices.



Error Acknowlegement shall never be triggered automatically, but only after a manual, human input.


Linking FSoE devices


To be written.

Extracting information from FSoE data stream


To be written.

Sending Data to and from FSoE Master (Standard Inputs and Outputs


To be written.

Perform SAFETY test.


The user shall always perform a Safety Acceptance Test verifying that the Safety Project is performing correctly. Not performing the safety test can lead to injuries and casualties. You will be responsible and accountable for this!


Test procedure

The one making the Safety Project (specification) is also responsible for writing the Safety Acceptance Test.
On site, the person responsible (for safety) shall check if this test is applicable or needs to be extended.
To be verified.

GCC safety Acceptence Test

For the GCC Safety Logic Vectioneer wrote the Safety Acceptence Test.

  1. Go to the GUI, and Acknowledge the system. The system should be powered: the lamp should turn green and STO output pins 2 and 4 should measure 24V against GND pin 3.
  2. Press the E-Stop button: Check if STO outputs 2 and 4 measure 0V against GND pin 3.
  3. Keep the E-Stop button pressed and acknowledge. The STOs shall not turn on.
  4. Unlock the E-Stop button. The system shall not automatically reset.
  5. Reset the system via the GUI. The STO outputs pin 2 and 4 shall go high and measure 24V against GND pin 3.

To be verified.

Things not covered by this test, but shall be checked are:

  • Is the machine safe and not damaged?
  • Is there a risk of human injury by people being exposed to the machine, while these shall be inaccessible?
  • Etc.

To be verified.

Appendix A: Vectioneer Pre-defined User Function Blocks

Intro to be written.

AlwaysTrue.ufb

The Safety PLC receives several non-safe signals from the Motion Controller (directly via EtherCAT, not via any physical inputs). Two of those are used to trigger STOs (watchdog and E-Stop from the motion Controller) , although because of their non-safe character do not improve the safety ratings (however due to their implementation it also does not make it worse).

In order to implement a non-safe signal into the safety software, it has to be combined with a safe signal. This could e.g. be Emergency Stop. This has as downside that all internal safety PLC signals that are used for diagnosis are also triggered in case of the Emergency Stop. In order to prevent confusion, an “AlwaysTrue” block is created to create the mandatory safe signal that can be combined with the non-safe signal.

NOTE: the non-safe signal is implement in such a way that it can never overwrite the outcome of the safe signals. Therefor there is no impact on the MTTFd on in implementing these extra signals.

NoEstop.ufb

In case the Motion Controller detects a situation that is not safety-critical (and therefor can be implemented on the non-safe Motion Controller), but does desire switching off of the drives, it can trigger an Emergency Stop. It does that with input signal “iNoESTop”. In order to combine this non-safe signal, it has to be joined by a safe signal, that is provided by the output of “AlwaysTrue.ufb”.

Watchdog100ms.ufb

The Watchdog is implemented in case of task freezing on the Motion Controller. FSoE has a built-in watchdog timer, however this one is only triggered if the EtherCAT master stops is too slow in sending packages. For cases where the EtherCAT task will keep running, but e.g. the logic task freezes, the FSoE watchdog will not respond. For this case a separate watchdog is created.

Watchdog100ms.ufb expects a pulsed signal with a maximum time of 100ms for a 0 or 1. Beyond that time, the output of this block will go to 0. The 250ms Ton delay and ErrorAcknowledgementBlock is implemented to prevent cases where the watchdog is border stable and otherwise could lead to a quick switching of the output (no relays are connected in this application to the output, but in case it would, it would significantly reduce the lifetime). Also here the AlwaysTrue signal is used to decouple status of the watchdog timer from any safety inputs.

5.6 -

⚠️ The user is responsible for uploading the correct safety program and testing its functionality. NOT proper Testing may lead to sever injuries or even death. ⚠️

Upload TwinSAFE project with TwinSAFEloader

Introduction

It is possible to upload an TwinSAFE project to the TwinSAFE logic module without the help of TwinCAT. Beckhoff provides for this purpose TwinSAFEloader software. This can run from your own computer or from the Motion Controller.

Requirements programming computer

  • TwinSAFE project (bin-file) with the project CRC

Additional when own computer is used for uploading:

Prepare motion controller

  1. Log in via SSH on the motion controller.
  2. Prepare communication path between EtherCAT master and TwinSAFE_Loader

Switch the EtherCAT mailbox on:

ethercat_mbg &

Check TwinSAFE logic devices

  1. Navigate to the folder where TwinSAFE loader and the TwinSAFE project file are located.

Uploading can be either your local computer or from the Motion Controller. In the latter case, make sure both TwinSAFEloader.bin as your Safety Project bin-file are on the Motion Controller and navigate to that remote folder.

  1. Find all TwinSAFE logic devices:
./TwinSAFE_Loader.bin --gw 192.168.2.100 --list FSoE_Logic_devices.txt
subcommand Description
–gw address of the motion controller. Per default is this “192.168.2.100”.
–list returns information of all TwinSAFE logic devices in a text file. This file must be named, otherwise the command does not work.

If TwinSAFE_loader is ran from the Motion Controller directly, it is also possible to use “localhost” instead.

  1. See which devices are available.

Display the content of the text file:

cat FSoE_Logic_devices.txt

This will result for the GCC (Generic Control Cabinet) default configuration as the following:

EtherCAT address;FSoE address;type;project crc;name
1001;1;EL6910;0x535b;EL6910, TwinSAFE PLC

Here we see the EtherCAT address that we need to send the new TwinSAFE logic to. NOTE: sometimes there are multiple devices that can run the twinSAFE logic. Make sure you choose the correct one. For the GCC Safety application this is the EL6910 on position 1001.

Upload the new Safety Program

./TwinSAFE_Loader.bin --gw 192.168.2.100 --user Administrator --pass TwinSAFE --slave 1001 --proj ./GCC_Safety_V120.bin
subcommand Description
–slave EtherCAT address of the TwinSAFE logic module where the TwinSAFE program shall be uploaded to. In the GCC application this is 1001 per default.
–user user that uploads the TwinSAFE program. Per default this is “Administrator”.
–pass password used for uploading the TwinSAFE program. Per default this is “TwinSAFE”.
subcommand Description
–slave EtherCAT address of the TwinSAFE logic module where the TwinSAFE program shall be uploaded to. In the GCC application this is 1001 per default.
–user user that uploads the TwinSAFE program. Per default this is “Administrator”.
–pass password used for uploading the TwinSAFE program. Per default this is “TwinSAFE”.
–proj This is binary of the TwinSAFE Project that needs to be uploaded.

You will get the response like below:

2020-09-01T14:17:04+0000 Info: TwinSAFE Loader - v7
2020-09-01T14:17:04+0000 Info: 'Administrator' is downloading 'GCC_Safety_V120' to EL6910 @1
2020-09-01T14:17:06+0000 Info: Download of 'GCC_Safety_V120' (0xcca4) to EL6910 @1 completed

Activate the TwinSAFE project

The project will only be active after it is activated. This is done by sending the project CRC is send. The project CRC can be found back on the title page of the documentation.

⚠️ The user is responsible for uploading the correct safety program and testing its functionality. NOT proper Testing may lead to sever injuries or even death. ⚠️

⚠️ By activating the TwinSAFE project you accept that the responsibility of the project on the system and that the system is tested.⚠️

./TwinSAFE_Loader.bin --gw 192.168.2.100 --user Administrator --pass TwinSAFE --slave 1001 --proj ./GCC_Safety_V110.bin --crc 0xcca4
subcommand Description
–crc This is project CRC as in the documentation. This CRC address should also be returned by TwinSAFE_loader in the last step.

You will get the response like below:

2020-09-01T14:21:04+0000 Info: TwinSAFE Loader - v7
2020-09-01T14:21:05+0000 Info: Project activation successful

Switch off the EtherCAT mailbox and reboot

pkill ethercat_mbg
sudo reboot

Check the functionality of the Safety Project

TBW:

For Vectioneers GCC application the following needs to be tested: For all other applications individual test protocols need to be made and executed.

Triggers:

  • press emergency stop
  • change watchdog timer
  • trigger no-estop Responses:
  • STO channel 1: 1>0
  • STO channel 2: 1>0

6 - Software Maintainance

6.1 - Determining software versions and Hardware Key

Motorcortex consists of a number of software components that each have a version associated with them. Sometimes it is necessary to determine the version of the components in a running system to check if updates are available or if dependencies are met.

The hardware key is required when validating licenses. Each host system generates its own unique hardware id. For some motorcortex components a license is required for each hardware id that the system should run on.

To get the Operating System version information and hardware id type this command in a terminal when logged-in to the control system:

cat /etc/issue

Information similar to the following will be shown.

Motorcortex 2021.01[g17f4d5d+1] \n \l

The active license does NOT match the active application

Active license information:
  File: /etc/motorcortex/config/license.pem
  Hardware key: 2651256591846471365
  Modules: mcx-core2, mcx-io2, mcx-math2, mcx-control2, mcx-generic-app2

Active application information:
  File: /usr/local/bin/mcx-generic-app
  Hardware key: 6591555251580943153 mcx-core2 mcx-io2 mcx-math2 mcx-control2 mcx-generic-app2

  Hardware key as QR Code:
  ##################################################################################
  ##################################################################################
  ##################################################################################
  ##################################################################################
  ########              ##  ########  ######          ########              ########
  ########  ##########  ##  ####      ##    ############    ##  ##########  ########
  ########  ##      ##  ##    ####          ##  ##  ##      ##  ##      ##  ########
  ########  ##      ##  ##      ##  ##  ##########      ##  ##  ##      ##  ########
  ########  ##      ##  ####    ##  ##    ##  ####  ####    ##  ##      ##  ########
  ########  ##########  ##      ####        ######  ####  ####  ##########  ########
  ########              ##  ##  ##  ##  ##  ##  ##  ##  ##  ##              ########
  ############################    ##      ####  ########    ########################
  ########    ####      ######  ##  ##  ##            ####  ####  ##        ########
  ########  ####    ################    ####  ########          ##        ##########
  ########    ##    ##  ##      ######  ####  ##      ####      ##  ##  ############
  ########  ########  ##      ####        ####  ##  ####      ####        ##########
  ############  ######  ########  ##        ######  ########  ##    ##  ############
  ############        ##    ##  ##  ##  ########      ##    ######          ########
  ########      ##  ##    ##        ##  ####  ##      ######        ################
  ########  ##      ######  ##    ##  ##  ####  ##  ####  ##  ##    ##  ##  ########
  ########  ##  ######  ##########  ##  ##  ####  ##    ##  ######  ################
  ########        ##  ####      ####  ##  ##    ##  ####  ##              ##########
  ########      ##      ##############  ##    ##        ##  ##  ##    ##  ##########
  ##############  ##  ##  ##    ##          ##  ######        ########  ##  ########
  ##########  ####        ##  ##  ##    ####          ##      ##########    ########
  ########  ####  ##  ########  ##            ##    ##  ##  ##  ##    ##############
  ############            ####      ##  ####      ##  ####    ####    ##############
  ############      ######  ##    ##      ####  ########    ######  ##    ##########
  ########      ####    ##    ####    ##  ##    ##    ####                ##########
  ########################  ##  ####    ########  ####      ######  ##    ##########
  ########              ####    ############  ##  ##  ####  ##  ##    ##    ########
  ########  ##########  ##  ######        ##############    ######  ##  ############
  ########  ##      ##  ##  ##        ####  ####    ####            ######  ########
  ########  ##      ##  ####  ####        ##    ##  ####    ####    ####    ########
  ########  ##      ##  ######    ##########  ##      ##  ######  ##  ##############
  ########  ##########  ##  ##    ##  ##    ############  ####  ##        ##########
  ########              ##  ##        ########    ####  ####    ######      ########
  ##################################################################################
  ##################################################################################
  ##################################################################################
  ##################################################################################

The first line shows the OS version, in this case Motorcortex 2021.01[g17f4d5d+1] \n \l.

Under Active license information you can find the hardware id and where the license file is located.

6.2 - Ethernet/EtherCAT Bridge-mode

Sometimes it is needed to configure a EtherCAT device via the manufacturers software, while keeping the EtherCAT topology intact (e.g. configuring a drive with integrated safety with the FSoE master located in the GCC). Normally this would mean unplugging the EtherCAT cable from the EtherCAT master and plugging it into a laptop, however in the case of a GCC this would mean opening the cabinet. Since this is laborious action involving opening the GCC, an alternative is made available by switching the MotorCortex Controller into bridge-mode, passing all data from front port “EN” directly to the EtherCAT network.

Switching on Bridge mode

  1. Log into the system from the console (or through ssh):

  1. Login to the system login using the default credentials or the credentials of the system:
  • login: admin
  • password: vectioneer
  1. Now the command line will change to
sudo mcx-bridge on
  1. After this you will be able to scan the EtherCAT network with your manufacturers software (directly via your PC or with an other EtherCAT master device) via the ENET port on the GCC.

⚠ It might be needed to change the network adapter IP settings if you use your PC with the manufacturers software

Switching off Bridge mode

There are two methods to switch off bridge mode and return the control to the MotorCortex Controller:

  1. Restarting the Motion Controller: Push the power button of the GCC to switch off the Motion Controller. Wait for all lights to switch off, before switching it on again.

  2. Directly in the controller (requires keyboard and screen) The controller is not available via SSH, since the system is now in bridge mode. However it is possible to access the console of the controller directly via a keyboard and screen.

sudo mcx-bridge off
  • password: vectioneer

TBD:

⚠ It might be needed to restore the network adapter IP settings to use your PC with MotorCortex again

MCX-bridge options

For more options type

sudo mcx-bridge --help

The current version of mcx-bridge has the following options:

  usage: sudo mcx-bridge on [-s SOURCE] [-t TARGET] [-b BRIDGE] [-i IP/MSK]
    SOURCE: Source device, e.g. eth0 (eth0 = default)
    TARGET: Target device, e.g. eth1 (eth1 = default)
    BRIDGE: Bridge device, e.g. br0  (br0 = default)
    IP/MSK: IP and Mask, e.g. 192.168.2.100/24 (192.168.2.100/24 = default)

  usage: sudo mcx-bridge off [-b BRIDGE] [-s SOURCE] [-i IP/MSK]
    BRIDGE: Bridge device, e.g. br0  (br0 = default)
    SOURCE: Source device, e.g. eth0 (eth0 = default)
    IP/MSK: IP and Mask, e.g. 192.168.2.100/24 (192.168.2.100/24 = default)

6.3 - Starting/Stopping/Restarting

Normally a Motorcortex application is configured to automatically boot when the machine is powered on. However it may be required for the software to be stopped or restarted in a different mode. This chapter shows how Motorcortex applications can be started, stopped and restarted.

  1. Log into the system from the console (or through ssh):

  1. Login to the system login using the default credentials or the credentials of the system:
  • login: admin
  • password: vectioneer
  1. Now the command line will change to

     mcx-intel:$~
    

You can use standard Linux commands to go trough files and perform Software Maintainance.

⚠ If a Virtual Machine is used it is convenient to put Motorcortex into Simulation Mode to prevent errors because there is no hardware connected.

Running of Motorcortex applications is handled through a system daemon. The daemon can be managed by calling

sudo /etc/init.d/motorcortex start|stop|restart|startsim|restartsim

For instance to switch an already running system to simulation mode execute:

sudo /etc/init.d/motorcortex restartsim

To return back to normal operation run:

sudo /etc/init.d/motorcortex restart

6.4 - Backup and Restore

The MOTORCORTEX-Imager USB Stick is a bootable USB drive that can be used to create backups and restore images of MOTORCORTEX Systems.

Downloading and flashing the MOTORCORTEX-Imager image to a USB stick

  1. You will need an USB Stick of at least 6Gb and at least 7Gb of free space on your PC.
  2. Download the latest MOTORCORTEX-Imager release: MOTORCORTEX-Imager
  3. Extract the image, so you should have a 6Gb .img file.
  4. On Windows systems, you will need an external tool to write disk images to an USB device. There are several options, one of them is http://unetbootin.github.io. On most Linux distribution s you can just doubleclick on the img file and this will open the Disk Image Writer tool.
  5. Write the image to your USB Drive.
  6. When done, you can mount the stick on your system and copy an existing image file onto the ImageData partition of the stick.

Booting from the MOTORCORTEX-Imager USB stick

The Motorcortex-Imager can be used with a screen and keyboard attached to the controller or over an SSH connection, so no screen and keyboard is necessarily.

Using a Screen and Keyboard

  1. Make sure the controller is switched off.
  2. Insert the Motorcortex-Imager USB Stick into an available USB port of the controller.
  3. Attach a keyboard to one of the USB-ports and a display to the HDMI-port.
  4. Switch the controller on.
  5. If all is correct you will see the something like the picture below:

If above screen does not appear, check the screen and usb connection. If that does not help, check the bios settings of the Motorcortex Controller, it might be that USB stick is not first in the boot order.

Using SSH

  1. Make sure the controller is switched off.
  2. Insert the Motorcortex-Imager USB Stick into an available USB port of the controller.
  3. Switch the controller on.
  4. Give the controller some time to boot. Log in after 20 seconds using a SSH client like Putty, the Linux Terminal or Windows Command Line. Type

ssh tc@192.168.2.100

Log in with password vectioneer.

  1. If all is correct you will see the something like the picture below:

    If above screen does not appear, check network settings and network connection (tip: first try

ping 192.168.2.100

If that does not help, check the bios settings of the Motorcortex Controller, it might be that USB stick is not first in the boot order.

Making a back-up

  1. Type sudo mcx-backup to start the back-up procedure.

  2. Choose which disk you want to back-up. Hard disks and solid state disks usually start with SD.. SD cards and USB sticks with eMMC.

  3. Next choose where you want to store your image:

    1. This is the default option, it stores it on the USB stick (/mnt/usb/), followed by the date and time on the controller + mcx-image.img.xz.
    2. It is also possible to choose your own name and location. Type /mnt/usb/ to store it on the USB stick. Follow this by the name you want to give. End with .img or .img.xz. The .xz means that the file is zipped. It is recommended to use zip, since otherwise the image file will be the size of the disk (in case of the Motorcortex Fitlet2 this is 32GB). If you follow this you will get something like:

    /mnt/usb/2020-04-08_another-image_name.img.xz

  4. Creating a backup image will take some time. You can watch the progress in the console.

  5. When the backup is finished the number of bytes written will be shown. Please check if there are any errors being reported that may indicate that creating the image has failed.

  6. Now you can reboot or poweroff. In case you are done with the back-up and want to go back to the Motorcortex Operating System, type:

    sudo poweroff

  7. Wait for for the system to power off. During this time any cached data is still written to the disk, so no not switch off early.

  8. The system should reboot or power off automatically. At that time remove the USB stick.

  9. Switch on the power again to start the system from the internal storage again.

  10. It is good practice to restore an image to another system or boot the image in a virtual box, to see if the backup went well.

Restoring an image (Cold Start)

This method can be used to install a fresh MOTORCORTEX-OS image or a backup image to your controller.

  1. If the MCX boot stick does not already contain your source image, copy it into the ImageData partition of the USB stick. Supported image file formats are raw image (.img), compressed images (.img.xz) or WIC images (.wic).
  2. Boot from the USB stick and log into the system (see above)
  3. Type sudo mcx-restore -f to start the restore procedure. The -f option will expand the image to use the full disk size, this is useful if you are restoring a truncated image and you wish to use all available disk space on the target system.
  4. Choose which image you would like to restore.
  5. Choose the drive where you want to restore your image to.
  6. Be patient, restoring the image will take some time. When the process is done, check for any errors in the console

make sure that the image will fit on your disk. Otherwise your system may not function properly!

  1. You will get the message Done when the process is finished.
  2. Now you can reboot or poweroff. In case you are done with the back-up and want to go back to the Motorcortex Operating System, type:

sudo poweroff

  1. Wait for 20 seconds for the system to power off.
  2. Switch off the power of the controller.
  3. Remove the USB stick.
  4. Switch on the power again.
  5. Done.

6.5 - Bios Settings Fitlet2

This chapter tells the bios settings of the Fitlet2 Motorcortex Controller.

These settings make it easier to back-up the system and use other storage devices to boot from.

Setting Fitlet2 Bios settings

  1. Make sure the controller is switched off.
  2. Attach a keyboard to one of the USB-ports.
  3. Start tapping the delete key.
  4. Switch the controller on.
  5. Stop tapping the delete key when the bios menu appears.
  6. In the Main screen Load Optimized Defaults by pressing the F3 key. Select Yes.

  1. Use the arow keys to navigate trough the BIOS. Go to OS Selection hit enter and select Linux.

  1. Go to the Boot screen using the arow keys and go to Boot Options hit enter and set the correct boot options as below:

    1. Go to Boot Option #1 and select USB Key.
    2. Go to Boot Option #2 and select USB HDD.
    3. Go to Boot Option #3 and select USB CD/DVD.
    4. Go to Boot Option #4 and select SD.
    5. Go to Boot Option #5 and select HDD:....

  1. go to the Save & Exit screen.
  2. Press F4 or go to Save Changes and Exit. Select Yes.

6.6 - Date and time

Setting date and time is important for debugging problems and to correlate data from different sources.

First, set the timezone by replacing the link /etc/localtime with a link that points to the desired timezone:

sudo rm -f /etc/localtime 
sudo ln -sf /usr/share/zoneinfo/Universal /etc/localtime

Replace Universal with your desired region or timezone.

The date and time can be set by executing the following Linux command (as root):

sudo date -s "Mon Mar 15 18:49:40UTC 2019"
sudo hwclock -w

The last line is important because only then the time is set correctly in the hardware clock and is not lost on reboot.

6.7 - Default File Locations

This page describes where on the Motion Controller Motorcortex related (configuration) files can be found. These are default locations, actual location may vary depending on your setup.

Application Specific Configuration files

Application Specific Configuration files are located in:

/etc/motorcortex/config/

This folder may be a link to a certain application configuration, e.g.:

/etc/motorcortex/config --> /etc/motorcortex/config.myproject

Inside the /etc/motorcortex/config/ folder there are a number of files and folders that hold configuration options:

  • motorcortex.conf; specifies which executable is going to be used and sets some commend line options. This file is used by the init.d script that automatically starts and stops motorcortex applications.
  • config.json; specifies runtime options for the exectuable. This file sets task priorities and can set various options that are used when the application starts.
  • control/; folder that holds control system parameters
  • io/; folder that holds io configuration

License certificates

License certificates for MOTORCORTEX products have to be installed in:

/etc/motorcortex/licenses/

Communication certificates

Communication certificates are installed in:

/etc/motorcortex/config/certificates/

Log files

Log files are created in:

/var/www/motorcortex/log/

or

/var/log/motorcortex/

depending on the system configuration.

6.8 - Network settings

This chapter will explain how to change the IP address of your controller.

Network adapter configuration

First log in to the controller. Either by connecting a keyboard and screen to the controller or logging in through ssh:

ssh admin@192.168.2.100

Then if you want to reconfigure the controller’s network settings, like changing its IP address do the following.

sudo nano /etc/network/interfaces

Look for the following section in this file:

# Wired or wireless interfaces
auto eth0
iface eth0 inet static
    address 192.168.2.100
    netmask 255.255.255.0
    gateway 192.168.2.100

Change the address and the gateway to the desired values. Save the file and exit.

If you want to modify the system’s hostname you can change it by modyfying /etc/hostname and /etc/hosts.

Restart the network to apply the new settings.

sudo /etc/init.d/networking restart

If you changed IP address while connected to the terminal over the network, your connection will probably be lost after restarting the network.

It is possible that due to the network change the communication certificate has become invalid. For security reasons, the certificate is only valid for the ip address and hostname of the controller. MCX-Linux OS provides a certificate renewal service that checks the certificate and renews it if either it has expired or if the host name or ip address has changed. To renew the certificate, either reboot the controller or restart the cert-gen service:

sudo /etc/init.d/cert-gen restart

Optionally, you can modify the certificate settings by modifying the cert-gen config file:

sudo nano /usr/share/cert-gen/config.json

After your modification restart the service to generate the new certificate.

EtherCAT adapter config

The EtherCAT master needs to know which card it will use for EtherCAT. The EtherCAT network card should not be configured for normal networking.

To change the EtherCAT network settings do:

sudo nano /etc/ethercat.conf

The important settings in this file are which network adapter to use and which driver to use.

You can select your network adapter by modifying the following line:

MASTER0_DEVICE="eth1"

To select the driver type, change the line:

DEVICE_MODULES="generic"

Refer to the EtherLAB documentation for a description of all available configuration options.

6.9 - Advanced use of disk images

Filling empty space with zeros

To improve compression of image files, the remaining free space of a partision can be filled with zeros before the image is created. Run this on the system to be backed up:

dd if=/dev/zero of=file; rm file

This command uses the low-level dd copy command to write zeros to a file, and when the disk is full and the command exits, removes the file.

Check if the space is actually freed again (file is actually deleted).

df -h

Create an Image from removable media

If the Motorcortex system is installed on a removable drive an image can also be made by attaching the drive to your PC and creating an image directly. Many Linux distributions already have convenient graphical tools to create an image if a disk.

In Ubuntu you can use the Disks tool to create an image file.

Then from the menu select create Disk Image:

Mounting an image

If you need to inspect or modify a partition of an image after the image has been created you can mount it on a Linux System.

First check the partition table of the image file:

fdisk -l image.img

In this case we would like to mount the second partition, which starts at block 1026048. We first need a mount point; and empty folder that will then be the location where the image will be mounted. In this case we use /mnt/image. If that does not exist, create a folder somewhere. Then mount the image:

sudo mount -o loop,offset=$((512*1026048)) image.img /mnt/image

When you are finished inspecting the contents of the image, unmount it.

sudo umount /mnt/image

Compressing an image

This command compresses the image using all available cpus:

xz -v \--threads=0 image.img

The result will be an image.img.xz file, which in Ubuntu can be restored with the Disks tool. if you want to keep the original file:

xz -v -k \--threads=0 image.img

An typical 8 GB image file should compress to about 400 MB if the empty space was first zeroed out.

Uncompressing an image file

Some operations on image files, such as mounting an image to make modifications to it or converting the image to a VirtalBox image require the xz compressed image file to be uncompressed. In Linux this is accomplished by executing the shell command:

unxz -k image.img.xz

the -k option keeps the original compressed file; without this option the compressed file is removed after uncompression.

Restoring an image to a removable disk

You can restore an image to a removable disk (for instance a CFAST card that is attached to your laptop with a card-reader) in Ubuntu by right-clicking the image and choosing “Open With Disk Image Writer” from the context menu:

This also works with xz compressed images directly.

Truncating (resizing) an image

Orignal Article: https://softwarebakery.com/shrinking-images-on-linux

When creating images from existing ISOs you often need to allocate a number of MB for the image to at least fit the files that are in the ISO. Predicting the exact size of the image is hard, even for a program. In this case you will create an image that is larger than actually needed: the image is much larger than the files on the image are combined.

This post will show how to shrink an existing image to a more optimal size. We will do this on Linux, since all required tools are available there: GParted, fdisk, gdisk (for GPT), and truncate.

Requirements

  • A Linux PC
  • Some knowledge how the terminal works will helps
  • The unoptimal image (myimage.img in this example)

Creating loopback device

GParted is a great application that can handle partition tables and filesystems quite well. In this tutorial we will use GParted to shrink the filesystem (and its accompaning partition in the partition table).

GParted operates on devices, not simple files like images. This is why we first need to create a device for the image. We do this using the loopback-functionality of Linux.

First we will enable loopback if it wasn’t already enabled:

$ sudo modprobe loop

Now we can request a new (free) loopback device:

$ sudo losetup -f

This will return the path to a free loopback device. In this example this is /dev/loop0.

Next we create a device of the image:

$ sudo losetup /dev/loop0 myimage.img

Now we have a device /dev/loop0 that represents myimage.img. We want to access the partitions that are on the image, so we need to ask the kernel to load those too:

$ sudo partprobe /dev/loop0

This should give us the device /dev/loop0p1, which represents the first partition in myimage.img. We do not need this device directly, but GParted requires it.

Resize partition using GParted

Next we can load the device using GParted:

$ sudo gparted /dev/loop0

This should show a window similar to the following:

Now notice a few things:

  • In this example, there is only one partition. There may also be a boot partion preceding the main partition.
  • The partition allocates the entire disk/device/image.
  • The partition is filled only partly.

We want to resize this partition so that is fits it content, but not more than that.

Select the partition and click Resize/Move. A window similar to the following will popup:

gparted-02

Drag the right bar to the left as much as possible.

Note that sometimes GParted will need a few MB extra to place some filesystem-related data. You can press the up-arrow at the New size-box a few times to do so. For example, I pressed it 10 times (=10MiB) for FAT32 to work. For NTFS you might not need to at all.

Finally press Resize/Move. You will return to the GParted window. This time it will look similar to the following:

gparted-03

Notice that there is a part of the disk unallocated. This part of the disk will not be used by the partition, so we can shave this part off of the image later. GParted is a tool for disks, so it doesn’t shrink images, only partitions, we have to do the shrinking of the image ourselves.

Press Apply in GParted. It will now move files and finally shrink the partition, so it can take a minute or two, most of the time it finishes quickly. Afterwards close GParted.

Now we don’t need the loopback-device anymore, so unload it:

$ sudo losetup -d /dev/loop0

Shaving the image

Now that we have all the important data at the beginning of the image it is time to shave of that unallocated part. We will first need to know where our partition ends and where the unallocated part begins. We do this using fdisk:

$ fdisk -l myimage.img

Here we will see an output similar to the following:

Disk myimage.img: 6144 MB, 6144000000 bytes, 12000000 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000ea37d

      Device Boot      Start         End      Blocks   Id  System
myimage.img1            2048     9181183     4589568    b  W95 FAT32

Note two things in the output:

  • The last partition (in this example there is only one partition) ends on block 9181183 (shown under End)
  • The block-size is 512 bytes (shown as sectors of 1 * 512)

We will use these numbers in the rest of the example. The block-size (512) is often the same, but the ending block (9181183) will differ for you. The numbers mean that the parition ends on byte 9181183512 of the file. After that byte comes the unallocated-part. Only the first 9181183512 bytes will be useful for our image.

Next we shrink the image-file to a size that can just contain the partition. For this we will use the truncate command (thanks uggla!). With the truncate command need to supply the size of the file in bytes. The last block was 9181183 and block-numbers start at 0. That means we need (9181183+1)*512 bytes. This is important, else the partition will not fit the image. So now we use truncate with the calculations:

Additionally (for a GPT) we will leave some free space (say 1Mb = 1048576 (= 1024**2) bytes) at the end of the image for the GPT backup header which we need to fix after truncation.

$ truncate --size=$(((9181183+1)*512+1024**2)) myimage.img

To fix the GPT backup header we use gdisk

(echo r; echo d; echo w; echo y) | gdisk ./myimage.img

Meaning of letters in gdisk:

r	recovery and transformation options (experts only)
d	use main GPT header (rebuilding backup)
w	write table to disk and exit
y	yes to confirm

Converting an image to VirtualBox

If you have a compressed image you first need to uncompress it:

unxz -k -v 2019-03-18-image.img.xz

Then convert it to a VDI image:

VBoxManage convertfromraw 2019-03-18-Vectioneer-v1.0.5-test.img
2019-03-18-Vectioneer-v1.0.5-test.vdi

For using the Virtual Machine see the Virtual Machine user guide.

6.10 - Installing a License Key

Motorcortex Libraries require a license key to run in a production environment. You can still run your Motorcortex application without a license key, but the program will exit after 30 minutes.

You can check if you have a valid license if you look at your Motorcortex application log:

...
2020-06-08 07:18:21.301 [INFO] Configuration:
Motorcortex-core version: 1.6.3-133-g2accb25_release
Motorcortex-control version: 1.0.8-12-g391134e_release
Motorcortex-math version: 1.0.1-5-g5258e76_release
License is valid
...

In the near future you can request a new license from the motorcortex.io portal. Until then the process involves some manual steps:

  1. Generate a hardware key: {path/to/application} -k This will return a License Key: License key: 12345678910
  2. email this key value to license@vectioneer.com
  3. if you have purchase a license for the required components you will receive a license.pem file.
  4. Copy the license.pem file to the controller into the folder /etc/motorcortex/license/
  5. Restart the application and check the log file again.

6.11 - Simulation Mode

Sometimes it is desirable to put Motorcortex into simulation mode. this makes it possible to use controlls and tools without the need to connect any physical hardware. this can be done directly on directly on the machine or done using by using SSH from a PC.

Setting Motorcortex into simulation mode

In the comandline of the Motorcortex controller (trough ssh connection or connected directly on the controller).

  1. Go to the /etc/motorcortex/config folder

     cd /etc/motorcortex/config/
    
  2. Open the motorcortex.conf file

     nano motorcortex.conf
    
  3. In the file change

     OPTIONS="-c=/etc/motorcortex/config -l=var/www/motorcortex/log"
    

    to

     OPTIONS="-c=/etc/motorcortex/config -l=var/www/motorcortex/log -s"
    
  4. Press Ctrl+s to save the file and exit editing the file with Ctrl+x

  5. Restart The system

     sudo reboot
    

(it might be needed to use the password to execute this command)

Motorcortex is now in simulation mode.

Exit Motorcortex simulation mode

In the comandline of the Motorcortex controller (trough ssh connection or connected directly on the controller).

  1. Go to the /etc/motorcortex/config folder

     cd /etc/motorcortex/config/
    
  2. Open the motorcortex.conf file

     nano motorcortex.conf
    
  3. In the file change

     OPTIONS="-c=/etc/motorcortex/config -l=var/www/motorcortex/log -s"
    

    to

     OPTIONS="-c=/etc/motorcortex/config -l=var/www/motorcortex/log"
    
  4. Press Ctrl+s to save the file and exit editing the file with Ctrl+x

  5. Restart The system

     sudo reboot
    

(it might be needed to use the password to execute this command)

Motorcortex is now out of simulation mode.

6.12 - Linking Ethercat Signals

Linking Ethercat hardware signals to Motorcortex.

After connecting and configuring your slave devices it is time to configure and link the slaves to Motorcortex. Configuring EtherCAT slaves requires a number of steps:

  1. Scan the EtherCAT bus and generate a topology file. the topology file is used by Motorcortex to create the correct format of EtherCAT messages, such that all slave devices and their data objects can be addressed.
  2. Configure each input or output for each device and link it to the Motorcortex application.
  3. Create special configurations for some more complex devices, such a servo-controllers or configurable i/o cards (This step is not always required).

Motorcortex and EtherCAT basics

Before linking and configuring the Ethercat slaves it is necessary to know some basics of how Ethercat works with motorcortex. In Motorcortex there are two files that have to be configured when adding new Ethercat devices:

  • topology.xml
  • master.xml

Creating the topology.xml

The topology.xml contains information about which devices are in a network and how they are connected. Each slave device will receive an ID that is determined by its place in the topology. With this ID the application can address the device and send information to an receive information from the device.

  1. Connect all Ethercat devices that you want to link and configure.

  2. Login to your controller using ssh (having trouble login in check out Remote access to the Motorcortex Computer).

     ssh admin@192.168.2.100
    

Note: the standard password on a motorcortex controller is vectioneer.

  1. Go to the location of the topology.xml file

     cd /etc/motorcortex/config/io
    
  2. Check if your Ethercat devices are connected using the following command.

     ethercat slaves
    

This command should output the connected EtherCAT slaves, for instance:

    0  0:0  OP     +  EK1914, 2 K. Safety Eingang/Ausgang 24V,  TwinSAFE
    1  0:1  OP     +  EL6910, TwinSAFE PLC
    2  0:2  PREOP  +  EK1110 EtherCAT-Verl�ngerung
    3  0:3  OP     +  EP2316-0003 8 K. Dig. Ein, 10�s, 8 K. Dig. Aus 24V, 0,5A, Diagn
  1. Next the topology.xml has to be updated. but before doing this it is wise to create a backup topology file in case things go wrong. Run the following command to create a copy of the topology file with a different name.

     cp topology.xml topology_backup.xml
    
  2. Now the topology.xml can be updated using the following command.

Careless changing of topology.xml can result that the whole application will not work anymore. Therefore always first make a backup before changes are made.

    sudo ethercat xml > topology.xml

The topology file is now updated to the new configuration of all connected Ethercat devices.

Creating the master.xml basics

The master.xml is used by Motorcortex to generate the EtherCAT folder in the Parameter Tree (more on the parameter tree will follow later in this chapter). Creating the master.xml is a complicated procedure which needs knowlegde about ethercat and rules creating this master.xml. Motorcoterx Link makes this procces a lot easyer and quicker linking and configuring your Ethercat devices. For this example Motorcoterx Link won’t be used. Therefore this chapter will provide the basic knowlege needed to create the master.xml file.

Motorcortex Parameter Tree

In the master.xml the user can define which parameter types are shown in the Parameter tree. The Parameter Tree contains a snapshot of all the inputs, outputs and internal data of the control objects at the current time.

Motorcortex has a tree structure in which the data objects are published. Each task or objects inside a task can create their own subtree (folder). Objects can be nested. In a general control application there are usually a “Logic”, “Control” and also “EtherCAT” folders that represent the data of different tasks. In the EtherCAT folder you will find the configured EtherCAT slave devices.

The names of the folders are configurable and the application developer can change these, but it is good practice to stick to some convention.

Inside the folders the data of the associated object is contained. Motorcortex currently supports the following datatypes: boolean, integer, double or binary (e.g. a c-struct). Also arrays of the same datatype are supported. Array elements start at index 0 (zero).

To view the tree structure of your Motorcortex application you can use Motorcoterx Desk.

Parameter Types in Motorcortex:

This subsection shortly describes how the different parameter types can be used in combination with EtherCAT.

The Motorcortex structure has the following parameter types:

  • Input: In this parameter type a value can be written. A typical use is an sensor. In the EtherCAT configuration file the sensor value will be linked to an input. However it is possible to also write this value an input into EtherCAT output. An input is typically linked to a PDO. In Motorcortex Desk an input is depicted as:

  • Output: this parameter type is read-only. A typical use is a set point value. The value is calculated within the Motorcortex and shall not be overwritten. Therefore this value can only be linked to an EtherCAT output, but never to an EtherCAT input. An output is typically linked to a PDO. In Motorcortex Desk an output is depicted as:

  • Parameter: This is parameter type that is used to configure the system. Typical uses are motor parameters and system constants.Parameters are retrieved from the parameter list during start-up. If the user changes a value and wants to use in the future, he has to save the list before rebooting/switching off the controller. A parameter can be read and written. However due to its character, it will be used mostly in combination with SDOs. In Motorcortex Desk an parameter is depicted as:

  • Persistent: these are values that contain process data that is continuously updated and will be retained through application restarts. Typical applications are running ours or amount of produced products. In Motorcortex Desk an persistent is depicted as:

Creating the master.xml

The standard master.xml on a Generic control cabinet will look like this.

TBD

The master.xml has to start with

    <?xml version="1.0"?>
    <Master Type="EtherCAT" Device="0" Name="Ethercat">

and end with

    </Master>

In between these lines you will have to configure the folowing elements:

  • Domains
  • Devices
  • SDO/PDO/MAILBOX

EtherCAT Domains

It is possible to divide EtherCAT IOs in separate domains.

A Domain is an group of EtherCAT slaves (physical cluster of EtherCAT modules). An advantage different domains, is that every domain is separate and can (if configured properly) be disconnected and reconnected (hot-plug), while other devices in other domains that remain connected are still operational. Beside hot-plug capability domains also keep your structure more clear.

to open a domain start with:

    <Domain File="topology.xml" Name="Domain Name">

and end with:

    </Domain>

EtherCAT Devices

Devices can be added inside the domains

To add a device start with:

    <Device Id="#" Name="Device name" MapAll="0">

The Id="#" is the position of the ethercat device in the bus and can be found running the following command (The slave Id’ number is in front of every device.).

    ethercat slaves

The Name="Device name" can be a custom name you give to the device.

The MapAll="0" is a function to automatically configure all mandatory SDO and PDO in the device. It can be turned on by setting the value to "1". It is not guaranteed that this function will provide a usable outcome in the Parameter Tree and is vendor dependant.

end a device with:

    </Device>

EtherCAT PDO/SDO/Mailbox

The information sent and received over the EtherCAT network consists of data packages of the following types: PDOs and SDOs.

PDO (Process Data Object).
This is cyclic data that is send or received during every EtherCAT broadcast. Examples are: status of switches and lights, actuator setpoints and actual values.

SDO (Service Data Object).
This is in data that is normally only send during start-up or during an event. Examples are: motor parameters, sensor configuration and (drive) error information.

Mailbox.
The configuration of the SDOs on an EtherCAT module can be send via a mailbox file. There are two file types: CANopen over EtherCAT (CoE) and Sercos over EtherCAT (SoE, sometimes also called Servo over EtherCAT). The structure of the file is very similar for both types. The EtherCAT module manufacturer decides which type is used.

Configurating SDO/PDO is dificult and vendor documentation in form of a object dictionary or esi.xml is needed to determine what name connects to what PDO/SDO. Some PDO/SDO are mandatory, these must be configured.

To open a pdo start with:

    <Pdo Index="####" Entry="####:##" Group="Group Name" Name="PDO Name" DataType="Datatype">

The Index+"####" of a PDO can be found in vendor documentation or esi.xml.

The Entry="####:##" of a PDO can be found in vendor documentation or esi.xml.

The Group="Group Name" makes it possible to create a group within the device with a custom name.

The Name="PDO Name" makes it possible to create a custom name for your PDO.

The DataType="Datatype"of a PDO can be found in vendor documentation or esi.xml.

end a pdo with:

     </Pdo>

To open a sdo start with:

    <Sdo Index="####" Entry="####:##" Group="Group Name" Name="SDO Name" DataType="Datatype">

The Index+"####" of a SDO can be found in vendor documentation or esi.xml.

The Entry="####:##" of a SDO can be found in vendor documentation or esi.xml.

The Group="Group Name" makes it possible to create a group within the device with a custom name.

The Name="SDO Name" makes it possible to create a custom name for your SDO.

The DataType="Datatype"of a SDO can be found in vendor documentation or esi.xml.

end a SDO with:

     </Sdo>

Master.xml file example

Below is a example of a master.xml file of the generic control cabinet.

Parameter Tree

to check the result:

Save the file

/etc/Motorcortex/config/io/master.xml, 

restart Motorcortex

sudo/etc/init.d/Motorcortex restart 

log in on Motorcortex-Desk (http://192.168.2.100:8000) and check the result.

6.13 - Back-up and Restore Slave Configurations

Synapticon Somanet Drives

To upload the configuration from connected Somanet slaves first log in to the master controller through ssh.

At the command line, first list the connected slave devices:

ethercat slaves

Then use the correct slave id to upload the configuration file from the slave:

ethercat -p [ID] foe_read config.csv > config-backup-[ID].csv

where [ID] is the slave id. The ethercat command outputs the contents of the file on stdout so this is redirected to a file, in this case config-backup-[ID].csv.

To restore a backup type:

ethercat -p [ID] foe_write -o config.csv config-backup-[ID].csv

Once the file is copied to the drive the drive needs to be told to reload its configuration from the file:

ethercat download -p [ID] -t uint32 0x1011 0x1 0x64616f6c

The value 0x64616f6c hex is actually “load” in ASCII (note that the byte order of the drive is reversed so you are actually sending “daol”.

Ingenia Drives

TBD

Beckhoff Drives

TBD

7 - Motorcortex Hardware

Motorcortex Hardware

Motorcortex has to run on a separate operating system. Vectioneer has multiple options availavle to get started using Motorcortex quickly. More information on this can be found at www.vectioneer.com/products/. In docs.motorcortex the hardware manuals for these products are described.

If you want to try out Motorcortex from your own machine it is possible to do this using a Virtual Machine. The Virtual machine manual provides information on how to get your virtual machine going.

7.1 - Generic Control Case

Introduction

This document is the User Manual for the Generic Control Cabinet.

The Vectioneer Generic Control Case (GCC) is a complete Industrial Motion Control and Safety System in a small form-factor. It has everything you need to control any EtherCAT-based Machine or Robot safely. Out-of-the-box it is set-up with the MOTORCORTEX-Generic-App pre-installed. This allows you to control multiple EtherCAT servo axis and numerous EtherCAT IO straight from a connected web-browser. No software installation required.

System Overview

The Generic Control Case allows easy control of EtherCAT slaves. It also provides (limited) onboard power to supply externally connected EtherCAT devices. Two EtherCAT branches can be connected to the two EtherCAT sockets on the front panel.

An integrated FSoE (FailSafe over EtherCAT) master provides a complete safety system, that can be extended with extra FSoE slaves if needed. As a standard one two-channel Emergency Stop input and a 2 channel STO output are provided and configured.

The (typical) System Overview is shown in the figure below.

Optionally the Generic Control Case can be extended with an Application Case that will provide a robot or machine with power or servo amplifiers. Vectioneer has a standard Application 48v case for 48VDC robots.

what’s in the box

After Buying a GCC you the following components should be in the box:

  • 1x Generic Control Cabinet
  • 1x IEC C13 Power cable with Schuko (EU) plug
  • 1x Ethernet cable (1m)
  • 1x E-stop Button
  • 1x E-Stop Cable (5m)
  • 2x Spare Male M12 A-coded Connectors
  • 1x Spare Female M12 A-coded Connector

Connecting the Generic Control Case

To connect the Generic Control Case to your pc you will need to go trough te following steps.

  1. Connect the powercable to the power connector and a powerinlet
  2. Connect the E-stop using the E-stop Cable at the E-stop M12 connector.
  3. Connect the Yellow Ethernet Cable to the ENET port and your PC.
  4. Turn on your Generic Control case by pressing the Power Switch.
  5. The status light should light up white.

To continue setting up the connection to your Generic Control Case follow the steps at Generic Control Case Connect your PC.

Generic Control Case Connections

This chapter will provide more information on how to connect the hardware of the Generic Control Case. All of the connectors are located on the front panel of the Case. The figure below provides an overview of all connectors, which can be grouped as:

  • Power Connector
  • Supply Voltage Connectors
  • Safety Connectors
  • Networking Connectors
  • Media Connectors

Power In Connector

The Generic Control Case Receives power trough the Fused IEC C14 Power inlet. Voltage supplied should be between 85 and 264VAC.

Always make sure the correct fuse is placed in the fuse holder. Standard a 5x20mm 3.5A speed T fuse is placed inside the fuse holder.

24VDC Out Connectors

The 24V DC supply voltage connectors at the front of the case are two Female A-coded M12 connectors marked with 24V. These connectors provide a interface for Us “bus voltage” +24V DC and Up “auxiliary voltage” power to the user. The figure below shows the pin-out of these connectors.

Pin Description
1 +24 V DC Us (Σ 2A max for all Us)
2 +24 V DC Up (Σ 3 A max for all Up)
3 0 V DC
4 0 V DC
5 PE

The 24V DC output is protected from over current and over voltage protection values can be found in the table below.

Case Internal Protection
Over-current protection 3A Circuit Braker
Over-voltage Protection 27.60 to 33.60V Automatically resetting
Logic Out Protection (Us)
Over-current protection 2A Circuit Braker
Over-voltage Protection 27.60 to 33.60V Automatically resetting
Auxiliary Power Protection (Up)
Over-current protection 4.2A Circuit Braker
Over-voltage Protection 27.60 to 33.60V Automatically resetting

* Note that the over-voltage protection of the Internal Case and Logic Out is combined.

* Note that the circuit brakers can be manually reset by the user.

Safety connectors

The GCC has two safety connectors, that can be easily identified by their yellow insert. These connectors allow the user to easily hook-up safety devices.

  • An Emergency Stop button can be connected to the female A-coded M12 connector.
  • A Safe output is available on the male A-coded M12 connector and can be used for e.g.for STO “Safe Torque Off” on Motor drives or a Safety Relay.

The figure below shows the pin-out of these connectors.

Emergency Stop

The GCC is outfitted with a M12 yellow e-stop connector for connecting the E-stop that comes in the box.

Pin Description
1 Pulse Output 1
2 Safe Input 1
3 Pulse Output 2
4 Safe Input 2
5 N.C.

STO-out

The STO-OUT Connector on the GCC is desitined for components using a safe torque off (STO) function. Using a Application Cabinet 48V the STO-OUT should be connected to STO-IN.

Pin Description
1 +24 V DC Us (Σ 2A max for all Us)
2 STO channel 1 (24v DC, 0.5A max)
3 0 V DC
4 STO channel 2 (24v DC, 0.5A max)
5 Feedback STO (non-safe)

The image below will provide an example of wiring STO output to drives with STO-input:

Example of STO-out connection to drives with STO-input

Altenatively, the STO can also be used with some types of Safety Relays if STO is not available on the drives. An example is given below:

Example of STO-out connection to a Safety Relay

Make sure that the Safety Relay is dimensioned for the load of the drives and motors.

Networking Connectors

On the top left of the front panel there are three RJ45 Cat6E ports. The table below provides an overview of the network ports

Port Description
ENET Gigabit Ethernet port (Used to connect to Motion PC), do not connect EtherCAT to this port
ECAT1 EtherCAT (Used to connect EtherCAT device), do not connect Ethernet to this port
ECAT2 EtherCAT (Used to connect EtherCAT device), do not connect Ethernet to this port

Note: That the ECAT2 port is always the last EtherCAT chain in the bus.

Media Connectors

On the bottom left of the front panel there are several media connectors. The table below provides detailed information:

Port Description
HDMI 1.4 4K @ 30 Hz
USB Blue: USB 3.0 White: USB 2.0
USB Blue: USB 3.0 White: USB 2.0

Auxiliary ports

On the front panel there are also two auxiliary ports marked with AUX. These ports are not connected and optional for the user to add extra port(s) via an connector that has an XLR form factor.

Operation of the Generic Control Case

This chapter provide more detail of operating the Generic Control Case. this chapter will go trough

  • switching on
  • switching off
  • connecting to Generic control cabinet

Switching the Case on

The Generic Control Case can be turned on by pressing the latching power button. When pressed the button should light up White, indicating that the case is powered with 24V DC. If the case does not power up its possible that one of the circuit breakers has been tripped. Resetting the internal circuit breaker manually has to be done by the following steps:

Make sure that the power cable is removed from the case before opening the case.

  1. Remove the side cover by removing the rubber strips with 4 Phillips screws as shown in the figure below.

\

  1. Reset the circuit breaker by pressing the button on top of the circuit breaker. The Location of the circuit breaker is shown in the figure below.

\

  1. When finished mount the right cover back on to the case. Make sure all that all panels line out correctly before fastening the Phillips screws.

If the case is powered the Motion PC will automatically start-up and the Status light will light up white if the system is “OK”

The Status Lamp is an RGB LED that is connected to 3 digital outputs (one for each channel). The Color of the lamp can be changed by changing the outputs accordingly from the Control Application. In the default installed Generic Application the Status Lamp pis configured as follows:

Status lamp color meaning
White System Okay
Yellow A Warning is active
Red An Error is active (Forced Disengage or Emergency Stop)

Note: More detail of these errors can be found in the GUI of the generic-app also it is possible to reset the errors in this GUI. More information about this can be found in Accessing the User Interface from your Controller

Switching the Case off

The Generic Control Case can be Turned Off by pressing the Power button such that it pops up to its off position. The power will be removed from the case.

7.2 - Application Case 48V

Introduction

This document is the User Manual for the Vectioneer Application Case 48V and a addition to the Generic Contol Case. This case provides 48v and a Interface for more demanding applications for example Robots.

Application Case 48V connections

This chapter will explain how to connect the hardware of the Application Case 48V. All of the connectors are located on the front panel of the Case.

Front vieuw of AC 48 Case

Power Connector

The Application Case 48V Receives power trough the IEC C14 Power inlet. Voltage supplied should be between 100 and 250VAC. Inside the Case there is a 10A Circuit breaker to protect the power Inlet.

The Circuit breaker is designed for protection on CE regulation. This will result in reduced power of the 48V power supply when using +/- 100V. It is possible to place a 15A Circuit breaker according to UL regulation.

STO IN connector

A Male A-coded M12 connector provides Safe output for STO (Safe Torque Off) from the Generic Control Case to the Robot Connector. The figure below shows the pin-out of this connector.

Pin Description
1 +24 V DC Us (Σ 2A max for all Us from GCC)
2 STO channel 1 (24v DC, 0.5A max)
3 0 V DC
4 STO channel 2 (24v DC, 0.5A max)
5 Feedback STO (non-safe)

The image below will provide an example of wiring STO output to drives with STO-input:

Example of STO-out connection to drives with STO-input

Altenatively, the STO can also be used with some types of Safety Relays if STO is not available on the drives. An example is given below:

Example of STO-out connection to a Safety Relay

Make sure that the Safety Relay is dimensioned for the load of the drives and motors.

EtherCAT IN Connector

On the front panel there is one RJ45 Cat6E port. It is possible to use this port to connect a EtherCAT port from the Generic Control Case to the Robot Connector.

Auxiliary ports

On the front panel there are also two auxiliary ports marked with AUX. These ports are not connected and optional for the user to reconfigure.

Robot Connector

The Application Case 48V has one Robot Connector for the user to connect a robot to. And still make it possible to connect separately without connector. In the robot connector there are three connectors:

  • 48V DC power connectors
  • Robot EtherCAT Connector
  • Robot STO Connector

48V DC power OUT Connector

On the Application Case 48V has an internal voltage of 48V DC. On the front Panel in the Robot connector position A there is a 2 Pole connector for the user. Protection values can be found in the table below:

Case Protection
Over-current protection 32A Self resetting Circuit breaker
Over-voltage Protection 57.00 to 67.20 Automatically resetting

Pin Description
1 +48 V DC Us (32A max)
2 0 v DC

EtherCAT OUT Connector

In the Robot Connector Position B There is a RJ45 Interface to connect to EtherCAT.

STO OUT connector

In the Robot Connector Position C there is a 5 pole connector for STO.

Pin Description
1 +24 V DC Us (2A max)
2 STO channel 1 (24v DC, 0.5A max)
3 0 V DC
4 STO channel 2 (24v DC, 0.5A max)
5 PE

Switching the Case on

The 48V Application Case can be turned on by rotating the main disconnector. When set to “1” the Status LED should light up White, indicating that the Case is provided with 48V DC.

If this it not the case it might be possible that the circuit breaker is tripped. Resetting the Circuit breaker can be done by the following steps

Make sure that the Power Cable is removed from the case before opening the case.

  1. Remove the side cover by removing 4 Phillips screws as shown in the figure below

  1. Reset the circuit breaker by flicking the the switch on top of the circuit breaker. Location of the circuit breakers is shown in the figure below.

  1. When finished mount the right cover back on to the case. Make sure all that all panels line out correctly before fastening the Phillips screws.

After any Fault the User shall check the cause of the Fault and make sure the problem is solved.

Switching the Case off

The 48V Application Case can be Turned Off by rotating the main disconnector. When set to “0” the Status LED will fade out, indicating that the Case is no longer provided with 48V DC.

Keep in mind that the Disconnector will turn off the 48 VDC. All other instances like STO and EtherCAT will stay connected.

7.3 - Motorcortex Fitlet2

Fitlet2 - Manual

Motorcortex Fitlet2 - Manual

The Motorcortex Fitlet2 is a ideal Industrial Embedded Computer to try out MOTORCORTEX. This Fitlet2 comes pre-installed with Vectioneer Linux and MOTORCORTEX-Core libraries. Is also has the Vectioneer Generic-App installed that allows you to control a number of EtherCAT servo drives out of the box. Or use it as a platform to build your own custom MOTORCORTEX-based control systems in C++ and use the tools on motorcortex.io to configure hardware devices, deploy web-interfaces to your controller and analyze your system’s realtime data.

More detailed information on the Fitlet2 Industrial PC can be found on the FITPC WIKI

Connecting the Fitlet2

This chapter will explain how to connect the hardware of the Motorcortex Fitlet2. all interfaces are located in the front and the back the figure below provides an overvieuw of all interfaces:

  • 2x USB 2.0 (White)
  • 1x HDMI
  • 1x mini display port
  • 1x 12v Power connector
  • 1x COM port
  • 2x RJ45 ports Eth1|2
  • 1x powerbutton
  • 2x USB 3.0 (Blue)
  • 1x micro SD slot

Front view fitlet 2

Communication from and to the Motorcortex Fitlet2 will go trough the RJ45 connectors. it is also possible to connect directly to the Motorcortex Fitlet2 with a screen and USB keyboard.

RJ45 Connectors

Communication from and to the Motorcortex Fitlet2 will go trough the RJ45 connectors. Eth1 is configured for Ethercat and Eth2 is configuered for ethernet connection.

7.4 - Virtual machine

This chapter will explain how to install a Virtual Machine on your PC. Please select the operating system you are u using:

Linux Linux Windows Windows Windows MacOS

A vitrual machine can be used to try out Motorcortex. Using a virtual machine you will need a .img file or a .vdi file. and VirtualBox installed on your machine. this chapter will show how to install VirtualBox and get your virtual machine up and going.

Installing VirtualBox (Linux)

To get VirtualBox you wil have to download it from the https://www.virtualbox.org/wiki/Downloads website. choose the operating system you are using. and download the .deb file.

  1. Double click the .deb file.

  2. Click install in the pop-up. VirtualBox will now be installed.

Converting image

to use virtual box you will need a .vdi file. If you have a .img or compressed .img.xz you will need to convert these files using the following commands.

to uncompress a .img.xz file run the following command in the folder the file is located.

    unxz -k -v yourfile.xz

the compressed image will now be uncompressed. after this you can convert the .img file to a .vdi file. make sure you are in the correct folder where the file is located.

    VBoxManage convertfromraw yourfile.img yourfile.vdi		

Setting up the virtal machine

Setting up the virtual machine has to be done using the folowing steps:

  1. Open VirtualBox and click on New.

  1. In the Create Virtual Machine pop-up the following settings have to be selected.
  • Name: desired name
  • Machine Folder: desired folder
  • Type: Linux
  • Version: Linux 2.6/3.x/4.x(64-bit)

  1. Click Next.

  2. Set the memory size to 8000 MB and click Next.

  1. select the Use an existing virtual hard disk file and click on the folder icon.

  1. Click the Add icon and browse to the desired .vdi file.

  1. Click Choose.

  1. Click Create.

A virtual machine is created. Now the Network has to be configured.

  1. Click File and go to Host Network Manager.

  1. In the Host Network Manager fill in the settings as following:
  • Disable the DHCP Server by unchecking the box
  • IPv4 Address: 192.168.2.1
  • Network Mask: 255.255.255.0

  1. Close the Host Network Manager.

The network manager is now configured. Now the system settings have to be checked.

  1. click on settings.

  1. In System under the Motherboard tab make sure the Enable EFI box is checked.

  1. In System under the Motherboard tab make sure that Processor(s) is set to 4 CPU’s.

  1. In Network under the Adapter1 tab set Attached to to Host-only Adapter.

  1. Click OK

The virtual machine has now been set up.

Using virtual machine

Starting your virtual machine has to be done using the folowing steps:

  1. In virtual box select the desired virtual machine and press Start.

  1. The virtual machine will boot now this can take up to 5 seconds or longer.

  1. Log in to the controller.
  • Login: Admin
  • Password: vectioneer

the command line should change like this.

    mcx-intel:~$

If no hardware is connected to the virtual machine make sure the simulation mode is activated. how to activate simulation mode is described in Sumulation Mode

7.5 -

Bios Settings Fitlet2

Introduction

This chapter tells the bios settings of the Fitlet2 Motorcortex Controller.

These settings make it easier to back-up the system and use other storage devices to boot from.

Setting Fitlet2 Bios settings

  1. Make sure the controller is switched off.
  2. Attach a keyboard to one of the USB-ports.
  3. Start tapping the delete key.
  4. Switch the controller on.
  5. Stop tapping the delete key when the bios menu appears.
  6. In the Main screen Load Optimized Defaults by pressing the F3 key. Select Yes.

  1. Use the arow keys to navigate trough the BIOS. Go to OS Selection hit enter and select Linux.

  1. Go to the Boot screen using the arow keys and go to Boot Options hit enter and set the correct boot options as below:

    1. Go to Boot Option #1 and select USB Key.
    2. Go to Boot Option #2 and select USB HDD.
    3. Go to Boot Option #3 and select USB CD/DVD.
    4. Go to Boot Option #4 and select SD.
    5. Go to Boot Option #5 and select HDD:....

  1. go to the Save & Exit screen.
  2. Press F4 or go to Save Changes and Exit. Select Yes.

7.6 -

This chapter will explain how to install a Virtual Machine on your PC. Please select the operating system you are u using:

Linux Linux Windows Windows Windows MacOS

A vitrual machine can be used to try out Motorcortex. Using a virtual machine you will need a .img file or a .vdi file. and VirtualBox installed on your machine. this chapter will show how to install VirtualBox and get your virtual machine up and going.

Installing VirtualBox (Windows)

To get VirtualBox you wil have to download it from the https://www.virtualbox.org/wiki/Downloads website. choose the operating system you are using. and download the .exe file.

  1. Double click the .exe file.

  2. The setup wizard will pop-up click next.

  1. Click Next unless you want to change the location for the VirtualBox.

  1. Click ‘Next’ unless you want to change some of the install options.

  1. A warning will tell you that network connections will be disconected temporarily. Click Yes.

  1. Click Install.

  1. The instalation will start. During the instalation a security warning will pop-up click Install.

  1. click Finish to complete the instalation.

Converting image

to use virtual box a .vdi file is needed. .img files or compressed .img.xz files have to be converted.

to uncompress a .img.xz file run the following command in the folder the file is located.

    unxz -k -v yourfile.xz

the compressed image will now be uncompressed. after this you can convert the .img file to a .vdi file. make sure you are in the correct folder where the file is located.

    VBoxManage convertfromraw yourfile.img yourfile.vdi		

Setting up virtal machine

Setting up the virtual machine has to be done using the folowing steps:

  1. Open VirtualBox and click on New.

  1. In the Create Virtual Machine pop-up the following settings have to be selected.
  • Name: desired name
  • Machine Folder: desired folder
  • Type: Linux
  • Version: Linux 2.6/3.x/4.x(64-bit)

  1. Click Next.

  2. Set the memory size to 8000 MB and click Next.

  1. select the Use an existing virtual hard disk file and click on the folder icon.

  1. Click the Add icon and browse to the desired .vdi file.

  1. Click Choose.

  1. Click Create.

A virtual machine is created. Now the Network has to be configured.

  1. Click File and go to Host Network Manager.

  1. In the Host Network Manager fill in the settings as following:
  • Disable the DHCP Server by unchecking the box
  • IPv4 Address: 192.168.2.1
  • Network Mask: 255.255.255.0

  1. Close the Host Network Manager.

The network manager is now configured. Now the system settings have to be checked.

  1. click on settings.

  1. In System under the Motherboard tab make sure the Enable EFI box is checked.

  1. In System under the Motherboard tab make sure that Processor(s) is set to 4 CPU’s.

  1. In Network under the Adapter1 tab set Attached to to Host-only Adapter.

  1. Click OK

The virtual machine has now been set up.

Using virtual machine

Starting your virtual machine has to be done using the folowing steps:

  1. In virtual box select the desired virtual machine and press Start.

  1. The virtual machine will boot now this can take up to 5 seconds or longer.

  1. Log in to the controller.
  • Login: Admin
  • Password: vectioneer

the command line should change like this.

    mcx-intel:~$

If no hardware is connected to the virtual machine make sure the simulation mode is activated. how to activate simulation mode is described in Sumulation Mode