09/04/2023

WebIQ - Communicate with ctrlX CORE Rest API

In WebIQ 2.13 there is no out of the box feature to communicate via REST API with the ctrlX CORE.
However, since you can include JS libraries in WebIQ, we show here how to include the axios library (axios-http.com) to communicate via JavaScript with the REST API of the ctrlX CORE.

Required WebIQ Designer version 1.13 or higher.

For more info on REST API see: Using REST API of ctrlX CORE 

The following steps are necessary in WebIQ Designer:

  1. Download package-axios.zip and DemoRestAPI-v*.zip (see end of this article)
  2. Upload WebIQ project "Demo-RestAPI-v*"
  3. Load project into workspace
  4. Open "Package Manager" in "Project Dashboard"
  5. "Upload package" file "package-axios.zip"
  6. Install the package
  7. Now the package is displayed in folder "Installed"
  8. Run the project in preview mode or in browser
  9. Enter the IP address of the ctrlX CORE or ctrlX COREvirtual, a valid user name and password
  10. Enter user name and password
  11. Press button "Rest API call"
  12. You find the example code in the UI action APIcall.
    /**
     * Custom UI-Action 'APIcall'.
     *
     * Description:
     * [Executes a REST API call to set PLC symbol on data layer]
     * lib-axios package must be installed
     * see https://axios-http.com/ how to use axios package.
     */
    (function () {
        'use strict';
        var actions = shmi.pkg("visuals.session.userActions"); //get reference to userActions object
        /**
         * UI-Action 'APIcall' implementation
         *
         * @params {any[]} parameters  configured ui-action parameters
         * @param[0] {string} var name ip address
         * @param[1] {string} var name user
         * @param[2] {string} var name password
         * 
         */
        actions["APIcall"] = async function (parameters) {
            let sReq = "";
            let sResult = "";
            let bError = false;
            const im = shmi.requires("visuals.session.ItemManager");
            // read entered data
            let sIP = im.readValue(parameters[0]);
            var sHost = `https://${sIP}/`;
            var sUser = im.readValue(parameters[1]);
            var sPwd = im.readValue(parameters[2]);
            sResult = `Host     = "${sHost}"\nUser     = "${sUser}"\nPassword = "${sPwd}"\n\n`;
            // check if all data are provided
            if (sIP === "") {
                sResult += "Fill in IP address\n";
                bError = true;
            }
            if (sUser === "") {
                sResult += "Fill in user name\n";
                bError = true;
            }
            if (sPwd === "") {
                sResult += "Fill in password\n";
                bError = true;
            }
    
            if (bError === false) {
                // login to identify me 
                try {
                    sReq = sHost + 'identity-manager/api/v1.0/auth/token';
                    var response = await axios.post(sReq, { name: sUser, password: sPwd });
                    if (response === null) {
                        sResult += `AXIOS call failed, check if package-axios is installed.`;
                        bError = true;
                    }
                }
                catch (err) {
                    sResult += `AXIOS unable to post request: ${err}\n${sReq}\nPlease check ip, user and password`;
                    bError = true;
                }
    
                if (bError === false) {
                    const token = response.data.access_token;
                    const config = { headers: { authorization: 'Bearer ' + token } };
    
                    // ***** list installed packages (=apps) *****
                    try {
                        sReq = sHost + `package-manager/api/v1/packages`;
                        sResult += `\n\nRequest: ${sReq}\n`;
                        sResult += `Status: ${response.status} ${response.statusText}\n`;
                        response = await axios.get(sReq, config);
                        sResult += " Apps:\n";
                        for (let i = 0; i < response.data.length; i++) {
                            let sApp = `${response.data[i].name} ${response.data[i].release.version} ${response.data[i].appType}`;
                            sResult += `${i}:${sApp}\n`;
                        }
                    }
                    catch (err) {
                        sResult += `Put error: ${err}`;
                        bError = true;
                    }
                    // ***************  list axes *********************************
                    let data = {};
                    let arGetCmds = ["system/api/v1/info", "automation/api/v2/nodes/motion/axs?type=browse"];
                    for (let i = 0; i < arGetCmds.length; i++) {
                        if (bError === false) {
                            // example: read system info of ctrlX
                            try {
                                sReq = sHost + arGetCmds[i];
                                sResult += `\n\nRequest: ${sReq}\n`;
                                response = await axios.get(sReq, config);
                                sResult += `Status: ${response.status} ${response.statusText}\n`;
                                if (i === 1) {
                                    sResult += " Axes: "
                                    for (let j = 0; j < response.data.value.length; j++) {
                                        sResult += `${j}:${response.data.value[j]}, `;
                                    }
                                } else {
                                    for (let sKey in response.data) {
                                        sResult += `  ${sKey} = ${response.data[sKey]}\n`;
                                    }
                                    //sResult += JSON.stringify(response.data, null, 2);
                                }
                            }
                            catch (err) {
                                sResult += `Put error: ${err}`;
                                bError = true;
                            }
                        }
                    }
    
                    // ***** dir listing of DefaultSolution: configurations/appdata/script *****
                    try {
                        const sSolutionName = "DefaultSolution";
                        const sDir = "configurations/appdata/script";
                        sReq = sHost + `solutions/api/v1/solutions/${sSolutionName}/content?dir=${sDir}`;
                        sResult += `\n\nRequest: ${sReq}\n`;
                        sResult += `Status: ${response.status} ${response.statusText}\n`;
                        response = await axios.get(sReq, config);
                        sResult += " Files: "
                        for (let i = 0; i < response.data.files.length; i++) {
                            let sFile = response.data.files[i].name.replace(/"/g, '');
                            sResult += `${i}:${sFile}, `;
                        }
                    }
                    catch (err) {
                        sResult += `Put error: ${err}`;
                        bError = true;
                    }
                }
            }
            im.writeValue("SString", sResult);      
    }());​
  13. See https://axios-http.com for information how to program axios
  14. See "API Reference" on ctrlX CORE Web page for REST API commands of ctrlX CORE

     

Update WebIQ package with a new version of axios

Based on article on SmartHMI web page the package was created: How To Create a Custom Widget 

  1. Unzip package-axios
  2. Download axios.min.js from https://axios-http.com alternatively look on the
    website https://cdnjs.com/libraries where many JS library files are collected for an easy download.
  3. Replace file in the folder
  4. Change version from "0.27.2" to version of axios.min.js in file package-axios\webiq.json
    {
      "format": 2,
      "name": "package-axios",
      "description": "Axios is a promise-based HTTP Client for node.js and the browser (axios-http.com). Use JaveScript in WebIQ to connect to ctrlX CORE REST API",
      "type": "library",
      "version": "0.27.2",
      "forceInstall": false,
      "forceUpdate": false,
      "keep": [
      ],
      "localeVariables": {
      },
      "localScripts": {
        },
      "requires": {
        "visuals": "^2.0.0"
      }
    }​
  5. To crate the WebIQ package, create a Zip file from the folder package-axios
  6. Now you can install the new package file

HINT: In version 2.12.1 there is a bug that some package names are not accepted. Bug fixed in 2.13. The following error then occurs:

Rename the package until you find a name, which is accepted. I assume that the bug will be fixed in the next release.

The Company 

Empowering HMI Excellence
Smart HMI is a team of experts for the development, enablement and integration of 100% Web-Technology based Software, which empowers every customer to easily create future-oriented industrial HMI solutions. The Software Platform WebIQ – developed by Smart HMI -is a 100% Web-Technology based, forward-looking Visualization-System with comprehensive Design-possibilities to create industrial Web HMI’s.

package-axios.zip
9.04KB
Demo-RestAPI-v1.1.zip
8.95MB

Latest published/updated articles

Types
Example
How-to
Categories
HMI