Teaser.jpg

Generate API client libraries from Engineering API

CopyPaste
Member

Overview

This blog will show you how to generate API client libraries. API client libraries is a code or an app that can access the provided REST services. Client code generators are used to create such API Client Libraries. Few well known client code generators are Swagger Codegen CLIAutoRestNSwag, and OpenAPI Generator. These tools  require NPM or the Java Runtime Environment to be installed on the developers machine. Alternative Java SDK implementations such as the OpenJDK works fine with this extension. 

The Swagger Codegen CLI and OpenAPI Generator are distributed as JAR files and are downloaded on demand but requires the Java SDK to be installed on the machine. AutoRest is installed on-demand via NPM as a global tool and uses the latest available version.

NSwagStudio is stand alone UI tool for editing a .nswag specification file for generating code. This tool is optional to install and official installation instructions are available on the NSwag Wiki on Github. If NSwagStudio is not installed on the machine then the Visual Studio Extension will install the NSwag CLI via NPM as a global tool using the latest available version.

For CSharp Environment
Prerequisites
  • Latest ctrlX WORKS with PLC and IO Engineering is installed
  • Visual Studio is installed. (As an alternative Visual Studio Code can be used with extension C# for Visual Studio Code)
  • Swagger Codegen CLI is downloaded. For Windows users, you can use Invoke-WebRequest in PowerShell (3.0+) to download swagger-codegen-cli v3.0.33, e.g.
    Invoke-WebRequest -OutFile swagger-codegen-cli.jar https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.33/swagger-codegen-cli-3.0.33.jar
  • If you're looking for the latest stable Swagger Codegen CLI version, you can grab it directly from Maven.org (search for swagger-codegen-cli)
  • Swagger Codegen is a Java app, so you must have Java Runtime Environment installedAdditionally JAVA_HOME environment variable, should point to java.exe path

Generate API client libraries using Swagger Codegen CLI
CSharp client library for PLC Engineering
  • Open installed ctrlX WORKS directory and navigate to → Studio\Help\API-CodeGenerator. (For ctrlX WORKS WRK-V-0112.4 version and below,  folder 'API-CodeGenerator' is not available, you can download the files from attachment)
  • Copy the contents of API-CodeGenerator and downloaded swagger-codegen-cli.jar to a folder inside your work directory (e.g. D:\CodeGen) as shown below:

    2022-02-18_10h23_53.png
  • To generate PLC Engineering API client library, run 'Generate_Rexroth_PlcEng_APIClient_CSharp.bat'
  • After successful generation, you will see a folder named 'Rexroth_PlcEng_APIClient_CSharp' as shown below:

    2022-02-18_10h25_11.png
  • Navigate to 'Rexroth_PlcEng_APIClient_CSharp' directory and run 'build.bat'. This downloads required packages and DLLs are available under bin folder as shown below. (The Codegen also creates a README file with all the information for running and building the API)

2022-02-16_10h22_22.png

 

 

 

 

 

 

 

 

 

  • Open 'Rexroth.Api.PlcEngineering.sln', project will be opened in Visual Studio
  • In Visual Studio, navigate and open Edit → Find and Replace → Replace in Files
  • In the editor, enter base(elementType, name, id, children) in find textbox  and enter base(elementType, name) in replace textbox and click on Replace All as shown below. (This step is required to correct few errors caused by Swagger Codegen CLI for CSharp language. Same errors might not occur in different language(s) or with different code generator(s))

2022-02-16_10h27_43.png

  • Again enter base(jobType, id, state, progress, jobResultInfo) in find textbox  and enter base(jobType, jobResultInfo) in replace textbox and click on Replace All as shown below. (This step is required to correct few errors caused by Swagger Codegen CLI for CSharp language. Same errors might not occur in different language(s) or with different code generator(s))

    2022-02-16_10h28_26.png
  • Only for ctrlX WORKS WRK-V-0112.4 version and below, additional changes are required to the generated file (Rexroth_PlcEng_APIClient_CSharp\src\Rexroth.Api.PlcEngineering\Model\RecipeManager.cs). Changes should match to below shown images (see line number in the below image as reference):
    Add missing AssignmentAdd missing AssignmentSelect Assignment from the enumSelect Assignment from the enumSelect Assignment from the enumSelect Assignment from the enum
  • In Visual Studio, navigate and click on Build → Rebuild Solution(Rebuild Solution should be successful, If you still have build error, ask for help in the comment section)
  • After successful build,  DLL's are available (under the `bin` folder) in the C# project as shown below:

    2022-02-16_10h30_25.png
  • For more information/examples on available API functions, navigate to menu Help → API-reference in ctrlX PLC Engineering

CSharp client library for IO Engineering
  • Run 'Generate_Rexroth_IoEng_APIClient_CSharp.bat' and follow steps similar to client library generation for PLC Engineering
  • For more information/examples on available API functions, navigate to menu Help → API-reference in ctrlX IO Engineering

Java client library for PLC and IO Engineering
  • Run 'Generate_Rexroth_PlcEng_APIClient_Java.bat' and 'Generate_Rexroth_IoEng_APIClient_Java.bat'
  • To build and install the generated API client, follow the README file inside the created 'Rexroth_PlcEng_APIClient_Java' and 'Rexroth_IoEng_APIClient_Java' folder

Client library for other languages
  • Swagger Codegen CLI also supports many other languages/frameworks. For more information visit there GitHub

Create a Test Application
CSharp console application for PLC Engineering
  • In Visual Studio, navigate and click on File → New → Project. Follow the instructions in the dialog and Create an Console App (.NET Framework)
  • Add generated 'Rexroth.Api.PlcEngineering.dll' reference to the created console application as shown below:

    2022-02-16_10h40_03.png
  • Open Program.cs file and replace existing code with below code:
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Threading;
    using Rexroth.Api.PlcEngineering.Api;
    using Rexroth.Api.PlcEngineering.Client;
    using Rexroth.Api.PlcEngineering.Model;
     
    namespace ConsoleApp
    {
      public class Program
      {
        static void Main(string[] args)
        {
          try
          {
            Console.WriteLine("Start PLC Engineering and create a new project");
            //Latest installed or latest used ctrlX WORKS instance will be used to start engineering
            //For ctrlX WORKS version WRK-V-0112.4 and below, protocol 'rexrothstudio://plc/?' to start engineering is not supported, use
            //Process.Start(@"path to engineering exe") and open existing project using 'ProjectJob' in API
            Process.Start("rexrothstudio://plc/?hostname=localhost&newproject=d:\\ctrlX\\Projects");
     
            //Wait till Engineering is ready for input
            Thread.Sleep(20000);
     
            //Set base path to the actual URL with port
            Configuration config = new Configuration {BasePath = "http://localhost:9002/plc/engineering/api/v2"};
     
            //Create new device api instance with the actual URL
            DevicesApi devicesApi = new DevicesApi(config);
     
            //Create a device with mandatory parameters
            Device ctrlXCoreDevice = new Device(name: "ctrlXCoreDevice", elementType: "Device");
            DeviceInfo deviceInfo = new DeviceInfo(deviceType: 4096, id: "1001 0080");
            ctrlXCoreDevice.DeviceInfo = deviceInfo;
     
            BaseElement addedDevice = devicesApi.AddDevices(ctrlXCoreDevice);
            Console.WriteLine($"Device added: {addedDevice.Name}");
     
            //Create and add task configuration
            TaskConfig taskConfigObj = new TaskConfig(elementType: "TaskConfig", name: "Task Configuration");
            devicesApi.AddDevicesByPath(taskConfigObj, "/ctrlXCoreDevice/PLC Logic/Application");
            Console.WriteLine("Task Configuration added");
     
            //Create and add a task
            Task taskObj = new Task(elementType: "Task", name: "MyTask")
            {
              Priority = "30",
              TaskGroup = "IEC-Tasks",
              Type = new TaskType("cyclic", "t#20ms"),
              Watchdog = new TaskWatchdog(false, "", "1"),
              PouCalls = new List<TaskPouCall>()
            {
              new TaskPouCall("Prg1", ""),
              new TaskPouCall("Prg2", "")
            }
            };
            devicesApi.AddDevicesByPath(taskObj, "/ctrlXCoreDevice/PLC Logic/Application/task-config");
            Console.WriteLine("Task added");
     
            Console.ReadLine();
          }
          catch (Exception e)
          {
            Console.WriteLine(e);
            throw;
          }
        }
      }
    }
  • After successful Build, Start the console app. This will start the ctrlX PLC Engineering with a new project and a DeviceTask Configuration, Task will be added to the project

Must Read

Trending

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