This documentation is out of date.

The new version of the documentation is here: https://cannylogic.com/docs

Difference between revisions of "CFD Language"

From CANNY Wiki
Jump to: navigation, search
[unchecked revision][unchecked revision]
(Created page with "В интегрированной среде разработки CannyLab, для программирования ПЛК CANNY7 используется язык прогр...")
 
(Initial edit)
 
(29 intermediate revisions by 4 users not shown)
Line 1: Line 1:
В интегрированной среде разработки CannyLab, для программирования ПЛК CANNY7 используется язык программирования Canny Function Diagram (CFD). При его разработке, была поставлена цель создать инструмент, максимально отвечающий возможностям контроллера и в то же время достаточно близкий к отраслевому стандарту. Язык диаграмм функциональных блоков Function Block Diagram (FBD), взятый за основу при разработке CFD, является, пожалуй, одним из самых сбалансированных среди пяти языков программирования, одобренных международной электротехнической комиссией для создания пользовательских программ ПЛК в рамках стандарта МЭК 61131-3.  
+
Canny Function Diagram (CFD) is the programming language used to program the Canny 7 controller within CannyLab IDE. During the development of the language, the goal was to create a tool which best suits the capabilities of the controller, while at the same time maintaining industry standard. Function Block Diagram (FBD) Language was used as the basis for the development of CFD. It’s fair to say that FBD is a contender for the most well-balanced among the five languages approved by the International Electrotechnical Commission for the purposes of creating user programs for PLC within the IEC 61131-3 standard.
  
Являясь графическим языком программирования, CFD отличается высокой наглядностью, сопоставимой с наглядностью принципиальных схем, но находится на более высоком уровне абстракции, позволяющем скрыть несущественные детали реализации.
+
As a graphical programming language, CFD has a high visual clarity comparable to wiring diagrams, but is at a higher level of abstraction, which lets largely irrelevant algorithm implementation details remain hidden.
  
=== Функциональная диаграмма ===
+
=== Function Diagram ===
  
Программа на языке CFD, представляющая собой чертеж (схему), на котором изображены функциональные блоки, связывающие их друг с другом соединительные линии (сети) и вспомогательные элементы, называется функциональной диаграммой.
+
A program in the CFD language is called a function diagram. It’s a draft (scheme) containing the function blocks, the connection lines (networks) linking those function blocks to each other, and miscellaneous supporting elements.
  
Процесс выполнения программы на языке CFD можно описать как последовательное, обычно слева на право, вычисление каждого функционального блока диаграммы, с передачей результата к следующему связанному с ним функциональному блоку. Такую организацию вычислений будем называть потоком выполнения.
+
The algorithm of executing a program in the CFD language can be best described as successive (usually from the left to the right) calculation of each function block’s values, with the result transferring to the next connected function block for further calculations. We will refer to such an algorithm as a thread of execution.
  
[[Изображение:3_1_1.png|900px]]
+
[[File:3_1_1.png]]
  
Представление программы подобным образом, позволяет легко проследить процесс ее выполнения, просто рассматривая изображение, переходя взглядом от блока к блоку по соединительным линиям.
+
Presenting the program this way makes it easy to trace the thread of execution, just by looking at the picture and following connection lines from block to block.
  
В языке CFD, взаимное расположение блоков на ациклической диаграмме не влияет на порядок их выполнения. Порядок выполнения функциональных блоков такой диаграммы вычисляется автоматически по следующему правилу: каждый функциональный блок выполняется тогда, когда вычислены все его входы.
+
In the CFD language, the relative position of blocks in an acyclic diagram, which in this context means a diagram without a feedback loop, does not affect their execution order. Function block order of execution of such a diagram is automatically determined by the following rule: each function block is executed when all of its inputs are calculated.
  
При определении порядка выполнения циклической, то есть имеющей обратные связи диаграммы, функциональные блоки участвующие в цикле обратной связи выполнятся в таком порядке, чтобы последним исполнился функциональный блок находящийся правее всех остальных участвующих в цикле блоков.
+
When determining the order of execution of a cyclic diagram, which in this context means a diagram with a feedback loop, function blocks involved in the feedback loop are executed in such order, that the rightmost function block is always the last one to be executed.  
  
[[Изображение:3_1_2.png|800px]]
+
[[File:3_1_2.png]]
  
 +
=== Function Block ===
  
=== Функциональный блок ===
+
The function block is a graphical element in the function diagram indicating a function, algorithm or mathematical expression. The function block produces calculation of its output data depending on the input data received from the outside. On the function block image, the inputs are positioned on the left and outputs on the right.
  
Функциональный блок является графическим элементом функциональной диаграммы, обозначающим функцию, алгоритм или математическое выражение, производящее вычисление своих выходных данных в зависимости от полученных извне входных данных. На изображении функционального блока, его входы располагают слева, а выходы справа.
+
[[File:3_2_1.png|900px]]
  
[[Изображение:3_2_1.png|800px]]
+
[[Built-in Function Blocks | Built-in Function Blocks of CFD-language]] includes both simple blocks that perform basic logic transformation on their input data – such as AND, OR, NOT – along side more complex function: triggers, generators, switches.
  
[[Справочник по встроенным функциональным блокам | Стандартная библиотека функциональных блоков языка CFD]] включает в себя как простейшие блоки, выполняющие элементарные логические преобразования над своими входными данными — элементы И, ИЛИ, НЕ, так и более сложные функции: триггеры, генераторы, коммутаторы.
+
A function block, depending on its type, may have several inputs and several outputs, use its own memory as well as access the controller operating system resources for computations. For example, a function block can read data from a timer and use it for calculating the output values.
  
Функциональный блок, в зависимости от его типа, может иметь несколько входов и несколько выходов, использовать для вычислений свою собственную память, а так же обращаться к ресурсам операционной системы контроллера, например к таймерам и использовать полученные данные в расчетах своих выходных значений.
+
[[File:3_2_2.png]]
  
[[Изображение:3_2_2.png|800px]]
+
In the CannyLab environment, valid sources of input data for a function block are: other function blocks whose output output is connected to the block’s input via connection lines (networks); numeric constants entered by the user or selected from the directory; data from controller service memory registers.
  
В среде CannyLab, источниками входных данных для функционального блока могут быть функциональные блоки, с чьими выходами он связан соединительными линиями (сетями), введенные пользователем или выбранные из справочника числовые константы либо данные регистров служебной памяти контроллера.
+
Any input or output of a function block can be inverted. In the case of an input inversion, the new value of input data is equivalent to the value that results from performing the operation "Logical NOT" on the real input data. In case of output inversion, the "Logical NOT" operation will be applied to the data before sending the calculation result of the function block to the next function block or supporting element.
  
Любой вход или выход функционального блока может быть инвертирован. В случае инверсии входа, в качестве входных данных в функциональный блок будет передано значение являющееся результатом операции «Логическое НЕ» над реальными входными данными. В случае инверсии выхода, перед передачей результата вычисления функционального блока «наружу», к нему будет применена операция «Логическое НЕ».
+
=== Network ===
  
=== Сеть ===
+
The line connecting a data source to one or more recipients of data on the function diagram, is called a network . In the CFD language, the data source is usually the output of a function block, a recipient is an input of another function block. In the CFD language any network can have only one data source.
  
Линия, соединяющая на функциональной диаграмме источник данных с одним или несколькими получателями данных, называется сетью. В языке CFD, источником данных обычно выступает выход какого-либо функционального блока, а получателем вход другого функционального блока. В языке CFD любая сеть может иметь только один источник данных.
+
In programming language terms, the network is a "variable", a place where specific data is stored. After a function block finishes its calculations, writes its output value into the network as the network value. The function blocks whose inputs are connected to this network read the data stored in the network and use it in their calculations as input values.
  
В терминах языков программирования, сеть является ''переменной'', местом хранения данных. Функциональный блок по окончанию вычислений, записывает в сеть своё выходное значение, а выполняющиеся следом за ним функциональные блоки, к чьим входам данная сеть подключена, считывают из этой сети хранящее в ней значение и используют его в своих вычислениях в качестве входных значений.
+
An unbroken connection line from one function block to another is a network segment. Network segments can have any number of branches(or none at all), the important part is the connection line being unbroken. This means that the networks described above consist of only one segment and can be referred to as anonymous networks.
Наряду с использованием анонимных сетей, в CannyLab, сетям можно назначать имена, которые будут отображаться на диаграмме. Логически единую сеть, для которой назначено имя, можно для удобства компоновки, разделять на несколько визуально не связанных между собой сегментов. Например, два сегмента «Давление в шинах, кПа» на приведенном ниже рисунке представляют одну и ту же сеть, и имеют одинаковое значение в каждый момент времени, хотя визуально не связаны.
+
  
[[Изображение:3_3_1.png|800px]]
+
Alongside anonymous networks, CannyLab has named networks, which are created by assigning a display name to an existing network on the diagram. Named networks are logically unified, meaning that it is possible to separate the network into several visually unrelated segments for easier composition. For example, the two segments of "Tyre pressure, kPa" (on the figure below) represent the same network, and have the same value at each point in time, despite not being visually connected.
  
 +
[[File:3_3_1.png]]
 +
=== Data ===
  
=== Данные ===
+
In the CFD language, all the data used is 16-bit non-negative integer numbers in the range of 0 to 65535. The result of an arithmetic operation is always a numeric value from the specified range, and logical operations results are "1" (true) and "0" (false).
  
В языке CFD, все использующиеся данные являются 16-битными целыми неотрицательными числами в диапазоне от 0 до 65535. Результатом арифметических операций будет числовое значение из указанного диапазона, а результаты логических операций представляются значениями «1» (истина) и «0» (ложь).
+
During function diagram execution, where necessary, data conversion from boolean to numeric data and vice versa is performed automatically using the following rules:
  
При выполнении функциональной диаграммы, там где это необходимо, преобразование данных от логического типа к числовым данным и обратно выполняется  автоматически по следующим правилам:
+
* When converting a number to a boolean value, zero is converted to a value of "false", any number other than zero is converted to "true".
  
* При преобразовании числа к логическому значению, ноль преобразуется в значение «ложь», любое число отличное от нуля – в значение «истина».
+
* In arithmetic operation, the logic values of "false" and "truth" are used as the numbers 0 and 1, respectively.
  
* В арифметических операциях логические значения «ложь» и «истина» представляются как числа 0 и 1 соответственно.
+
* Inversion at the input or output of any block, automatically converts data to a boolean.
  
* Инверсия на входе или выходе любого блока, автоматически преобразует его данные к логическому типу.
+
[[File:3_4_1.png]]
  
[[Изображение:3_4_1.png|800px]]
+
The results of arithmetic operations are taken modulo 65535. This means that if the operation result exceeds 65535, then 65536 is automatically deducted from the result, creating the final value. And if the result was less than 0, then 65536 is added to the result, creating the final value.
 
+
Результаты арифметических операций берутся по модулю 65535. Это означает, что если результат операции превысил 65535, то из него автоматически вычитается 65536. А если результат оказался меньше нуля, то к нему прибавляется 65535 и еще единица.
+
  
 
{|
 
{|
 
|-
 
|-
|Например:
+
|For example:
 
|65535 + 1 = 0
 
|65535 + 1 = 0
 
| 
 
| 
Line 80: Line 80:
 
|}
 
|}
  
=== Управление ресурсами контроллера ===
+
=== Controller Resources Management ===
 
+
Для того, чтобы разработанная пользователем функциональная диаграмма могла использовать данные физических входов контроллера и изменять состояние его физических выходов, получать и передавать данные по интерфейсам передачи данных, или хотя бы просто изменять состояние встроенного светодиода контроллера, диаграмму и ресурсы контроллера необходимо связать между собой.
+
  
В контроллере CANNY7 доступ к аппаратным ресурсам из пользовательского приложения, реализован в форме чтения и записи данных по определенным адресам (регистрам) отображающим состояние этих ресурсов.
+
In order for the function diagram to use the controller's physical input data, change the status of the physical outputs, receive and transmit data on the data interfaces or even simply change the status of the built-in LED, the diagram and controller resources have to be linked to each other. In other words, they need to communicate somehow.
  
Ресурсы контроллера требуют определенного порядка доступа. Например, в самом простом случае, чтобы включить встроенный светодиод контроллера, достаточно передать по определенному адресу «1», а чтобы выключить «0». Но уже для того, чтобы использовать универсальный внешний канал контроллера для управления реле, его необходимо предварительно его инициализировать, записав значение требуемого режима его работы в адрес его конфигурации. Лишь после этого появляется возможность, устанавливая «1», или «0» в адрес выходного значения канала, управлять электрическим потенциалом данного канала контроллера.
+
In the CANNY7 controller, the access to hardware resources from the user application is implemented in the form of data reads and writes from/to specific registers (addresses) reflecting the status of these resources.
  
Так будет выглядеть приведенная ранее диаграмма управления светофором железнодорожного переезда, после привязки к ресурсам контроллера. Такая диаграмма уже полностью пригодна для записи в ПЛК и управления реальным оборудованием.
+
Controller resources require a specific order of access. For example, in the simplest possible case, to turn on the embedded controller LED it is enough to send "1" to a particular register and "0" to turn it off. But in order to use, say, a universal external channel for relay control, it must first be initialized, by writing its specific operating mode value into the relevant configuration register. Only then it is possible to control the electric potential on the channel by sending a "1" or "0" to the channel’s output value register.
  
[[Изображение:3_5_1.png]]
+
As an example, the diagram below is used to control railway crossing traffic lights. Notice the three controller resource bindings in the top of the diagram. This diagram is perfectly suitable for uploading into the PLC and controlling actual hardware.
  
Список адресов всех доступных пользователю ресурсов контроллера находится в справочнике адресов CannyLab, который доступен пользователю через контекстное меню при назначении входов и выходов типа «Адрес» функциональных блоков.
+
[[File:3_5_1.png]]
  
Конфигурация определенных ресурсов контроллера требует использования специальных констант, все они поименованы и собраны в списке констант CannyLab, который доступен пользователю при назначении входов типа «Константа» функциональных блоков.
+
The list of registers of all the resources available to the user of the controller is in the CannyLab controller register directory, which is available to the user via the context menu when assigning registers as inputs and outputs in CannyLab.
  
Подробное описание ресурсов CANNY 7 и порядка доступа к ним, рассматривается в [[CANNY 7|справочном руководстве по контроллеру]].
+
The configuration of certain controller resources requires the use of special named constants that can be found in the CannyLab named constant list, which is available to the user during when assigning a constant as an input.
 +
For more information on the UI and how to access these lists, read [[CANNY Lab Functional Diagram Editor]].
 +
Detailed description CANNY 7 resources and the access procedure to them, is described in [[CANNY 7| CANNY 7 Reference Manual]].

Latest revision as of 15:21, 11 December 2020

Canny Function Diagram (CFD) is the programming language used to program the Canny 7 controller within CannyLab IDE. During the development of the language, the goal was to create a tool which best suits the capabilities of the controller, while at the same time maintaining industry standard. Function Block Diagram (FBD) Language was used as the basis for the development of CFD. It’s fair to say that FBD is a contender for the most well-balanced among the five languages approved by the International Electrotechnical Commission for the purposes of creating user programs for PLC within the IEC 61131-3 standard.

As a graphical programming language, CFD has a high visual clarity comparable to wiring diagrams, but is at a higher level of abstraction, which lets largely irrelevant algorithm implementation details remain hidden.

Function Diagram

A program in the CFD language is called a function diagram. It’s a draft (scheme) containing the function blocks, the connection lines (networks) linking those function blocks to each other, and miscellaneous supporting elements.

The algorithm of executing a program in the CFD language can be best described as successive (usually from the left to the right) calculation of each function block’s values, with the result transferring to the next connected function block for further calculations. We will refer to such an algorithm as a thread of execution.

3 1 1.png

Presenting the program this way makes it easy to trace the thread of execution, just by looking at the picture and following connection lines from block to block.

In the CFD language, the relative position of blocks in an acyclic diagram, which in this context means a diagram without a feedback loop, does not affect their execution order. Function block order of execution of such a diagram is automatically determined by the following rule: each function block is executed when all of its inputs are calculated.

When determining the order of execution of a cyclic diagram, which in this context means a diagram with a feedback loop, function blocks involved in the feedback loop are executed in such order, that the rightmost function block is always the last one to be executed.

3 1 2.png

Function Block

The function block is a graphical element in the function diagram indicating a function, algorithm or mathematical expression. The function block produces calculation of its output data depending on the input data received from the outside. On the function block image, the inputs are positioned on the left and outputs on the right.

3 2 1.png

Built-in Function Blocks of CFD-language includes both simple blocks that perform basic logic transformation on their input data – such as AND, OR, NOT – along side more complex function: triggers, generators, switches.

A function block, depending on its type, may have several inputs and several outputs, use its own memory as well as access the controller operating system resources for computations. For example, a function block can read data from a timer and use it for calculating the output values.

3 2 2.png

In the CannyLab environment, valid sources of input data for a function block are: other function blocks whose output output is connected to the block’s input via connection lines (networks); numeric constants entered by the user or selected from the directory; data from controller service memory registers.

Any input or output of a function block can be inverted. In the case of an input inversion, the new value of input data is equivalent to the value that results from performing the operation "Logical NOT" on the real input data. In case of output inversion, the "Logical NOT" operation will be applied to the data before sending the calculation result of the function block to the next function block or supporting element.

Network

The line connecting a data source to one or more recipients of data on the function diagram, is called a network . In the CFD language, the data source is usually the output of a function block, a recipient is an input of another function block. In the CFD language any network can have only one data source.

In programming language terms, the network is a "variable", a place where specific data is stored. After a function block finishes its calculations, writes its output value into the network as the network value. The function blocks whose inputs are connected to this network read the data stored in the network and use it in their calculations as input values.

An unbroken connection line from one function block to another is a network segment. Network segments can have any number of branches(or none at all), the important part is the connection line being unbroken. This means that the networks described above consist of only one segment and can be referred to as anonymous networks.

Alongside anonymous networks, CannyLab has named networks, which are created by assigning a display name to an existing network on the diagram. Named networks are logically unified, meaning that it is possible to separate the network into several visually unrelated segments for easier composition. For example, the two segments of "Tyre pressure, kPa" (on the figure below) represent the same network, and have the same value at each point in time, despite not being visually connected.

3 3 1.png

Data

In the CFD language, all the data used is 16-bit non-negative integer numbers in the range of 0 to 65535. The result of an arithmetic operation is always a numeric value from the specified range, and logical operations results are "1" (true) and "0" (false).

During function diagram execution, where necessary, data conversion from boolean to numeric data and vice versa is performed automatically using the following rules:

  • When converting a number to a boolean value, zero is converted to a value of "false", any number other than zero is converted to "true".
  • In arithmetic operation, the logic values of "false" and "truth" are used as the numbers 0 and 1, respectively.
  • Inversion at the input or output of any block, automatically converts data to a boolean.

3 4 1.png

The results of arithmetic operations are taken modulo 65535. This means that if the operation result exceeds 65535, then 65536 is automatically deducted from the result, creating the final value. And if the result was less than 0, then 65536 is added to the result, creating the final value.

For example: 65535 + 1 = 0   1 – 2 = 65535
65535 + 2 = 1   1 – 3 = 65534
65500 + 122 = 86   117 – 259 = 65294

Controller Resources Management

In order for the function diagram to use the controller's physical input data, change the status of the physical outputs, receive and transmit data on the data interfaces or even simply change the status of the built-in LED, the diagram and controller resources have to be linked to each other. In other words, they need to communicate somehow.

In the CANNY7 controller, the access to hardware resources from the user application is implemented in the form of data reads and writes from/to specific registers (addresses) reflecting the status of these resources.

Controller resources require a specific order of access. For example, in the simplest possible case, to turn on the embedded controller LED it is enough to send "1" to a particular register and "0" to turn it off. But in order to use, say, a universal external channel for relay control, it must first be initialized, by writing its specific operating mode value into the relevant configuration register. Only then it is possible to control the electric potential on the channel by sending a "1" or "0" to the channel’s output value register.

As an example, the diagram below is used to control railway crossing traffic lights. Notice the three controller resource bindings in the top of the diagram. This diagram is perfectly suitable for uploading into the PLC and controlling actual hardware.

3 5 1.png

The list of registers of all the resources available to the user of the controller is in the CannyLab controller register directory, which is available to the user via the context menu when assigning registers as inputs and outputs in CannyLab.

The configuration of certain controller resources requires the use of special named constants that can be found in the CannyLab named constant list, which is available to the user during when assigning a constant as an input. For more information on the UI and how to access these lists, read CANNY Lab Functional Diagram Editor. Detailed description CANNY 7 resources and the access procedure to them, is described in CANNY 7 Reference Manual.