filou

A tutorial on using the OpenPLC runtime on embeded Linux systems.

 

The reason that prompted me, to look into the problem in more detail, was the slow speed of the compilation process. The main cause, is probably the limited speed of the mass storage SD card. “C++” compilation is a big challenge with regard to macros, definitions, templates, which are all located in many different header files.

 

Cross compiling is one of the answers to the limited resources of embedded systems.

 

OpenPLC already uses this technology with Arduino-based microcontroller hardware, without this is being particularly noticeable. The used avr-gcc is nothing other than a cross compiler. In a similar way, to how the Arduino IDE can be integrated into the editor, this should also be possible with a compiler for an ARM Linux target.

 

First Step, a new backend:

 

In the project window, in the configuration tab, you can select different targets. The "Generic" configuration is the key to our project, the command line contains the "make" command.

“make” is one of the oldest tools on unix platforms for controlling complex build processes.

 

The new backend is therefore a simple Makefile!

 

Let's take a closer look at the process. As usual, the editor generates the C sources from the ST file and saves them in the build subfolder in the project directory. Then make is started in this, with the Makefile file expected in the project_files subfolder. This is a bit confusing at first glance, but becomes clearer when you look at the file more closely. The reason for this is the clean separation of the different components.

    

CXX      = g++

CFLAGS  += -std=gnu++11

SOURCES  = ../project_files/core/client.cpp
SOURCES += ../project_files/core/custom_layer.h
SOURCES += ../project_files/core/hardware_layer.cpp
SOURCES += ../project_files/core/interactive_server.cpp
SOURCES += ../project_files/core/ladder.h
SOURCES += ../project_files/core/main.cpp
SOURCES += ../project_files/core/modbus_master.cpp
SOURCES += ../project_files/core/modbus.cpp
SOURCES += ../project_files/core/persistent_storage.cpp
SOURCES += ../project_files/core/server.cpp

SOURCES += glueVars.cpp

SOURCES += LOCATED_VARIABLES.h
SOURCES += POUS.c
SOURCES += POUS.h
OBJS     = Config0.o Res0.o

CPPFLAGS += -I ../project_files/include -w

%.o: %.c
  $(CXX) -c $(CFLAGS) $(CPPFLAGS) -o $@ $ <
glueVars.cpp:
  echo "Generating glueVars..."
  ../project_files/glue_generator

openplc: $(OBJS) $(SOURCES)
  $(CXX) $(CFLAGS) $(CPPFLAGS) *.cpp ../project_files/core/*.cpp -o openplc *.o -lrt -lpthread -fpermissive `pkg-config --cflags --libs libmodbus`

all: $(OBJS) openplc
  
clean:
  rm -fr $(OBJS) openplc
 

Let's take a closer look at the folder structure. In the core subdirectory we find a series of C++ source files, they come from the OpenPLC Runtime. One file of particular interest is "hardware_layer.cpp". This is where the platform-specific code goes. The starting point was "hardware_layer.cpp_empty", there is plenty of inspiration in the OpenPLC Runtime source code, located in "/..../OpenPLC_v3/webserver/core/hardware_layers"

 
OpenPLC_Makefile_Projekt.png
      
        

The build folder contains all files generated by Matiec iec2c and the OpenPLC glue generator, as well as the end result of the build process, the openplc executable file. The separation into core, include and build is necessary, because the content of the latter is overwritten by the editor.

        

        

OpenPLC_build.png
  
  

The Makefile already works on the command line, but in the editor, more precisely in the file toolchain_makefile.py, there is still an error from Beremiz times. Python2 and Python3 differ in some places and since this file has not been used in OpenPLC so far, no one has noticed.

  

toolchain_makefile.py  

Old Python2:  self.md5key = hashlib.md5(wholesrcdata).hexdigest()
New Python3:  self.md5key = hashlib.md5(wholesrcdata.encode('utf-8')).hexdigest()
 
 

Another hurdle lurks in "ProjectController.py". The existing targets are all treated the same, as of the type "simulator" and thus no located variables are created, which is necessary for the connection to hardware inputs and outputs. That is why I have expanded the code accordingly so that a distinction can made between "Makefile" and "Simulation" at the appropriate point. Since saving the intermediate ST file is also not necessary, I used the same mechanism to suppress the pop-up save window.

  

ProjectController.py

New:
        targetname = self.GetTarget().getcontent().getLocalTag()  
        self.logger.write("Target: "+targetname+"\n")

Old:      
            if self._buildType == "simulator":
                plc_file.write(self.RemoveLocatedVariables(fullPLCProg))
            else:
                plc_file.write(fullPLCProg)
    
New:    
           if targetname == "Generic":      
                plc_file.write(fullPLCProg)
            else:
                if self._buildType == "simulator":
                    plc_file.write(self.RemoveLocatedVariables(fullPLCProg))
                else:
                    plc_file.write(fullPLCProg)  



Old:      
def _generateOpenPLC(self):
        self._Clean()
        if (self._Build() is True):
            f = open(self._getIECgeneratedcodepath(), "r")
            program = f.read()
            f.close()
            dlg = wx.FileDialog(self.AppFrame, "Save to file:", "", "",
                                "OpenPLC Program(*.st)|*.st", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
            if dlg.ShowModal() == wx.ID_OK:
                try:
                    f = open(dlg.GetPath(), "w")
                    f.write(program)
                    f.close()
                    #wx.MessageBox('OpenPLC program generated successfully', 'Info', wx.OK | wx.ICON_INFORMATION)
                    self.logger.write(
                        "OpenPLC program generated successfully\n")
                except:
                    self.logger.write_error(
                        'It was not possible to save the generated program\n')
    
New:
def _generateOpenPLC(self):    
        targetname = self.GetTarget().getcontent().getLocalTag()  # FILOU
        self.logger.write("Target: "+targetname+"\n")

        self._Clean()
        if (self._Build() is True):
            if targetname != "Generic":
                f = open(self._getIECgeneratedcodepath(), "r")
                program = f.read()
                f.close()
                dlg = wx.FileDialog(self.AppFrame, "Save to file:", "", "",
                                    "OpenPLC Program(*.st)|*.st", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
                if dlg.ShowModal() == wx.ID_OK:
                    try:
                        f = open(dlg.GetPath(), "w")
                        f.write(program)
                        f.close()
                        #wx.MessageBox('OpenPLC program generated successfully', 'Info', wx.OK | wx.ICON_INFORMATION)
                        self.logger.write(
                            "OpenPLC program generated successfully\n")
                    except:
                        self.logger.write_error(
                            'It was not possible to save the generated program\n')
            else:
                self.logger.write("Generic OpenPLC program generated successfully\n")
 

Now we have everything we need for a Makefile backend. At the very top of the Makefile, are the two most important lines, here we can enter the desired cross compiler for our embedded Linux system. If it works on our Linux host, it should also be possible to compile it for another target. Since errors can always creep in, the host and target should not differ too much.
I have set up the following simple test system for this. The simplest Pi there is, the ZERO without WLAN, only with USB. The USB Ethernet gadget driver is used to connect to the host, it enables us to use an SSH console and upload via SCP. The connection to the outside world is handled by a CAN hat. I chose CAN, because it also works without any problems with a laptop and the microchip can bus analyzer.
Linux offers excellent support for the CAN bus, the cansocket API. The initialization and mapping between the OpenPLC buffer and the CAN Open messages takes place in the "hardware_layer.cpp". For development I use my laptop and if everything works there, the cross compiler can be started.
  
  
//-----------------------------------------------------------------------------
// Copyright 2015 Thiago Alves
//
// Based on the LDmicro software by Jonathan Westhues
// This file is part of the OpenPLC Software Stack.
//
// OpenPLC is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// OpenPLC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with OpenPLC.  If not, see <http://www.gnu.org/licenses/>.
//------
//
// This file is the hardware layer for the OpenPLC. If you change the platform
// where it is running, you may only need to change this file. All the I/O
// related stuff is here. Basically it provides functions to read and write
// to the OpenPLC internal buffers in order to update I/O state.
// Thiago Alves, Dec 2015
//
// Makefile example using CAN Bus, W.Fild, Aug 2024
//-----------------------------------------------------------------------------

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <stdbool.h>

#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>

#include <linux/can.h>
#include <linux/can/raw.h>

#include "ladder.h"
#include "custom_layer.h"


volatile int cansocket;   // can raw socket

volatile uint8_t can_output[2] = {0x00,0x00};
volatile uint8_t plc_output[2] = {0x00,0x00};

volatile uint8_t can_input[2]  = {0x00,0x00};

pthread_mutex_t canLock;

inline uint8_t bit_set_to(uint8_t number, uint8_t n, bool x) {
    return (number & ~((uint8_t)1 << n)) | ((uint8_t)x << n);
}

inline uint8_t bit_check(uint8_t number, uint8_t n) {
    return (number >> n) & (uint8_t)1;
}

void *canReadThread(void *arguments) {
  bool   run_server = true;
  int    nbytes;
  struct can_frame frame;

  fprintf(stderr,"Start CAN thread\n");
  fprintf(stderr,"Use thread socket %d\n",cansocket);

  while(run_server) {
    nbytes = read(cansocket, &frame, sizeof(struct can_frame));
    if (nbytes < 0) {
       perror("CAN Read");
    }
    if (nbytes > 0) {
      if ( frame.can_id == 0x181 ) {
        pthread_mutex_lock(&canLock);
          can_input[0] = frame.data[0];
          can_input[1] = frame.data[1];
        pthread_mutex_unlock(&canLock);
      }
    }
  }

  pthread_exit(NULL);
}

//-----------------------------------------------------------------------------
// This function is called by the main OpenPLC routine when it is initializing.
// Hardware initialization procedures should be here.
//-----------------------------------------------------------------------------
void initializeHardware() {
  struct can_frame frame;
  struct ifreq ifr;
  struct sockaddr_can addr;

//  MUTEX initialization

  if (pthread_mutex_init(&canLock, NULL) != 0) {
    printf("Mutex init failed\n");
    return;
  }

//  open socket

  if ((cansocket = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
    perror("socket");
    return;
  }

//  Next, we must retrieve the interface index for the interface name
//  (can0, can1, vcan0 etc) we wish to use. To do this we send an I/O
//  control call and pass an ifreq structure containing the interface name:

  strcpy(ifr.ifr_name, "can0" );
  ioctl(cansocket, SIOCGIFINDEX, &ifr);

  memset(&addr, 0, sizeof(addr));
  addr.can_family = AF_CAN;
  addr.can_ifindex = ifr.ifr_ifindex;

  if (bind(cansocket, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
    perror("bind");
    return;
  }

//  -------------------------- NMT ------------------------
//  Possible commands include transition to operational (state 01),
//  to stopped (state 02), pre-operational (state 80) as well as
//  reset application (81) and reset communication (82).
//
//  send frame NMT Start All

  frame.can_id = 0x000;
  frame.can_dlc = 2;
  frame.data[0] = 1;
  frame.data[1] = 0;

  if (write(cansocket, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
     perror("CAN Write");
     return;
  }

  pthread_t thread;
  int arguments[2];
  int ret = -1;

  arguments[0] = cansocket;
  fprintf(stderr,"Init thread socket %d\n",cansocket);
  ret = pthread_create(&thread, NULL, canReadThread, (void*)arguments);
  if (ret==0) {
    pthread_detach(thread);
  }
}

//-----------------------------------------------------------------------------
// This function is called by the main OpenPLC routine when it is finalizing.
// Resource clearing procedures should be here.
//-----------------------------------------------------------------------------
void finalizeHardware() {
  close(cansocket);
}

//-----------------------------------------------------------------------------
// This function is called by the OpenPLC in a loop. Here the internal buffers
// must be updated to reflect the actual Input state. The mutex bufferLock
// must be used to protect access to the buffers on a threaded environment.
//-----------------------------------------------------------------------------
void updateBuffersIn() {
  uint8_t plc_input[2];
  
  pthread_mutex_lock(&canLock);
    plc_input[0] = can_input[0];
    plc_input[1] = can_input[1];
  pthread_mutex_unlock(&canLock);

  pthread_mutex_lock(&bufferLock); //lock mutex

    for (int i=0; i<2; i++) {
      for (int j=0; j<8; j++) {
        if ( bool_input[i][j] != NULL ) {
          *bool_input[i][j] = bit_check(plc_input[i],j);
        }
      }
    }

  pthread_mutex_unlock(&bufferLock); //unlock mutex  
}
  

//-----------------------------------------------------------------------------
// This function is called by the OpenPLC in a loop. Here the internal buffers
// must be updated to reflect the actual Output state. The mutex bufferLock
// must be used to protect access to the buffers on a threaded environment.
//-----------------------------------------------------------------------------
void updateBuffersOut() {
  struct can_frame frame;
  bool changed = false;

  pthread_mutex_lock(&bufferLock); //lock mutex

    for (int i=0; i<2; i++) {
      for (int j=0; j<8; j++) {
        if ( bool_output[i][j] != NULL ) {
          plc_output[i] = bit_set_to(plc_output[i], j, *bool_output[i][j]);
        }
      }
      if ( plc_output[i] != can_output[i] ) {
        changed = true;
        can_output[i] = plc_output[i];
      }
    }

  pthread_mutex_unlock(&bufferLock); //unlock mutex

  if (changed) {
    /* send frame */
    frame.can_id = 0x201;
    frame.can_dlc = 2;
    frame.data[0] = can_output[0];
    frame.data[1] = can_output[1];

    if (write(cansocket, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
       perror("Write");
       return;
    }
  }
}
 
  
  
Thanks to the presets in the CANOpen standard, this works very easily in our test environment. Send NMT start message and use the two PDUs for data transfer. If an input changes, the CAN module reports automatically and we only send a message if something has changed in the OpenPLC program.
  
    
    
The last step, cross compilation for the Pi:
  
  
  
      
TOOLCHAIN=/opt/x-tools/armv6-rpi-linux-gnueabihf
PREFIX=armv6-rpi-linux-gnueabihf-
SYSROOT=/opt/raspberry/chroots/rpi-stretch-armhf

CXX=$(TOOLCHAIN)/bin/$(PREFIX)g++

CFLAGS += --sysroot=$(SYSROOT) -std=gnu++11
 
 
 
 
Upload to the Pi with "scp" and run, the LEDs flash!
 
openplc_pi.png
 
Setting up a cross toolchain and how CANOpen works would go beyond the scope of the tutorial. I will add a few links to this.
   
 
I will add a few more goodies over time, have fun
   
 
Filou
Reply 2 0
AndBat
Hello. I find this thread only now. It is very interesting. @thiagoralves, is there any plan to implement the cross compiling in the new IDE?
Reply 0 0
thiagoralves
There will be a more tight integration between the runtime and the ide on the new version, but cross compiling won’t come any time soon. OpenPLC runtime (the Linux version) supports a plethora of different hardware platforms. Cross compiling for raspberry pi is not hard, but cross compiling for all platforms that currently run today is a huge task, not to mention it would enlarge the size of the IDE significantly with all those toolchains onboard. Therefore I would rather have the runtime compile its own software so that each board takes care of its own toolchain, and the IDE keeps itself agnostic to it.
Reply 0 0
AndBat
Thanks @thiagoralves for your answer. I understand. And what about cross compiling only for docker version? Does it require the same effort?
Reply 0 0
thiagoralves
Thanks @thiagoralves for your answer. I understand. And what about cross compiling only for docker version? Does it require the same effort?
Yes. Docker is a virtualization platform, not an emulator. It will still be required to run binaries compatible with the host platform. So docker on arm will have a different compilation than docker on riscV for example
Reply 0 0
filou
Hello,
As thiagoralves already mentioned, including all possible platforms would go beyond the scope of OpenPLC. The generic platform approach transfers responsibility for the toolchain to the user. The fact that, in addition to Linux, Mac, and Windows, there is also the option to enable compilation via a Makefile, is a legacy of beremiz, on which the OpenPLC Editor 3 is based. It is not an OpenPLC standard.
 
Arduino-cli also uses cross-compiling technology, so there is alternate way to use new target systems for OpenPLC, you have to integrate them into the Arduino ecosystem. I described how this works in "Add a new Arduino platform." This should also be possible in the new Editor 4. However, the effort required to create a completely new platform for Arduino, is significantly greater than a generic Makefile project in Editor 3. (https://www.instructables.com/Arduino-IDE-Creating-Custom-Boards/ )
 
A completely different approach would be to write a "pseudo runtime" that accepts the code for the target system in the form of an ST file and cross-compiles it, like the Linux runtime does. The runtime then, also serves as a proxy for debugging, etc. This allows the editor to be used for new projects and targets without having to modify it. Simply put, are two independent tools, that communicate with each other via a network socket. I'll think about this and do some tests. Keyword: "Runtime Gateway."
 
The easiest way to test this, is to modify the compile_program.sh script accordingly ! If the compilation works, the web interface still needs to be adapted to transfer the data to the target system and start it.
Reply 0 0
AndBat
Hello @filou,
This sounds amazing.
I'd like to help you, but unfortunately all of this is far from my competence and knowledge.
But, what about running the "Runtime gateway" inside a container?
By using Qemu is possible to run multiarch containers and this could be helpful to compile .st file for different platforms.
Moreover, docker/podman can run linux containers both in windows and macos.
What do you think about?
Reply 0 0
filou
Hello,
 
First of all, a note about Docker and the like. This is a technique for bundling an application, including all its resources, into a single package and running it in an isolated environment. A lightweight alternative to a virtual machine. Unlike a virtual machine, however, this means that the host and Docker systems are equivalent to each other. Variants that also using the container principle, are chroot, flatpack and appimage. Qemu is an emulator like VMware and VirtualBox and can also run foreign operating systems, even those with completely different architectures, such as ARM. Before considering Docker, etc., you should consider the necessary requirements and the entire process behind OpenPLC.
 
Essentially, three independent parts are required. First, the editor, which creates an ST file regardless of the input method. Second, MATIEC (iec2c), which converts this into a C program along with some auxiliary files, and as the third and final step, a C compiler that generates the program for the target system. Depending on the target system, a small intermediate step and a HAL are required to adapt the various resources, such as IOs.
 
The last step is the most challenging. Is there a suitable compiler that meets at least the C99 standard? Can it be executed on the host platform running the OpenPLC Editor? And last but not least, is there suitable software or information for the hardware layer?
 
Once all of this is met, you can think about how to integrate it into a complete package, for example, a Docker image. Now to Qemu, which can be helpful if the compiler is only available for a very specific operating system or architecture. Depending on the case, full virtualization may be necessary, but simple userspace emulation is often sufficient. If all you need is an isolated environment with suitable libraries and tools, Docker is also a good choice.
 
To illustrate how this works and the associated problems, here's an example. The target platform is good old DOS, real-mode x86.
This doesn't work with the built-in tools on Windows 11, nor does it work on Linux. The first approach is a DOSBOX emulator and Borland C. The problem is that the C compiler doesn't understand some of the C constructs generated by MATIEC. An alternative from the retro scene, OpenWatcom, has the same problem. The GNU compiler is usually the best choice when it comes to standards compliance. After extensive research online, the ia16-gcc toolchain was chosen, which meets all the requirements. In many cases, however, there are no binary packages available, and the tools must be built from source. There are a few stumbling blocks. Often, the projects, and thus the source code, date back to a time when the target platform was still modern, so you have to use tools from that era for translation. For this, it's very useful to use older Debian versions on a virtual machine and, if possible, create static programs.
 
At the end, when all hurdles have been overcome and others are also supposed to participate in the hard work, it's time to put everything into a Docker image.
ST file in, binary runtime out!
Reply 0 0
Reply