HmiGuide_0-1660918342332.png

WebIQ - Communicate with ctrlX CORE Rest API

HmiGuide
Community Moderator
Community Moderator

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*"
    HmiGuide_0-1660913327114.png
  3. Load project into workspace
    HmiGuide_1-1660913372366.png
  4. Open "Package Manager" in "Project Dashboard"
    HmiGuide_2-1660913432520.png
  5. "Upload package" file "package-axios.zip"
    HmiGuide_3-1660913488171.png
  6. Install the package
    HmiGuide_4-1660913560036.png
  7. Now the package is displayed in folder "Installed"
    HmiGuide_5-1660913739807.png
  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"
    HmiGuide_6-1660914091181.png
  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
    HmiGuide_7-1660914551735.png

     

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
    HmiGuide_0-1660915374140.png
  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:

HmiGuide_1-1660916087819.png

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.

SmartHMI_Logo.png

Must Read
Icon--AD-black-48x48Icon--address-consumer-data-black-48x48Icon--appointment-black-48x48Icon--back-left-black-48x48Icon--calendar-black-48x48Icon--center-alignedIcon--Checkbox-checkIcon--clock-black-48x48Icon--close-black-48x48Icon--compare-black-48x48Icon--confirmation-black-48x48Icon--dealer-details-black-48x48Icon--delete-black-48x48Icon--delivery-black-48x48Icon--down-black-48x48Icon--download-black-48x48Ic-OverlayAlertIcon--externallink-black-48x48Icon-Filledforward-right_adjustedIcon--grid-view-black-48x48IC_gd_Check-Circle170821_Icons_Community170823_Bosch_Icons170823_Bosch_Icons170821_Icons_CommunityIC-logout170821_Icons_Community170825_Bosch_Icons170821_Icons_CommunityIC-shopping-cart2170821_Icons_CommunityIC-upIC_UserIcon--imageIcon--info-i-black-48x48Icon--left-alignedIcon--Less-minimize-black-48x48Icon-FilledIcon--List-Check-grennIcon--List-Check-blackIcon--List-Cross-blackIcon--list-view-mobile-black-48x48Icon--list-view-black-48x48Icon--More-Maximize-black-48x48Icon--my-product-black-48x48Icon--newsletter-black-48x48Icon--payment-black-48x48Icon--print-black-48x48Icon--promotion-black-48x48Icon--registration-black-48x48Icon--Reset-black-48x48Icon--right-alignedshare-circle1Icon--share-black-48x48Icon--shopping-bag-black-48x48Icon-shopping-cartIcon--start-play-black-48x48Icon--store-locator-black-48x48Ic-OverlayAlertIcon--summary-black-48x48tumblrIcon-FilledvineIc-OverlayAlertwhishlist