Mastering File Management in Industrial Control with TwinCAT: A Comprehensive Guide

 


In the industrial control sector, process parameters, recipes, and other data are of paramount importance. TwinCAT3 offers various data storage methods to meet different scenarios and requirements.

Firstly, using Persistent, Retain variables, and Novram allows for the saving of small amounts of process data. These methods are designed for scenarios where there is an unexpected power loss. In such cases, the critical data or variable values that need to be recorded within the project are saved in the system's boot folder. However, these data can only be saved as current values, thus historical values cannot be viewed.

For the storage and management of large volumes of data, options include XML file storage and Database Server. Both can save not only current values but also all historical data, significantly enhancing data integrity. XML file storage refers to the TwinCAT XML Data Server. With this, data stored in XML files can be used to initialize TwinCAT PLC variables, or PLC variables can be stored in XML files. The structure of variables in the XML should match the structure of variables in the PLC. Sub-elements of variables can be directly read, which is quite convenient. The Database Server, on the other hand, uses third-party databases to interact with TwinCAT data for more extensive data management and integration. However, both methods require purchasing the corresponding licenses to use.

For scenarios with smaller data volumes, a low-cost approach is to use txt files for storage and management. TwinCAT3 provides function blocks for managing txt files, allowing operations like opening, closing, writing, reading, and renaming of both local and network neighborhood files. However, due to the limitations of txt file format and encoding, there are constraints on the format and size of data within TwinCAT.

Hardware and Software Versions

  • Controller Hardware:
    • Laptop (Example "TwinCAT File Test Project2" requires CX5130 controller, related modules, and motors)
  • Control Software:
    • TwinCAT 3.1 4024.35

Preparation

Folder Creation

Create a test folder and files on the computer. In this example, a folder named "Data" is created in D:\ to store the necessary data and files.



How to Use File Management Function Blocks

he effects of each file management function block must be combined with other function blocks to achieve results. Before calling these blocks, it's crucial to note whether the function requires the file to be in open or closed mode.

Writing Content to a (New) File

  • If we need to write Julia's score into a txt file, how can this be done?

    Here, we would use three function blocks: FB_FileOpen, FB_FilePuts, and FB_FileClose (to open, write to, and close the file respectively). These are included in the example file "TwinCAT WriteContent Project" (Project for Writing File Content).

    • Note: Before use, change the AmsNetId, and create the Data folder on the D drive; otherwise, the specified folder will not be found, leading to an error.

FB_FileOpen

  • FB_FileOpen is one of the most commonly used file management function blocks and a prerequisite for others. Often, when operating on files, they must first be opened. Here's how to connect and configure the pins for FB_FileOpen:






SNetId refers to AmsNetId. It can be found in System-Routes-NetId Management. If this pin is left unfilled, it defaults to the device currently controlled by the program, not the local machine.

SPathName represents the path to the target file. The file path for this test is: D:\testfile\testfile.txt.

NMode signifies the method of opening the file, with eight options in total. The commonly used modes are 1 and 2. Here are all the modes and their meanings:




he ePath pin can select the TwinCAT system path. Most modes for this pin are still under development. If you are not accessing the boot folder, you can directly choose PATH_GENERIC.



bExcute is the trigger pin. When using it, just set it to True to activate the block.

tTimeout is the timeout response time, defaulting to 5 seconds if not specified.

bBussy is a status bit, an output pin used to check if the function block is currently running. It will be FALSE once the operation is complete.

bError and nErrorld are error detection bits, also output pins. If bError is TRUE, it indicates an error in the function block operation, and nErrorld will provide an error code for reference.

The output pin HFile is a number representing the file handle, which is used in other function blocks that require the file to be opened first.

Note that the way function blocks open files is not like opening a window in Windows; they deal with memory data. If you try to delete the target file in Windows Explorer after only executing FB_OpenFile, you'll see a message saying "The operation cannot be completed because the file is open in TwinCAT3 System Service." When a txt file hasn't been created yet, choosing FOPEN_MODEAPPEND or FOPEN_MODEPLUS for the file opening mode allows for both reading and writing permissions upon opening. If the specified filename doesn't exist, it will be created.

Naturally, as there is an opening, there is also a closing. The function block used to close files is FB_FileClose. Its pins are almost identical to FB_FileOpen, except the input pin hFile is different because it looks for the file by handle rather than by path. Here, HFile is the handle generated by FB_FileOpen. When using it, simply assign the handle from FB_FileOpen to FB_FileClose.

FB_FilePuts

Beyond opening and closing files, you'll often need to modify file content. In the example, FB_FilePuts is used for input. Before starting this block, remember two things: first, the file must be open; second, the open mode must support writing. Otherwise, you'll see an error code 1792 in nErrId. Writing with this block is initially done to memory, and it's only saved to disk after closing with FB_FileClose.

Note: Since we are testing with Notepad, the encoding format is ASCII, so we use String type data for writing and reading.

To know whose score this is, the example uses the CONCAT() function to concatenate "Julias score is" with " 90 $L" and writes them together. ($L is the newline character in TwinCAT.)

FB_FileOpen, FB_FileGets, and FB_FileClose are executed in sequence. To determine if the previous block has finished, check if the input pin bExecute is TRUE and the output pin bBussy is FALSE, then proceed to the next block. The trigger pin for the whole program is b_excute.


Reading File Content

How do you know if writing to a file was successful?

We can use FB_FileOpen, FB_FileGets, and FB_FileClose to retrieve the contents of the file.

To avoid overwriting files or encountering gibberish, the example "TwinCAT ReadContent Project" uses the file opening mode FOPEN_MODEREAD (read-only). We set a STRING variable s_content to extract the data from the function block.

Note: Before using this routine, change the corresponding AmsNetId, and run "TwinCAT WriteContent Project" first to have content to read. If the corresponding file path or name isn't found, an error will occur.

FB_FileGets

The function block for reading strings is FB_FileGets. Input pins won't be detailed here as they've been discussed above. The output pin bEOF is a detection bit: it's True when you've reached the end of the file and no more bytes can be read; otherwise, it's False if bytes are still readable. You still need to open the file before reading, or you'll see error code 1795 in nErrId.

After loading the program, FB_FileOpen, FB_FileGets, and FB_FileClose are executed sequentially using CASE statements and logical checks. The whole program's trigger pin is b_excute.

Appending File Content

It's not feasible to upload all scores at once, especially with the size limitations of STRING data type. How do we append a new student's score?

This requires FB_FileOpen, FB_FileWrite, and FB_FileClose. In the example "TwinCAT AddContent Project", we still use FOPEN_MODEAPPEND or FOPEN_MODEPLUS for opening the file. (Be mindful of the format and size limits of STRING data when testing.)

To demonstrate adding content, it's best to run "TwinCAT WriteContent Project" first and modify the AmsNetId.

FB_FileWrite

With this function block, you can append new content to the end of the file. Pay attention to two pins: pWriteBuff for the address of the content to write and cbWriteLen for the size in bytes of the content. Use the ADR and SIZEOF functions to set these. Appending still requires the file to be open and writable, or you'll see error code 1792 in nErrId.

ADR() function explanation:

[Link to Beckhoff documentation]

SIZEOF() function explanation:

[Link to Beckhoff documentation]

After loading the program, FB_FileOpen, FB_FileWrite, and FB_FileClose are executed in sequence using CASE statements and logical checks. The whole program's trigger pin is b_excute.

Note: By default, the string byte size for the write block is 81; for consistency, it's recommended to add a newline character ($L) after the appended content. Otherwise, any space before 81 bytes without content might be replaced with spaces.

Copying Source Files

New Function Block: FB_FileCopy

To prevent file loss, backing up files is common. The simplest backup method is to copy the file. How can we do this?

Using FB_FileOpen, FB_FileRead, FB_FileWrite, and FB_FileClose, we can create a new function block FB_FileCopy in the example "TwinCAT CopyFile Project".

Note: Before use, ensure the source file exists and change the AmsNetId and file paths, or you'll get an error.

FB_FileRead

Another function block for reading file content is FB_FileRead. It's different from FB_FileGets as it reads via pointers (more flexible and powerful). You need to open the file beforehand. When setting the pins, pay attention to pReadBuff and cbReadLen, which are similar to the input pins pWriteBuff and cbWriteLen from FB_FileWrite. Use ADR and SIZEOF to fill these in.

The internal structure of this function block involves five steps:

  1. Parameter initialization
  2. Opening both source and destination files
  3. Reading source file content
  4. Writing content to the destination file
  5. Resetting

Once completed, you can call it in the main program, just fill in the AmsNetId for the source and destination systems, and corresponding file paths and names. After loading, set bExcute to True, and a new file will appear below the original with identical content.

Other File and Folder Operations

Often, with an accumulation of files, you might encounter "duplicate file name" issues. What to do then?

The first solution is to delete the old file directly, calling FB_FileDelete.

FB_FileDelete

The function block for deleting files is FB_FileDelete. Its pins are almost the same as FB_FileOpen, except there's no nMode. Remember to close the file before deleting, not just in Windows but using FB_FileClose, or you'll see error code 1804 in nErrId. The second solution is to rename the file, calling FB_FileRename.

FB_FileRename

The function block for renaming files is FB_FileRename. Just fill in the pins to use it. sOldName is the old name, and sNewName is the new name. The file must be closed before renaming, or you'll get error code 1804 in nErrId.

In projects, data types vary, and for organization, you might need to create different folders. Use FB_CreateDir to create and FB_RemoveDir to delete folders.

FB_CreateDir

To create a new folder, use FB_CreateDir. After declaring and calling, just fill in the folder name sPathName and path type ePath, then activate to create a new folder in the specified directory.

FB_RemoveDir

The function block for deleting a folder is FB_RemoveDir. The usage is similar to FB_CreateDir. If the folder doesn't exist, you'll see error code 1804 in nErrId.

All these examples are in the "TwinCAT OtherFunction Project". These function blocks are simple to use, no need for additional blocks; just set their trigger pins to TRUE.

File Management Function Blocks in Power Loss Scenarios

Power loss retention is very practical in industrial production, with Beckhoff offering Persistent and Retain variables. However, after power loss, the data can only be viewed in TwinCAT upon rebooting. How to access this data externally?

With file management function blocks, you can extract this data. The example "TwinCAT Write UPS Data Project" uses axis motion control and includes four parts:

  1. Motion control program (enable, motion function block)
  2. Power loss detection program (CX5130 UPS command)
  3. File management program (open, write, close blocks) and data conversion program.

Note: Before use, change the relevant hardware settings, or the program won't run. Also, the UPS commands in this example are only for the CX51 series controllers; adjust according to your controller during debugging.

When loading the program, you can first debug the axis motion. As the axis moves, its actual position is converted into a WSTRING variable (WSTRING for displaying Chinese), concatenated with "Axis actual position". Since txt files are in UTF-8 format, convert the Chinese content using WSTRING_TO_UTF8(). During axis movement, power off the CX5130 controller. FB_S_UPS_CX51x0 detects the power loss, sets b_excute to true, and through logical statements, executes the open, write, and close file operations in sequence.

WSTRING_TO_UTF8()

https://infosys.beckhoff.com/content/1033/tcplclib_tc2_utilities/3483049227.html?id=1615333347779599462


Error code and cause



How to Manage Files on Computers in a Network Neighborhood

The file management function blocks can not only manage files on the local computer but also those on computers in the network neighborhood through TwinCAT. Before this, you must ensure that the network neighborhood computer is on the same local area network (LAN) as your machine, and you need to know the username and password of the network neighborhood computer. Just like with controllers, the first step in the operation is to perform a broadcast search in the system. Since this is over a LAN, you need to check the wireless network option:



After the device is found during the search, you can:




Once connected, since TwinCAT's default AmsNetId is set to the currently controlled system, there's no need for changes. The rest of the operational steps are the same as for local file management, so we won't go into further detail here. This setup allows you to manage files on computers in the network neighborhood effectively.

Conclusion

In summary, file management function blocks are extremely practical in industrial control settings. If the data parameters you need to record aren't overly complex, these blocks offer a cost-effective solution for users. Different function blocks work together to meet various file management requirements. If you're interested, you can manually debug the program to tailor it to your specific needs.