HMS NETWORKS CANbridge NT Lua ADK Bridge Router User Guide

September 11, 2024
HMS NETWORKS

CANbridge NT Lua ADK Bridge Router

“`html

Product Information

Specifications

  • Product Name: CAN@net NT/CANbridge NT Lua ADK
  • Version: 4.02.0332.20002 Version 1.5
  • Publication Date: 2023-11-27
  • Based on: Lua 5.3.5 distribution

Product Usage Instructions

Purpose of this Document

The CAN@net NT/CANbridge NT Lua ADK document provides
information on developing Lua applications for Ixxat CAN@net NT and
CANbridge NT.

Description of Ixxat Lua ADK

The Ixxat Lua ADK is based on the standard Lua 5.3.5
distribution, optimized for embedded system development and
execution. It provides a scripting framework for creating
applications with limited RAM and Flash memory resources.

Difference between Standard Lua and Ixxat Lua ADK

The Ixxat Lua ADK is non-preemptive and event-driven, requiring
tasks to be associated with events by registering callback
functions. Tasks are called sequentially upon event occurrence,
returning control upon completion.

Lua Library Functions Enabling the Registration of Lua

Callbacks

The ADK libraries act as C wrappers around registered Lua
callback functions, enabling them to be used as tasks in an
event-driven programming style.

Limitations of the Ixxat Lua ADK

The document outlines specific considerations and limitations
when coding for the Ixxat Lua ADK, ensuring efficient application
development.

Specifics in Coding for the Ixxat Lua ADK

Details on coding practices and guidelines to follow when
developing applications using the Ixxat Lua ADK are provided.

FAQ

Q: What version of Lua is supported by the Ixxat Lua ADK?

A: The Ixxat Lua ADK is based on the standard Lua 5.3.5
distribution.

Q: How are tasks associated with events in the Ixxat Lua

ADK?

A: Tasks are associated with events by registering callback
functions using the ADK API.

“`

ENGLISH
CAN@net NT/CANbridge NT Lua ADK SOFTWARE DESIGN GUIDE
4.02.0332.20002 Version 1.5
Publicaon date 2023-11-27

Important User Inormaon
Disclaimer The inormaon in this document is for inormaonal purposes only. Please inform HMS Networks of any inaccuracies or omissions found in this document. HMS Networks disclaims any responsibility or liability for any errors that may appear in this document.
HMS Networks reserves the right to modify its products in line with its policy of connuous product development. The inormaon in this document shall therefore not be construed as a commitment on the part of HMS Networks and is subject to change without noce. HMS Networks makes no commitment to update or keep current the inormaon in this document.
The data, examples and illusraons found in this document are included for illusrave purposes and are only intended to help improve understanding of the unconaliy and handling of the product. In view of the wide range of possible applicaons of the product, and because of the many variables and requirements associated with any parcular implemenaon, HMS Networks cannot assume responsibility or liability for actual use based on the data, examples or illusraons included in this document nor for any damages incurred during insallaon of the product. Those responsible for the use of the product must acquire sucien knowledge in order to ensure that the product is used correctly in their specic applicaon and that the applicaon meets all performance and safety requirements including any applicable laws, regulaons, codes and standards. Further, HMS Networks will under no circumstances assume liability or responsibility for any problems that may arise as a result from the use of undocumented features or unconal side eecs found outside the documented scope of the product. The eecs caused by any direct or indirect use of such aspects of the product are undened and may include e.g. compabiliy issues and stability issues.
Copyright © 2021 HMS Networks
Contact Inormaon Postal address: Box 4126 300 04 Halmstad, Sweden
E-Mail: info@hms.se

CAN@net NT/CANbridge NT Lua ADK
Table of Contents
1. Purpose of this Document ………………………………………………………………………………………….. 1 2. Descripon of Ixxat Lua ADK ……………………………………………………………………………………….. 2
2.1. Dierence between Standard Lua and Ixxat Lua ADK ……………………………………………………… 2 2.2. Lua Library Funcons Enabling the Regisraon of Lua Callbacks ……………………………………….. 2 2.3. Limiaons of the Ixxat Lua ADK ……………………………………………………………………………… 3 2.4. Specics in Coding for the Ixxat Lua ADK ……………………………………………………………………. 3
2.4.1. Bit Model 32 Bit Version ………………………………………………………………………………… 3 2.4.2. Errors and Debugging …………………………………………………………………………………… 3 2.4.3. Declaring Variables ………………………………………………………………………………………. 3 2.4.4. Passing Context between Lua Event Tasks ……………………………………………………………. 4 3. Using Lua ADK with the CAN NT Devices …………………………………………………………………………. 5 3.1. How to Enable the Use of the Lua ADK? …………………………………………………………………….. 5 3.2. How to Use Lua in Target Mode? …………………………………………………………………………….. 5 3.3. How to Use Lua in Remote Mode? …………………………………………………………………………… 6 3.4. How to Debug the Lua File? …………………………………………………………………………………… 7 4. Creang Lua Scripts ………………………………………………………………………………………………….. 8 4.1. How does the Lua ADK Event System Work? ……………………………………………………………….. 8 4.2. Example Applicaons ………………………………………………………………………………………….. 8 5. Lua API Funcon and Module Reference …………………………………………………………………………. 9 5.1. Lua Callback Funcons Called from C ……………………………………………………………………….. 9 5.2. C Funcons Called from Lua …………………………………………………………………………………. 10 5.2.1. Module misc …………………………………………………………………………………………… 10 5.2.2. Module can …………………………………………………………………………………………….. 11 5.2.3. Module mqtt …………………………………………………………………………………………… 13 5.2.4. Module sys …………………………………………………………………………………………….. 13 5.2.5. Module cyc …………………………………………………………………………………………….. 15 5.2.6. Module json …………………………………………………………………………………………… 16 5.2.7. Module array …………………………………………………………………………………………. 16 6. Lua License ……………………………………………………………………………………………………………. 20
4.02.0332.20002 Version 1.5

This page is inenonally lef blank.

Purpose of this Document

CAN@net NT/CANbridge NT Lua ADK

1. Purpose of this Document
The Lua ADK FAQ answers common quesons concerning the development of Lua applicaons for Ixxat CAN@net NT and CANbridge NT.
For inormaon how to program in Lua, refer to Lua resources on the internet:
· complete language specicaon in the Lua Reference Manual on lua.org · inormaon about availability and licensing issues in the lua.org FAQ · Q and A content and help for learning Lua as a second language in the unocial Lua FAQ · Lua Users Wiki provides examples source and relevant discussions, and inormaon to start Learning Lua · Programming in Lua by Roberto Ierusalimschy, one of the creators of Lua, is a detailed inroducon to Lua
programming. The online version is the rs edion and aims at. Lua 5.0. The third edion for Lua 5.3 is available for purchase.
This FAQ is derived from the FAQ of the NodeMCU 3.0.0 framework, published under the license MIT© zeroday)/ nodemcu.com. This original FAQ was started by Terry Ellison as an unofcial FAQ in mid 2015. This version in October 2019 includes some signican rewrites.

4.02.0332.20002 Version 1.5

Page 1 of 20

CAN@net NT/CANbridge NT Lua ADK

Descripon of Ixxat Lua ADK

2. Descripon of Ixxat Lua ADK

The Ixxat Lua ADK is based on the standard Lua 5.3.5 disribuon, a fully featured implemenaon of Lua 5.3. The implemenaon is opmized for embedded system development and execuon to provide a scripng framework that can be used to deliver useful applicaons within the limited RAM and Flash memory resources of embedded processors.
· All standard Lua language constructs and data types are working.
· Main Lua standard libraries core (partly), coroutine, string, math, debug and table are implemented.
· File handling uncons like require, dofile, and loadfile are missing. To be able to load other Lua les, like json.lua and misc.lua, the sys library provides the dofile uncon that is similar to the original uncons.
2.1. Dierence between Standard Lua and Ixxat Lua ADK
Lua is primarily an extension language that makes no assumpons about a main program. Lua works embedded in a host applicaon to provide a powerful, lightweight scripng language for use within applicaons. The host applicaon can invoke uncons to execute a piece of Lua code, can write and read Lua variables, and can register C uncons to be called by Lua code. Through the use of C uncons, Lua can be augmented to cope with a wide range of dieren domains, thus creang customized programming languages that share a synaccal framework.
The Ixxat Lua ADK is a rmware extension and must be layered over the standard rmware. The hooks and features of Lua enable the Ixxat Lua ADK to be seamlessly integrated without losing any of the standard Lua language features. The rmware has replaced some standard Lua modules that do not align well with the rmware. For example, the standard io and os libraries do not work, but are partly replaced by the libraries can, mqtt, and sys. To write to the terminal window that is provided by the CAN-Gateway Conguraor the uncon print(string) is used by default.
The main impacts of the Ixxat Lua ADK are how applicaon programmers must approach the developing and structuring of their applicaons. The ADK is nonpreempve and event driven. Tasks can be associated with given events by using the ADK API to registering callback uncons to the corresponding events. Events are queued internally within the ADK, and then the associated tasks are called one at a me. Each task returns the control to the ADK when run to compleon (nished successfully).
The ADK libraries act as C wrappers around registered Lua callback uncons to enable these to be used as ADK tasks. Therefore an event-driven programming style must be used in wring Lua programs.
2.2. Lua Library Funcons Enabling the Regisraon of Lua Callbacks
The following library uncons dene or use callbacks:
· sys.call_after() in Lua module sys · can.register_msg() in Lua module can · mqtt.subscribe() in Lua module mqtt
For can the standard Lua callback uncon on_can is used and for mqtt the standard Lua callback uncon on_mqtt.
The libraries (can, sys, mqtt, etc.) use the ADK callback mechanism to bind Lua processing to individual events (for example a CAN message recepon). Developers should make full use of these events to keep Lua execuon sequences short.
For more inormaon see the module documenaon in Lua API Funcon and Module Reference, p. 9.

Page 2 of 20

4.02.0332.20002 Version 1.5

Limiaons of the Ixxat Lua ADK

CAN@net NT/CANbridge NT Lua ADK

2.3. Limiaons of the Ixxat Lua ADK
The Ixxat Lua ADK has hardware resource limiaons because code is loaded from the Flash le system into o-chip RAM and executed there. This RAM area is shared between Lua and other tasks on the target. The overall size is approximately 900 Kbyte. Therefore, Lua can use up to approximately 600 Kbyte RAM for code and data.
The total amount of memory in use by Lua (in Kbytes) can be determined and wrien to the terminal window of the CAN-Gateway Conguraor with the following command:
print(collectgarbage(“count”))
Keep in mind:
· Lua scripts need much more CPU me than compiled code wrien in C. · Do as less as possible compuaon in Lua. · Do the compuaon with the lowest possible frequency.
To reduce the eor for Lua:
· If possible use mapping tables and other features. · Use the max_frequency feature for registered can messages to reduce the on_can call frequency. · Use the array.repack uncon to reassemble CAN message payload.
The needed CPU power can be monitored via the output in the status bar of the CAN-Gateway Conguraor. The Lua uncon sys.get_us_time() allows to measure execuon mes more precisely.
A typical value for the execuon me of a short Lua uncon is 150 to 200 s. About 5000­8000 messages can be processed per second.
2.4. Specifcs in Coding for the Ixxat Lua ADK
2.4.1. Bit Model 32 Bit Version
The Ixxat Lua ADK is compiled for the 32 bit model. Therefore integer and oang points values are stored as 32 bit values instead of 64 bit values as with a standard desktop Lua insallaon.
2.4.2. Errors and Debugging
The Ixxat CAN@net/CANbridge NT runs the Lua ADK over the nave hardware. There is an underlying kernel system to capture errors and to provide graceful failure modes. To avoid aecng the standard rmware, error handling is kept simple. If an error occurs when calling a Lua uncon, an error message is wrien to the log le and Lua is stopped. Runme errors in Lua uncons are wrien to the terminal and Lua is stopped. The rest of the rmware is running without resricons. To reacvae the Lua script the system has to be restarted.
There is currently no target debugging support. The print statement diagnoscs through the terminal interface of the system must be used. The Ixxat Lua ADK provides a remote debugging feature to run the Lua script on the PC while communicang with the target device via an USB connecon.
2.4.3. Declaring Variables
Two types of data can be assigned to Lua variables:
· values such as numbers, booleans, and strings · references such as uncons, tables, and user data
For example, if the contents of variable a are assigned to variable b, there is a dierence between values and references. In case of a value, the content of a is copied into b. In case of a reference, both a and b now refer to the same object. No content is copied. The Ixxat Lua ADK provides the uncon table.copy() which returns a deep copy of the provided table parameters.

4.02.0332.20002 Version 1.5

Page 3 of 20

CAN@net NT/CANbridge NT Lua ADK

Specics in Coding for the Ixxat Lua ADK

In standard Lua all variables can be classied as globals or locals. By default, any variable that is referenced and not previously declared as local is global. Global variables persist in the global table unl the variable is explicitly deleted.
To see what global variables are in scope, use the following command:
for k,v in pairs(_G) do print(k,v) end
Local variables are lexically scoped. This means the scope of local variables is limited to the block where they are declared. A block is the body of a control structure, the body of a uncon or a chunk (the le or string with the code where the variable is declared). Any variable can be declared local within nested blocks or uncons without aecng the enclosing scope. Because locals are lexically scoped it is also possible to refer to local variables in an outer scope. These variables are sll accessible within the inner scope.
The Lua runme internally uses hashed key access to retrieve keyed data from a table. Locals are stored as a conguous vector and are accessed directly by an index, which is faster. Access to rmware based tables is parcularly slow.
Using locals as follows is both a lot faster at runme and generates less byte code insrucons for their access:
local can_send = can.send
2.4.4. Passing Context between Lua Event Tasks
A single Lua uncon is bound to any event callback task. The uncon is executed from within the relevant C code using a lua_call(). Each uncon can invoke other uncons and so on. But each uncon must ulmaely return the control to the C library code which then returns the control to the rmware.
Lua local variables that are dened inside a uncon only exist within the context of this execung Lua uncon. Therefore locals are unreferenced on exit and any local data and garbage might be collected between the lua_call() acons.
Context can be passed in two ways between event tasks:
· by global variables: any global variable persists unl it is explicitly dereferenced by assigning nil to the variable.
· by local variables: local variables that are dened in an outer scope (see descripon of locals in Declaring Variables, p. 3).

Page 4 of 20

4.02.0332.20002 Version 1.5

Using Lua ADK with the CAN NT Devices

CAN@net NT/CANbridge NT Lua ADK

3. Using Lua ADK with the CAN NT Devices
The use of the ADK is only possible in Bridge operaonal modes.
The Lua ADK supports two operaonal modes:
· running the Lua script on the target device in autonomous mode (target mode) · running the Lua script on the host PC for debugging purposes, communicang with the target device via USB
(remote mode)
Funconally there is no dierence between running the Lua script on the device or on the host PC. The operaonal mode can be set in the CAN-Gateway Conguraor (see How to Enable the Use of the Lua ADK?, p. 5).
Running scripts on the target device provides only limited debugging possibilies via print statements. Running scripts on the host PC allows debugging with breakpoints and watch windows. Running Lua on the host PC provides the possibility to run huge Lua les with low compuaon me due to performance of PC, but the USB communicaon introduces extra delays for each ineracon (e.g. CAN-Lua-CAN) of about one millisecond.
3.1. How to Enable the Use of the Lua ADK?
To be able to use the Lua ADK with the CAN NT device, the device must be updated with the Lua framework and Lua must be enabled in the CAN-Gateway Conguraor.
1. Connect the device to the host computer and to power supply (for more inormaon see User Manual of the device in use).
2. Make sure that the latest CAN-Gateway Conguraor is installed (check within the product support pages on www.ixxat.com/support-bridges-gateways).
3. Start the CAN-Gateway Conguraor and connect the device in use (for more inormaon see User Manual CAN-Gateway Conguraor).
4. In the toolbar open menu Lua ADK and select Update Lua ADK. 5. In C:Program FilesHMSIxxat CAN-Gateway Confguraor V6 open the le lua_framework_vx and update
the Lua ADK. · Lua ADK is loaded to the connected device. 6. In the conguraon tree select General and enable the ADK in the drop-down list Use of Lua as ADK. a. enabled in target mode: running the script on the target device (see How to Use Lua in Target Mode?,
p. 5) b. enabled in remote mode: running the script on the host PC, communicang with the device via USB
(see How to Use Lua in Remote Mode?, p. 6)
7. In CAN-Ethernet-CAN bridges note that the Lua ADK must be enabled for the Master and each Slave individually.
8. In the toolbar open menu Target and select Write confguraon to target to write the device conguraon to the connected CAN NT device.
3.2. How to Use Lua in Target Mode?
1. In the CAN-Gateway Conguraor enable the use of the Lua ADK in target mode (see How to Enable the Use of the Lua ADK?, p. 5).
2. In the toolbar open menu Target and select Write confguraon to target to write the device conguraon to the connected CAN NT device.

4.02.0332.20002 Version 1.5

Page 5 of 20

CAN@net NT/CANbridge NT Lua ADK

How to Use Lua in Remote Mode?

3. Create a Lua script. or Test the HelloWorld example, that is provided in C:UsersPublicDocumentsHMSIxxat CAN-Gateway ConfguraorExamplesLua.
4. Download the Lua script to the device with the CAN-Gateway Conguraor or with the command line tool CANGWle.exe. With CAN-Gateway Confguraor
a. In the toolbar open menu Lua ADK and select Write Lua script to target. b. It is possible to capture the print outputs of Lua with the terminal window.
· Lua script is wrien to the CAN NT device. · Lua script is auomacally started when the device is started.
With command line tool CANGWfle.exe
a. Make sure the CAN@net or CANbridge NT device is connected. b. To download and start the script in terminal mode use the following command:
CanGWfile.exe USB any w LUA myscript.lua -init -terminal The command executes the following: · downloads the script myscript.lua to the connected CAN NT device · restarts the device and acvaes the script · ushes old text strings from the output FIFO on the target · opens the terminal mode for text outputs
c. To terminate the tool press any key on the keyboard. · Lua script is auomacally started when the device is started.
NOTE For descripons of the command line parameters see User Manual CAN-Gateway Conguraor.

3.3. How to Use Lua in Remote Mode?
Running the Lua script on the host PC and using it in remote mode can be used for example for debugging. The recommend IDE is ZeroBrane Studio.
The Ixxat Lua ADK includes the command line tool LuaADK.exe. This is a Lua interpreter v5.3 including a USB driver for the communicaon with the CAN@net/CANbridge NT device. This tool has to be used instead of the Lua interpreter of the IDE.
To use the LuaADK.exe from ZeroBrane: 1. To open the user setngs le, open menu Edit — Preferences — Setngs: user. 2. Add the path to the LuaADK.exe (e.g. path.lua53 = ‘C:\Program Files\HMS\IXXAT
CAN-Gateway Configurator\LuaADK.exe’). 3. Open Project — Lua Interpreter and select Lua 5.3. 4. Restart ZeroBrane.
To communicate with the Target Device in Remote Mode
1. Make sure the CAN@net or CANbridge NT device is connected via USB. 2. Enable the use of the Lua ADK in remote mode (see How to Enable the Use of the Lua ADK?, p. 5). 3. In the CAN-Gateway Conguraor, open menu Target and select Write confguraon to target to write the
device conguraon to the connected CAN NT device. 4. Create a Lua script.

Page 6 of 20

4.02.0332.20002 Version 1.5

How to Debug the Lua File?

CAN@net NT/CANbridge NT Lua ADK

5. Note that the Lua script depends on the conguraon on the target. For example, MQTT broker setngs must be congured on the target to be able to use the callbacks in the Lua script.
6. Start the Lua script on the host PC. · LuaADK.exe reinializes the device (connect device, test connecon and load script).
7. Note that the target device only starts to operate, if the Lua script is started on the host PC. 8. Congure the target device from the Lua inialize uncon and start normal operaon. 9. If ZeroBrane stops at uncon initialize(), use Project — Connue to run the Lua script or Project —
Step over to single step the script line by line.
3.4. How to Debug the Lua File?
Lua is not able to detect set breakpoints, because uncons like loop, initialize, and on_can are called from the C environment.
· To be able to detect set breakpoints, add the following line to each uncon:

function loop(ticks, elapsed) require(‘mobdebug’).on()
— my code … end

— <== Add this line at the beginning of the function

If this line is added, breakpoints can be set and single step debugging is possible.

NOTE Remove the line when using the code in target mode.

4.02.0332.20002 Version 1.5

Page 7 of 20

CAN@net NT/CANbridge NT Lua ADK

Creang Lua Scripts

4. Creang Lua Scripts

4.1. How does the Lua ADK Event System Work?
Understanding how the system executes the code can help you to structure the code beer and to improve both
performance and memory usage.
· Ixxat Lua ADK uses the tree kinds of callback uncons initialize, on_… , and loop. ­ initialize is called once while the system is inializing. It is used to register further events and to set CAN message lers.
­ loop is called cyclically every 100 ms afer the inializaon phase, when the device is up and running. It is used to trigger cyclically recurring tasks.
­ on_can and on_mqtt uncons are used to handle events from CAN and MQTT.
· Keep the uncon execuon mes as short as praccal so that the overall system can work smoothly and responsively. The general recommendaon is to keep the callbacks under 5 ms in duraon. If exceeded inermien problems because of mailbox overruns of the Lua task might occur.
· The Lua libraries provide a set of uncons for declaring applicaon uncons (wrien in Lua) as callbacks to associate applicaon tasks with specic hardware and mer events. These are also non-preempve at an applicaons level. The Lua libraries work in consort with the ADK to queue pending events and invoke any registered Lua callback rounes, which then run to compleon uninterrupted. For example Luasys.call_after(time, callback, arg) calls a uncon in the sys library which registers a Lua uncon for this mer alarm. When this alarm is triggered, it will call the Lua callback.
· Lua uncons iniaed by mer or network events and other callbacks run non- preempvely to compleon before the next task can run. This includes all Lua ADK uncons.

Observe that you are using the wrong approach,
· if you are not using mers and other callbacks. · if you are using poll loops. · if you are execung more than a few hundred lines of Lua per callback.

4.2. Example Applicaons
Various example applicaons can be found afer insallaon of the CAN-Gateway Conguraor download package
in folder C:UsersPublicDocumentsHMSIxxat CAN-Gateway Confguraor\ExamplesLua.

Example applicaon Descripon

can_demo.lua

Shows how to handle (send and receive) CAN messages via Lua.

canfd_demo.lua coroune.lua
hello_world.lua

Shows how to handle (send and receive) CAN FD messages via Lua. Implements a task and delay uncon and show how more than one task can be executed simultaneously. Read and output ADK and device inormaon, addionally blink with the user LED.

iso15765.lua

Segmenaon of large CAN FD messages into classic CAN messages using the ISO 15765-2 transport protocol

mqt.lua

Shows how to subscribe and publish MQTT messages.

mqt_json.lua

Subscribes MQTT JSON messages and sends the messages on CAN and vice versa.

repack.lua

Repack the data bytes of a receive CAN messages from CAN1 and send on CAN2

Page 8 of 20

4.02.0332.20002 Version 1.5

Lua API Funcon and Module Reference

CAN@net NT/CANbridge NT Lua ADK

5. Lua API Funcon and Module Reference
5.1. Lua Callback Funcons Called from C
Funcon ‘initialize’
initialize()
Called once while the rmware is being inialized. It is used to register CAN and MQTT messages for recepon and to inialize variables.
Funcon ‘loop’
loop(ticks, elapsed)
Called cyclically every 100 ms afer the inializaon phase, when the device is up and running. It is used to trigger cyclically recurring tasks.
· ticks: counter value that is incremented with each call of loop · elapsed: me in ms since the last call of loop
Funcon ‘on_can’
on_can(topic, port, format, ident, data)
Called on each CAN message recepon, based on message regisraons via can.register_msg. · topic: user dened reference value used by can.register_msg
port: CAN port number (1 .. 4), depending on the available CAN ports of the target device · format: combinaon of three characters to specify the message format, e.g.:
­ “csr” means: “classic CAN”, “standard idener (11 bit)”, “remote frame” ­ “fed” means: “CAN-FD”, “extended idener (29 bit)”, “data frame” · ident: CAN message idener (0 .. 0x7FF for standard messages and 0 .. 0x1FFFFFFF for extended messages) · data: message data bytes provided as Lua table or as byte array (see module array)
Funcon ‘on_mqtt’
on_mqtt(handle, topic, payload, qos)
Called on each MQTT message recepon, based on message regisraons via mqtt.subscribe. · handle: user dened reference value used by mqtt.subscribe · topic: message topic as string · payload: message data as string · qos: quality of service (0, 1, 2)

4.02.0332.20002 Version 1.5

Page 9 of 20

CAN@net NT/CANbridge NT Lua ADK

C Funcons Called from Lua

Funcon ‘on_action’
on_action(param1, param2, param3)
The “CAN-Gateway Conguraor” allows the denion of acon rules with the acon ” Call Lua uncon ‘on_acon'”. If this acon is triggered, the uncon on_action is called. · param1, param2 and param3 are strings or numeric values, depending on the denion in the acon rule.
5.2. C Funcons Called from Lua
5.2.1. Module misc
Funcons from the module misc are loaded by default and are directly available.
Funcon ‘hex’
hex(val)
Converts the parameter val into a hexadecimal represenaon.
Funcon ‘dump’
dump(o, indent, nested, level)
Dumps values in a one-statement format. For example, {test = {“Tesng…”}} becomes:
{ test = { “Testing…” }
}
The uncon also supports tables as keys, but not circular references. · indent: species an indenaon string, it defaults to a tab. Use the empty string to disable indenaon. · nested: internal only. Do not provide any value. · level: internal only. Do not provide any value.
Funcon ‘string.split’
string.split(str, delim, include_empty, max_splits, sep_is_pattern)
Splits the string str into a list of substrings, breaking the original string on occurrences of the given separator delim (character, character set, or paern).
· include_empty: boolean, default: false, e.g. “a,,,b”:split(“,”) returns {“a”,””,””,b”} · max_splits: number, if negave, splits are not limited, default: -1 · sep_is_pattern: boolean, species whether the separator is a plain string or a paern (regex), default:
false, e.g. “a,b”:split(“,”) returns {“a”,”b”}

Page 10 of 20

4.02.0332.20002 Version 1.5

C Funcons Called from Lua

CAN@net NT/CANbridge NT Lua ADK

Funcon ‘table.copy’
table.copy(tbl)
Returns a deep copy of tbl.
5.2.2. Module can
The module can is loaded by default and can is directly available.
Funcon ‘can.dump_data’
can.dump_data(data)
Formats data as byte hex dump, like:
can.dump_data({1, 2, 3, 4}) –> [01, 02, 03, 04] Funcon ‘can.register_msg’
can.register_msg({ handle = 1, port = 1, format = “std”, ident = 0x100, data_as = “array”, max_frequency = 500,
})
Registers a CAN/CAN-FD message for recepon via on_can. · handle: user dened reference to the registered message, to be used inside on_can · port: CAN port number (1 .. 4), depending on the available CAN ports of the target device · format is std for 11-bit, or ext for 29-bit ideners · ident: message idener · data_as possible values:
­ “array”: received message payload (data bytes) is provided as byte array (userdata) ­ “table”: received message payload (data bytes) is provided as Lua table · max_frequency: value in msec for the “message load reducon ler” to reduce the CPU load. CAN messages is forwarded to Lua with the given maximum frequency. This parameter is oponal. Default value is 0 (no ler is used). Type “array” has beer performance and is therefore the preferred type. Type “table” is more generic and provides more possibilies to work with the received data.
Funcon ‘can.send’
can.send(port, format, ident, payload)
Sends a CAN message.

4.02.0332.20002 Version 1.5

Page 11 of 20

CAN@net NT/CANbridge NT Lua ADK

C Funcons Called from Lua

· port: CAN port number (1 .. 4), depending on the available CAN ports of the target device. · format: combinaon of three characters to specify the message format, e.g.:
­ “csr” means: “classic CAN”, “standard idener (11 bit)”, “remote frame” ­ “fed” means: “CAN-FD”, “extended idener (29 bit)”, “data frame” · ident: message idener · payload: data bytes of the message as array or table (see “can. register_msg”)
Funcon ‘can.stop’
can.stop(port)
Stop the CAN controller to prevent message recepon/ransmission on the port.
· port: CAN port number (1 .. 4), depending on the available CAN ports of the target device.
Funcon ‘can.start’
can.start(port)
Start the CAN controller again.
· port: CAN port number (1 .. 4), depending on the available CAN ports of the target device.
Funcon ‘can.init’
can.init(port, mode, baudA, baudD)
Inialize the CAN controller. The CAN controller must be stopped beforehand and restarted afer inializaon.
Example:
can.stop(1) can.init(1, “—“, 250, 0) can.start(1)
· port: CAN port number (1 .. 4), depending on the available CAN ports of the target device. · mode: combinaon of three characters to specify the CAN operaonal mode:
­ “aci” means: “acve”, “Classic CAN”, “ISO” (“—” is also valid as an alernave) ­ “lfn” means: “listen-only”, “CAN-FD”, “non ISO” (“non ISO” only with CAN-FD) · baudA: Classic CAN: Baud rate value in KBaud like 125, CAN FD: Baud rate value in KBaud for arbiraon phase · baudD: For CAN-FD: Baud rate in KBaud for data phsae. 0 for Classic CAN
Funcon ‘can.set_crossbar_switch’
can.set_crossbar_switch(rx_port, tx_port, turn_on)
Turns the device internal message stream on or o. Message streams are specied by the CAN ports (receive and transmit can port). The uni-direconal message ow between these ports can be turned on and o with the crossbar switch.

Page 12 of 20

4.02.0332.20002 Version 1.5

C Funcons Called from Lua

CAN@net NT/CANbridge NT Lua ADK

· rx_port: CAN port where the messages are received (1..4) · tx_port: CAN port where the messages shall be sent (1..4) · turn_on: possible values: true or false
5.2.3. Module mqtt
The module mqtt is loaded by default and directly available.
Funcon ‘mqtt.publish’
mqtt.publish(topic, payload, qos)
Publishes (sends) an MQTT message to an MQTT broker. The broker setngs have to be specied in the device conguraon (MQTT Broker Setngs).
· topic: message topic as string (maximum length is 256 characters) · payload: message data as string or array (maximum length is 1536 characters) · qos: quality of service (0, 1, 2)
TIP If Lua is enabled in “remote mode”, the maximum string length for topic and payload is 184 bytes each due to USB communicaon limiaons.
Funcon ‘mqtt.subscribe’
mqtt.subscribe(handle, topic, qos)
Sends a SUBSCRIBE message to the MQTT broker to be able to receive messages on topics of interest. · handle: user dened reference to the registered message, to be used inside on_mqtt · topic: message topic as string (maximum length is 256 characters) · qos: quality of service (0, 1, 2)
TIP If Lua is enabled in “remote mode”, the maximum string length for topic and payload is 184 bytes each due to USB communicaon limiaons.
5.2.4. Module sys
The module sys is loaded by default and directly available.
Funcon ‘device_info’ Reads and provides device related inormaon as Lua table. Here a code extract:

4.02.0332.20002 Version 1.5

Page 13 of 20

CAN@net NT/CANbridge NT Lua ADK

C Funcons Called from Lua

local info = device_info() print(info.hw_version) print(info.fw_version) print(info.fpga_version) print(info.security_lvl) print(info.config_name) print(info.config_type) print(info.device_type) print(info.serial_num) print(info.device_name) print(info.ip_address)

–> e.g.: “3.02.00” –> e.g.: “6.00.00” –> e.g.: “1.01.00” –> e.g.: 1 –> user provided configuration name –> e.g.: “Local Bridge” –> e.g.: “CAN@net NT 200” –> e.g.: “HW906509” –> user provided device name –> e.g.: “192.168.178.23”

Funcon ‘sys.get_ms_time’
sys.get_ms_time() Returns the system me (32 bit value) in milliseconds. Funcon ‘sys.get_us_time’
sys.get_us_time() Returns the system me (32 bit value) in microseconds. Funcon ‘sys.call_after’
sys.call_after(ticks, func, arg) Calls the Lua uncon func afer ticks system cks (resoluon is 1 ms). arg can be used as parameter for func and should be a numeric value.
IMPORTANT There are maximum 16 mers available, which can be used in parallel.

Example:

function foo(val) print(“delayed “..val)
end sys.call_after(100, foo, 123)
Funcon ‘sys.set_user_led’
sys.set_user_led(pattern, ticks)
Sets the User LED of the device.

Page 14 of 20

4.02.0332.20002 Version 1.5

C Funcons Called from Lua

CAN@net NT/CANbridge NT Lua ADK

· pattern possible values: ­ 1 – turn o (set ticks to 0) ­ 2 – set to red (set ticks to 0) ­ 3 – set to green (set ticks to 0) ­ 4 – set to orange (set ticks to 0) ­ 5 – ash red for ticks cks ­ 6 – ash green for ticks cks ­ 7 – ash orange for ticks cks ­ 8 – blink red (frequency in Hz is 50 / ticks) ­ 9 – blink green (frequency in Hz is 50 / ticks) ­ 10 – blink red/green (frequency in Hz is 50 / ticks) ­ 11 – blink orange (frequency in Hz is 50 / ticks) ­ 12 – blink red/orange (frequency in Hz is 50 / ticks) ­ 13 – blink green/orange (frequency in Hz is 50 / ticks)
· ticks: me in mulples of 10 milliseconds
Funcon ‘sys.logging’
sys.logging(severity, message)
Writes a test message into the LOG/ERR le, e. g. sys.logging(“E”, “my log message”).
· severity: possible values: e’X’epon, ‘E’rror, ‘W’arning or ‘L’ogging · message: text string
5.2.5. Module cyc
The cyc module allows stopping, updang and sarng the cyclic transmission of CAN messages. CAN messages to be sent cyclically can be congured with the “CAN-Gateway Conguraor”. These messages can then be controlled from Lua.
Funcon ‘cyc.stop_msg’
cyc.stop_msg(row)
Congured “cyclic messages” will be sent on secondary side as soon as the message on primary side is received once. To prevent the transmission of such a message, the uncon cyc.stop_msg can be used e. g. from within the Lua uncon initialize.
· row: The row number in the “CAN-Gateway Conguraor” grid (0 to 127)
Funcon ‘cyc.start_msg’
cyc.start_msg(row)
To enable the transmission of cyclic message again, the uncon cyc.start_msg is used.
TIP The transmission only begins when the rs message has been received on primary side or the cyc.update_msg uncon has been called.
· row: The row number in the “CAN-Gateway Conguraor” grid (0 to 127)

4.02.0332.20002 Version 1.5

Page 15 of 20

CAN@net NT/CANbridge NT Lua ADK

C Funcons Called from Lua

Funcon ‘cyc.update_msg’
cyc.update_msg(row, format, ident, payload)
The uncon cyc.update_msg is used to start the transmission of messages and/or to update the message idener or data for transmission.
· row: The row number in the “CAN-Gateway Conguraor” grid (0 to 127) · format: Combinaon of three characters to specify the message format, e. g.:
­ “csr” means: “classic CAN”, “standard idener (11 bit)”, “remote frame” ­ “fed” means: “CAN-FD”, “extended idener (29 bit), “data frame” · ident: message idener · payload: data bytes of the message as array or table (see Funcon ‘can.register_msg’, p. 11)
5.2.6. Module json
The module json is oponal and has to be loaded via json= sys.dofile(‘json.lua’).
Funcon ‘json.encode’
json.encode(val)
Serializes the provided value as JSON string. The result is returned. Allowed data types for value are boolean, number, string, and table.
Funcon ‘json.decode’
json.decode(st)
De-serializes the provided JSON string. The result is returned.
5.2.7. Module array
The module array is loaded by default and directly available.
Provides the data type array which is a userdata byte array with up to 64 bytes, used for CAN messages payload.
The module provides uncons to generate and modify byte arrays in C which is more ecien than doing this in Lua, like:
· extract data bytes from an array · insert data bytes into an array · repack data from one array into another
Funcon ‘array.new’
a = array.new(64, 0) — OR a = array.new({1, 2, 3, 4, 5 ,6 ,7 ,8})
Creates a new instance of type array. The rs parameter is used as size (number of bytes) , the second parameter as inializaon value for the array. A provided table is used as list of inializaon values.

Page 16 of 20

4.02.0332.20002 Version 1.5

C Funcons Called from Lua

CAN@net NT/CANbridge NT Lua ADK

NOTE Array/table indexes in Lua always start with 1 (instead of 0 as in many other languages).
Funcon ‘array.extract’
a = array.extract(a, first [, last]) Returns an extract of a that starts at first and connues unl last. If last is absent, then it is assumed to be equal to the array length.
Funcon ‘array.insert’
a = array.insert(a, [pos,] value) Inserts element value at posion pos in a, shifing up the elements a[pos] ···, a[#a]. The default value for pos is #a+1, so that a call array.insert(a, x) inserts x at the end of array a. Funcon ‘array.string_to_array’
a = array.string_to_array(“this is string”)
Converts a Lua string to a byte array. The length of the array corresponds to the number of string characters.
Funcon ‘array.array_to_string’
s = array.array_to_string(a)
Converts a byte array to a Lua string. Strings in Lua are not zero-terminated and can contain any arbitrary binary data.
Funcon ‘array.compile’
format = array.compile(s)
Generates a binary format string for array.repack() based on the given ASCII format string. array.repack() allows a re-packaging of data bytes from one array into another. The format string denes which bytes are used and how they are packed into the desnaon array.
Example:
— copy 4 bytes to the destination array in opposite order format = array.compile(“#4,#3,#2,#1”) dest_array = array.repack(format, src_array)
— this corresponds to dest_array[1] = src_array[4] dest_array[2] = src_array[3] dest_array[3] = src_array[2] dest_array[4] = src_array[1] The format allows constant values in addion:

4.02.0332.20002 Version 1.5

Page 17 of 20

CAN@net NT/CANbridge NT Lua ADK

C Funcons Called from Lua

— copy only 2 bytes from the source array format = array.compile(“#1,0,#2,0×55”) dest_array = array.repack(format, src_array)
— this corresponds to dest_array[1] = src_array[1] dest_array[2] = 0 dest_array[3] = src_array[2] dest_array[4] = 0x55
References to addional uncon parameters are also possible:
— copy 2 byte variables and 2 bytes from the source array to the destination array
format = array.compile(“@1,@2,#3,#4”) dest_array = array.repack(format, src_array, var1, var2)
— this corresponds to dest_array[1] = var1 dest_array[2] = var2 dest_array[3] = src_array[3] dest_array[4] = src_array[4] Important to know: · The length of the desnaon array is directly given by the format string length. · The maximum value for a reference (e.g. #8) is the source array length. · The maximum number for variable references (e.g. @1) is 32. · Valid value for variables are 0 to 255 (unsigned byte). · The maximum value for a constant is 255, or 0xff.
Funcon ‘array.repack’
dest_array = array.repack(format, src_array)
Packs the data from the array src_array according to the compiled format string format and returns the result array.
Valid Operaons on Arrays Read a value:
val = a[2] Write a value:
a[l] = val
Size of the array:
num_bytes = #a

Page 18 of 20

4.02.0332.20002 Version 1.5

C Funcons Called from Lua
Concatenate two arrays:
arr_c = arr_a .. arrb Iterate over an array:
for
,v in ipairs(a) do — do something end

CAN@net NT/CANbridge NT Lua ADK

4.02.0332.20002 Version 1.5

Page 19 of 20

CAN@net NT/CANbridge NT Lua ADK
6. Lua License

Lua License

Copyright © 1994­2019 Lua.org, PUC-Rio.
Permission is hereby granted, free of charge, to any person obtaining a copy of this sofware and associated documenaon les (the “Sofware”), to deal in the Sofware without resricon, including without limiaon the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Sofware, and to permit persons to whom the Sofware is furnished to do so, subject to the following condions:
The above copyright noce and this permission noce shall be included in all copies or subsanal porons of the Sofware.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Page 20 of 20

4.02.0332.20002 Version 1.5

Read User Manual Online (PDF format)

Read User Manual Online (PDF format)  >>

Download This Manual (PDF format)

Download this manual  >>

Related Manuals