Manual ScriptCommunicator
Manual ScriptCommunicator
Manual
Table of contents
ScriptCommunicator History......................................................................................................7
GUI documentation...................................................................................................................18
Main window............................................................................................................................18
Settings dialog..........................................................................................................................19
Send dialog...............................................................................................................................20
Single sequence table.........................................................................................................20
Cyclic sequence area..........................................................................................................20
Scripts dialog............................................................................................................................21
Create sce file dialog................................................................................................................24
Add message dialog.................................................................................................................26
Sending and receiving a file.....................................................................................................26
Configuration files....................................................................................................................26
Main configuration file.............................................................................................................26
Sequence configuration file......................................................................................................27
Script configuration file...........................................................................................................27
SCE configuration file..............................................................................................................27
Command-line arguments.........................................................................................................27
Command-line mode................................................................................................................27
SCE files............................................................................................................................28
SCEZ files..........................................................................................................................28
Self extracting zip (exe) files (only on windows).....................................................................29
Internal architecture..................................................................................................................30
Script interface..........................................................................................................................30
Worker scripts...........................................................................................................................30
void stopScript(void)................................................................................................................31
The scriptThread object/class...................................................................................................32
Main interface....................................................................................................................32
Separate interfaces.............................................................................................................32
Standard dialogs.................................................................................................................32
Filesystem..........................................................................................................................39
SQL support.......................................................................................................................44
XML support......................................................................................................................45
CRC functions...................................................................................................................50
Inter-WorkerScript communication...................................................................................52
Process...............................................................................................................................55
Miscellaneous....................................................................................................................59
The scriptInf object/class.........................................................................................................69
Main interface....................................................................................................................69
Separate interfaces.............................................................................................................85
Script UDP socket class...........................................................................................................85
Script TCP client class..............................................................................................................88
Script TCP server class.............................................................................................................93
Script serial port class..............................................................................................................94
Script PCAN class....................................................................................................................99
Script Aardvark I2C/SPI class................................................................................................102
Script sound class...................................................................................................................109
Script timer class....................................................................................................................109
Script plot window class.........................................................................................................111
User interface classes.............................................................................................................117
Script dialog.....................................................................................................................118
Script main window.........................................................................................................119
Script tab widget..............................................................................................................119
Script tool box..................................................................................................................121
Script group box..............................................................................................................122
Script label.......................................................................................................................123
Script action (menu entry)...............................................................................................123
Script button.....................................................................................................................124
Script tool button.............................................................................................................125
Script check box..............................................................................................................126
Script radio button...........................................................................................................127
Script combo box and font combo box............................................................................128
Script line edit..................................................................................................................130
Script table widget...........................................................................................................131
Script list widget..............................................................................................................139
Script tree widget.............................................................................................................141
Script tree widget item.....................................................................................................144
Script text edit..................................................................................................................146
Script progress bar...........................................................................................................148
Script slider......................................................................................................................149
Script spin box.................................................................................................................150
Script double spin box.....................................................................................................151
Script time edit.................................................................................................................152
Script date edit.................................................................................................................154
Script date time edit.........................................................................................................156
Script calendar widget.....................................................................................................157
Script splitter....................................................................................................................158
Script dial.........................................................................................................................159
Script plot widget.............................................................................................................160
ScriptWidget class...........................................................................................................166
Custom script widget.......................................................................................................172
Dynamic link libraries............................................................................................................173
Sequence script.......................................................................................................................174
Script converter object/class...................................................................................................183
Example scripts.......................................................................................................................187
ScriptCommunicator (https://sourceforge.net/projects/scriptcommunicator/,
https://github.com/szieke/ScriptCommunicator_serial-terminal) is a scriptable cross-platform
data terminal which supports following interfaces:
All sent and received data can be shown in a console and can be logged in an html and a text
log.
In addition to the simple sending and receiving of data the ScriptCommunicator has a script
interface (JavaScript). JavaScript is based on the ECMAScript scripting language, as defined
in standard ECMA-262. Microsoft's JScript, and Netscape's JavaScript are also based on the
ECMAScript standard.
Scripts can send and receive data with the main interface.
In addition to the main interface scripts can create and use own interfaces (serial port
(RS232, USB to serial), UDP, TCP client/server, SPI (Aardvark I2C/SPI) and I2C
(Aardvark I2C/SPI)).
Scripts can be connected to GUI files which have been created with the QtDesigner or
QtCreator. All elements in the GUI (files) can be accessed from the script.
Multiple plot windows and plot widgets can be created by scripts (QCustomPlot from
Emanuel Eichhammer is used).
Dynamic link libraries with a special interface (see chapter Dynamic link libraries) can
be loaded by script. Script function can be called by the library and vice versa.
A video which demonstrates the basic features of ScriptCommunicator can be found here:
https://www.youtube.com/playlist?list=PLniMuy2Q_xGuFB_kl1nte2mDxfeeOu8ce
ScriptCommunicator History
3.18 2015-11-14 • sequence and custom console/log scripts are running in their own thread now
• worker, sequence and custom console/log script function added:
setBlockTime
• blocked worker scripts are terminated now (after the block-time (can be set
with setBlockTime) has elapsed)
• custom console/log script functions changed: readFile, readBinaryFile
• custom console/log script functions added: getFileSize, checkFileExists,
checkDirectoryExists, createDirectory, renameDirectory, renameFile,
deleteFile, deleteDirectory, deleteDirectoryRecursively, readDirectory,
writeFile, writeBinaryFile
3.19 2015-11-18 • new send window menus: create script, add script
• 'edit custom console script' button added (console tab)
• 'edit custom log script' button added (log tab)
3.20 2015-11-21 • bug fix: possible crash while starting a worker script with a syntax error
3.24 2015-12-21 • the sizes of the tool box pages in the main window (Sequences, Scripts, …)
are saved now
• send history added in the main window
• main window send area: the data can be sent with 'alt+enter' now
• main config file lock implemented
3.24.1 (Mac 2015-12-23 • bug fix: error while starting the external script editor on Mac OS X
OS X only) • QtCreator is now used for editing worker script user interfaces on Mac OS X
3.25 2015-12-28 • XML support for worker and custom console/log scripts implemented
• new color dialog for selecting the colors of the consoles (background,
receive data …)
• new manual chapter: 'Configuration files'
3.26 2015-12-30 • bug fix:
◦ possible crash while saving the content of a script plot widget/window
◦ menu 'Config/create new config' did not work correctly
• settings dialog elements adjusted (especially for Linux and Mac OS X)
3.27 2016-01-04 • send history: create script button added
• ScriptTcpClient, ScriptUdpSocket and ScriptSerialPort functions added:
canReadLine, readLine, readAllLines
• ScriptPlotWidget and ScriptPlotWindow:
◦ the x-range, y-min and y-max input fields accept floats now
◦ function setMaxDataPointsPerGraph added
◦ QCustomPlot has been updated to version 1.3.2
◦ show legend check box added
◦ showHelperElements has new arguments
◦ signal plotMousePressSignal added
• ScriptThread functions and signals added/: setScriptState,
getScriptTableName, globalStringChangedSignal,
globalDataArrayChangedSignal, globalUnsignedChangedSignal,
globalSignedChangedSignal, setGlobalRealNumber, getGlobalRealNumber,
globalRealChangedSignal
3.28 2016-01-10 • a simple default script editor is included now
• the sequences- and worker-scripts in the main window tool box are
organized in a list view now
• ScriptPlotWidget and ScriptPlotWindow:
◦ show legend check box added
◦ showHelperElements has new arguments
◦ signal plotMousePressSignal added
• ScriptThread function added: getScriptTableName
3.29 2016-01-16 • bug fix: crash if the start button (main window scripts tab) has been pressed
with an empty script list
• GUI's of paused worker-scripts are disabled (greyed out) now
• ScriptThread functions added: currentCpuArchitecture, productType,
productVersion
• new sequences and scripts are inserted at the front of their tables now
• new menus in the script and the send window: move up/down
• ScriptPlotWidget and ScriptPlotWindow new function added:
setUpdateInterval
• script editor:
◦ the line number is displayed now
◦ zoom in/out implemented
4.00 2016-01-30 • new features:
◦ script debugger (worker-scripts)
◦ custom script widget
• new script widget class: ScriptCanvas2D
• ScriptTableWidget functions changed/added: insertWidget, getWidget,
cellSelectionChangedSignal, getAllSelectedCells,, addCanvas2DWidget
• ScriptWidget functions added: getClassName, height
4.01 2016-02-05 • main window send area: sequence-scripts can be used now
• main window 'Top' button added
• sequence and custom console/log scripts: debug support added
• new custom script widget: ScriptWebView
• ScriptCanvas2D functions added: print, saveToFile
• new command-line argument: -P'plug-in path'
4.02 2016-02-07 • ScriptThread function added: availableSerialPorts
• script editor: multi-document support, 'open all included scripts' button
added
• ScriptSerialPort, ScriptUdpSocket and ScriptTcpClient function added:
writeString
4.03 2016-02-13 • new script editor buttons and menus: new script, edit user interface
• script editor auto completion and call tips for several objects/functions
added:
◦ scriptThread object
◦ several QtScript functions and objects
• script window and send window menu: 'edit all scripts'
• ScriptThread functions added: createProcessAsynchronous,
waitForFinishedProcess, getProcessExitCode, killProcess, terminateProcess,
writeToProcessStdin, readAllStandardOutputFromProcess,
readAllStandardErrorFromProcess, stringToArray, addStringToArray
• sequence and custom console/log script functions added: byteArrayToString,
byteArrayToHexString, stringToArray, addStringToArray
• new example script: TestProcess
4.04 2016-02-23 • ScriptThread functions added: getScriptCommunicatorFolder,
getScriptArguments, zipDirectory, zipFiles, extractZipFile and
getUserDocumentsFolder
• new default argument in ScriptThread.ceateProcessAsynchronous
• new command-line argument: -minScVersion'version', -A'argument' and -
L'library path'
• new main window menu: check for updates
• new file types: .sce (ScriptCommuncator executable) and .scez
(ScriptCommuncator executable, zipped)
• new dialog: create sce file
4.05 2016-02-27 • bug fix: deleting the scez temporary folder failed in some cases
• drag&drop for several GUI elements implemented
4.06 2016-03-05 • bug fixes: wrong 'send history button' text after sending the history, the
console message color has not been saved
• new log option: 'append time stamp at log file name'
• new main window button: reopen (is only visible if the log option 'append
time stamp at log file name' is selected)
• the default text-log file extension is 'txt' now
4.07 2016-03-12 • new ScriptWidget function: setPaletteColorRgb
• new script widget: ScriptFontComboBox
• new and changed ScriptTextEdit functions: lockScrolling, insertHtml and
insertPlainText
• new and changed ScriptThread functions: sendDataArray, sendString,
sendCanMessage and addTabsToMainWindow
4.08 2016-03-19 • bug fix: 0xd ('\r') was changed to 0xa ('\n') in the data input fields (main and
send window) if the format was changed to 'ascii'
• file paths in configuration files are store relative to the configuration file in
which they occur if they have the same root path (on windows for example
C:\)
4.09 2016-04-02 • Linux: changed the config-file directory to
'/${USER}/home/.config/ScriptCommunicator'
• send history: repetition count added
• main window: quit button added, merged the connect and disconnect buttons
to one button, Action menu added
• new ScriptThread function: addToolBoxPagesToMainWindow
• mixed console: the background-color for the different data types (ascii, bin,
hex and dec) can be adjusted now
4.10 2016-05-01 • the console font size can be modified with 'Ctrl' + 'mouse scroll up/down'
now
• send history: the max. number of repetitions have been changed from 99 to
999999999
• increased performance at high data rates
4.11 2016-05-06 • scriptThread functions/signals added: sendReceivedDataToMainInterface,
sendDataFromMainInterfaceSignal, checkScriptCommunicatorVersion
• new worker scripts: exampleScripts\WorkerScripts\AdditionalInterface
4.12 2016-05-28 • bug fix: the state of a script which has been started at the start-up of
ScriptCommunicator was not shown correct if the user interface could not be
found
• worker, sequence and custom console/log script function added:
getAllObjectPropertiesAndFunctions
• the arrangement of the main window script-buttons changed
4.13 2016-07-03 • bug fix: the stop bits, the data bits and the parity (main interface serial port)
were not set correctly (except the default settings)
• script exception-handling improved (in some cases more information is
displayed)
• the TCP server (main interface) can handle multiple TCP clients now
• scriptThread functions and signals added:
getMainInterfaceSerialPortSettings, getMainInterfaceSocketSettings,
mainWindowClearConsoleClickedSignal,
mainWindowLockScrollingClickedSignal
• new argument in scriptThread::appendTextToConsole
• sequence and custom console/log script function added:
appendTextToConsole
• main window save console: the background color is saved now
4.14 2016-07-16 • new ScriptTimer functions and signals: setSingleShot, isSingleShot,
setInterval, interval, isActive, remainingTime, timeoutSignal
• ScriptEditor: auto-completion for script GUI elements and for dynamically
created script objects (e.g. ScriptSerialPort) implemented
4.15 2016-07-30 • ScriptEditor:
◦ if the enter key is pressed after an unclosed '{' then '\n}' is added
◦ improved auto-completion
◦ the auto-completion can be manually started with 'CTRL+Shift' now
4.16 2016-10-11 • bug fix:
◦ possible crash while running a custom log/console script in the script
debugger
◦ possible crash while running a worker script in the script debugger and
receiving data at high data rates
• new worker, and sequence script function: calculateCrc8WithPolynomial
• new worker script function: getMainWindowTitle, setMainWindowTitle
• ScriptEditor: removed the adding of '\n' by the script editor
• main window: worker scripts can be started and stopped by a double click in
the script area
• new worker, custom log/console and sequence script object: conv (script
converter)
4.17 2016-11-01 • bug fix:
◦ error in conv.byteArrayToUint32 (big numbers)
◦ under some circumstances the order of the received and sent bytes were
wrong
• new script converter (conv object) function: unsignedCharToSignedChar
• new command line option: -C'config file'
• ScriptEditor: auto-completion texts for the script SQL classes added
4.18 2016-12-29 • new shortcuts in ScriptEditor and ScriptCommunicator
• ScriptEditor: the font is adjustable now
• new worker script functions: getSerialPortSignals, getTimestamp
• new ScriptWidget functions: getObjectName, setObjectName
• new ScriptButton and ScriptToolButton functions: setCheckable,
isCheckable, isChecked, setChecked
• new ScriptTableWidget function: insertRowWithContent
4.19 2017-02-23 • ScriptStatusBar class removed (replaced by
ScriptMainWindow::showMessage)
• ScriptEditor:
◦ bug fix: ScriptButton::clickedSignal was missing in the auto-
completion list
◦ script file locks added (to prevent opening the same file in multiple
instances of ScriptEditor)
• settings dialog: connect button added
• if ScriptCommunicator detects that a script file is opened by an instance of
ScriptEditor and contains unsaved changes then a message box is displayed
• new config file extensions (.config, .scripts and .seq)
• new script converter function: byteArrayToUtf8String
• new scriptThread functions: getConsoleSettings,
setMainWindowAndTaskBarIcon
• new command-line argument -I
• new ScriptWidget function: setWindowIcon
4.20 2017-03-31 • new scriptThread function: processIsRunning
• scriptThread function changed: getTimestamp
• new ScriptWidget function: createShortCut
• bug fix: readAllStandardOutputFromProcess and
readAllStandardErrorFromProcess return now if the process has stopped (if
isBlocking is true)
• SCE files are now created in a separate folder.
• new ScriptLed (CustomWidget) functions: setColorRgb, setFlashRate
• ScriptEditor: UTF-8 support added
• new worker and custom log/console script object: scriptFile
4.21 2017-05-09 • batch files added with which self extracting (sfx) zip (exe) files can be
created (only on window) with winrar (the sfx file contains all necessary
ScriptCommunictor files and a script (and it's resources) which shall be
executed)
• update tab added (settings dialog)
• ScriptEditor:
◦ global variables are now displayed in the outline window
◦ ui window added
◦ reload/close button added
◦ goto definition added (Ctrl+DoubleClick)
◦ improved source parsing
◦ icons in the outline windows added
◦ find/replace all added
◦ if the mouse is moved to a function with a call tip (API functions like
scriptThread.stopScript()) then this call tip is shown now
4.22 2017-05-27 • option 'None' for 'send on enter key' added
• bug fix: ScriptCommunicator could not open the manual if the installation
folder contains spaces
• ScriptEditor:
◦ tabs can be moved now
◦ Number.api added
◦ bool.api added
◦ improved source parsing
5.00 2017-06-16 • all text pasted in the consoles ('Ctrl+V') is sent now (if the 'send input' check
box is checked)
• Cheetah SPI removed
• Aardvark I2C/SPI support added
5.01 2017-06-22 • bug fix: possible crash if ScriptEditor could not find the saved
settings
5.02 2017-06-30 • bug fix: instead of one timestamp several timestamps were added to the
consoles
• several keys are send now if they are added in a console and the 'send input'
checkbox is checked:
- ESC (0x1b), Backspace (0x08), up (0x1b 0x5b 0x41), down (0x1b 0x5b
0x42), left (0x1b 0x5b 0x44), right (0x1b 0x5b 0x43)
• I2C/SPI slave support added
• scriptInf object added (worker scripts)
• the toolbar position (main window) is saved/restored now
5.03 2017-08-02 • consoles: performance optimizations
• the main window 'Scripts tab' accepts Drag&Drop now
• scripts can be started/stopped with 'Enter' from the main window 'Scripts tab'
now
• new ScriptPlotWindow and ScriptPlotWidget functions: setScatterStyle,
setLineStyle, removeDataRangeFromGraph
• new ScriptCanvas2D properties and functions: textAlign, setFont, fillText
• new ScriptWidget function: setAutoFillBackground
• switched from QCustomPlot 1.3.2 to QCustomPlot 2.0
• sequences can be sent with 'Alt+Enter' from all input elements now (main
window send area and send window)
• sequences can be send with 'Enter' from the main window 'Sequences tab'
now
5.04 2017-08-11 • custom console/log script functionality removed (worker scripts are much
more flexible (exampleScripts\WorkerScripts\MainWindowConsole))
• bug fix: print/save console didn't find any console
• consoles: performance optimizations
5.05 2017-09-10 • bug fix: ScriptPlotWidget::plotMousePressSignal and ScriptPlotWindow::
plotMousePressSignal returned wrong mouse positions.
• ScriptPlotWidget and ScriptPlotWindow: new argument in
setInitialAxisRanges, addGraph accepts now the whole subset of svg color
keywords
• ScriptPlotWidget and ScriptPlotWindow new functions and new signal:
xRangeChangedSignal, setCurrentAxisRanges, setAutoUpdateEnabled,
isAutoUpdateEnabled, updatePlot, setLineWidth, getDataFromGraph
• ScriptEditor: improved source parsing
5.06 2017-09-27 • bug fix: if a hex string with no spaces was inserted into a send area then it
was truncated
• bug fix (Aardvark I2C/SPI): reading more then 128 bytes in on script call did
not work
• in some cases more information is shown if an exception occurs
5.07 2017-12-08 • bug fix: on some platforms the lines in ScriptEditor were overlapping each
other
• main window find tab: the line of the found string is displayed now
• ScriptEditor: 'go to line' added
• ScriptPlotWidget and ScriptPlotWindow: new argument in addDataToGraph
and removeDataRangeFromGraph
5.08 2018-05-25 • new scriptThread function: showOpenFileNamesDialog
• new WorkerScript: exampleScripts\WorkerScripts\xTerm\xTerm.js (terminal
which can interpret xTerm control sequences)
• consoles: If a vertical scrollbar slider is moved up then the scrolling is
automatically locked and if the slider is moved to the end again then the
scrolling is automatically unlocked.
5.09 2018-10-27 • ScriptCommunicator can be build with Qt5.11 now
• new ScriptPlotWidget and ScriptPlotWindow function: saveAllGraphs
• bug fix: ScriptCommunicator could not automatically load/find user
interface files whose file path contains dots.
• bug fix: The min. SC version was not loaded correctly in the SCE file dialog.
5.19 2022-10-29 • Bug fix: If a script calls stopScript then the execution is stopped immediately
now
• If a window position is invalid (not on a screen) it is shown at the
coordinates 0:0 now
• The default mode is dark mode now
5.20 2023-02-10 • Bug fix: configuration files with special characters like à could not be read
• scriptThread: the default final XOR value for calculateCrc8WithPolynomial,
calculateCrc16WithPolynomial and calculateCrc32WithPolynomial is 0 now
• Windows: ScriptCommunicator is 64 bit now
6.00 2023-03-20 • migrated to Qt6.4.2
• script debugger removed
• ScriptCanvas removed
• ScriptThread: renamed sleepFromScript to sleep
• ScriptWidget::getWidgetPointer removed
• ScriptSound: loopsRemaining, loops and setLoops removed
• QCustomPlot 2.1.1 is used now
• ScriptEditor: migrated to Qscintilla 2.13.4
• ScriptThread functions added: getUserHomeFolder, getUserConfigFolder
and getUserGenericConfigFolder
• ScriptXmlWriter: setCodec removed
6.01 2023-03-31 • Bug fix: the worker script function ‘stopFunction’ was not called
• CAN-FD support added
6.02 2023-04-19 • Bug fix: CAN message with no data bytes were not sent
• New options for the input field on the main window added
6.04 2023-07-04 • The default position of a script user interface is the position main window
now
• Sequence script functionality removed from the main window
6.05 2023-10-18 • If ScriptCommunicator detects a not supported Widget (e.g. LCD number) it
adds a message in the script window instead of showing a message box
• Bug fix: The console font size was ignored
Note: The console font size can be modified with 'Ctrl' + 'mouse scroll up/down'.
a sequence area in which the sequences from the send window can be sent
a script area in which the scripts from the script window can be started (normal and in
a script-debugger, stopped and paused)
a find text in console area in which a console text can be searched (in the visible
console)
the send history
Settings dialog
the main interface settings (serial port tab, sockets tab, aardvark I2c/Spi tab and pcan
tab)
the console settings (the console options and the colors tab)
the log settings (the log options tab)
the update proxy settings (the update tab)
the path to the external script editor (for editing a script in the script window)
activate/deactivate the dark mode
Note: To close this dialog press the close button or press Ctrl+Shift+X.
Send dialog
The send dialog contains the single sequence table and a cyclic sequence area.
Note:
A selected row in the sequence table can be moved up or down while holding the left mouse
button at the row and moving the mouse up and/or down.
In addition to the simple sending of a sequence a sequence script can be used (see chapter
Sequence script).
Note:
If ScriptCommunicator is connected to a I2C master interface the send bytes are:
Byte 0= flags bits (1=10 bit address, 2=combined FMT, 4=no stop condition)
Byte 1-2 (MSB)= I2C address
Byte 3-4 (MSB)= number of bytes to read
Byte 5-n= the data which shall be sent
Note:
To close this dialog press Ctrl+Shift+X.
Scripts dialog
In this window worker scripts (see chapter Worker scripts) can be added and executed.
This dialog contains following functionality:
Edit a script (with an external script editor): select the corresponding row and press
Ctrl+E menu script/edit script
Create new script (from template): Ctrl+N or menu script/new script (after pressing
this menu 2 dialogs appear (first the template file must be chosen and then the
name/path of the new script))
Edit an ui file (with QtDesigner): select the corresponding row and press
Ctrl+Shift+E or the menu script/edit ui
Create new ui file: select the corresponding row and press Ctrl+Shift+N or the menu
script/new ui
Edit all scripts: press Ctrl+Shift+A or menu script/edit all sequence scripts
Load and save the script configuration (the content of the script table)
Following is implemented:
Load a script configuration from a file: Ctrl+L or menu script config/load config
Unload the current script configuration: Ctrl+U or menu script config/unload config
Save the current script configuration: Ctrl+S or menu script config/save config
Save config as (opens a save dialog, where a file name can be chosen): Ctrl+Shift+S
or menu script config/save config as
Start a script: select the corresponding row and press the start button or press Ctrl+1
Debug a script: select the corresponding row and press the debug button or press
Ctrl+2 (the script will be executed with an attached script debugger)
Pause a running script: select the corresponding row and press the pause button or
press Ctrl+2
Stop a running or paused script: select the corresponding row and press the stop button
or press Ctrl+3
Note:
If ScriptCommunicator is closed it saves the state (running, paused and not running) of all
scripts. If ScriptCommunicator is started again all script status are restored.
This means if a script is running while ScriptCommunicator is closing then this script will be
automatically started after ScriptCommunicator has been started the next time.
To clear the console press the clear button or press or press Ctrl+Shift+C.
To close this dialog press the close button + press Ctrl+Shift+X.
Load and save the sce file configuration (the content of the complete window)
Following is implemented:
Note:
• To generate a sce or a scez file at least one 'executable script' must be in the file table
(a file marked with this type is started by ScriptCommunicator as script) and the sce
file name must be set.
• If ScriptCommunicator shall load the user interface file of the 'executable script'
automatically, then it must have the same name, it must have the file-ending .ui and it
must reside in the same folder. If the user interface file has not the same name, has not
the file-ending .ui or resides not in the same folder, then the function bool
loadUserInterfaceFile(String path, bool isRelativePath=true, bool showAfterLoading =
true) must be used to load the user interface file manually.
• To close this dialog press Ctrl+Shift+X.
• To start/execute a sce or scez file ScriptCommunicator must be started with the
corresponding file as a command-line argument (see chapter Command-line
arguments).
• If you have associated the .scez and the .sce file ending with ScriptCommunicator then
you can simply double click on the file to execute it.
File table
The file table contains following columns:
• sub directory: contains the directory of the file entry inside the sce folder
• file type: the type of the file entry
• source: the source of the file entry
The file type is used by ScriptCommunicator to suggest the sub directory (which can be
changed manually).
Furthermore following file types have a special meaning:
• executable script: a file marked with this type is started by ScriptCommunicator
(during the sce or scez file execution)the
• lib: the sub directory of this file is added to the ScriptCommunicator library path (if
you need extra libraries (e.g. for a custom widget) then add the libraries with this file
type)
• plugin: the sub directory of this file is added to the ScriptCommunicator plug-in path
(if you need extra plug-ins (e.g. for a custom widget) then add the plug-ins with this
file type)
Arguments list
All arguments which are added here can be read by the worker scripts with Array<String>
getScriptArguments(void).
Note:
You can find an example sce project in ScriptCommunicator\exampleScripts\WorkerScripts\
PlotWindow (exampleSceFileConfig.xml).
Add message dialog
In this dialog a message can be entered which will be shown in the consoles and be written
into the logs.
Configuration files
ScriptCommunicator has 4 configuration files:
Note: File paths in configuration files are store relative to the configuration file in which they
occur if they have the same root path (on windows for example C:\).
To create/use a new main configuration file the 'Config' menu in the main window can be
used (see chapter Main window).
Sequence configuration file
The sequence configuration file contains all entries of the sequence table in the send window.
To load, unload or save the sequence configuration file the 'config' menu can be used (see
chapter Change the sequence configuration).
Command-line arguments
ScriptCommunicator has several command-line arguments. These arguments are:
• -A: a script command-line argument (these arguments can be read by worker scripts
with the function Array<String> getScriptArguments(void)
• -L: adds an additional library path (e.g. for loading a custom script widget)
• -C: the configuration file to start with (if a script, a sce or a scez file is in the
command-line arguments then the configuration file is ignored)
• -P: adds an additional folder to the ScriptCommunicator plug-in (custom script
widgets) search path
• -I: replace the standard icon for the main window (taskbar and window), supported
formats: .ico, .gif, .png, .jpeg, .tiff, .bmp, .icns
• scripts, sce files (see chapter SCE files) or scez files (see chapter SCEZ files)
separated by a space (if a script file is in the command-line arguments then the option -C
(configuration file) is ignored)
Example:
ScriptCommunicator.exe -CC:\initialSettingsWin2.config -IC:\myIcon.ico
Command-line mode
ScriptCommunicator has a command-line mode in which scripts can be executed without the
ScriptCommunicator GUI. This command-line mode is entered if a script, a sce or a scez file
is found in the command-line arguments.
SCE files
The sce file (ScriptCommunicator executable) is a possibility to put all command-line
arguments in one file. This file is a simple XML file and has following structure:
<ExecutableConfig version="04.04"> <!--ScriptCommunicator version with which this file has been created-->
<Scripts>
<Script path="./scripts/scrip1.js"/><!--script which shall be started-->
<Script path="./scripts/scrip2.js"/><!--script which shall be started-->
</Scripts>
<LibraryPaths>
<LibraryPath path="./libs1"/><!--additional library path-->
<LibraryPath path="./libs2"/><!--additional library path-->
</LibraryPaths>
<PluginPaths>
<PluginPath path="./plugins1"/><!--additional plugin path-->
<PluginPath path="./plugins2"/><!--additional plugin path-->
</PluginPaths>
<ScriptArguments>
<ScriptArgument value="arg1"/><!--script argument (getScriptArguments())-->
<ScriptArgument value="arg2"/><!--script argument (getScriptArguments())-->
</ScriptArguments>
<Options withScriptWindow="1" notMinimized="1" minScVersion="4.4"/>
<!--these 3 attributes have the same meaning as the corresponding command-line argument-->
</ExecutableConfig>
Notes:
• For creating a sce file the Create sce file dialog shall be used (but it can be created manually
too).
• If a sce file is in the command-line arguments then the option -C (configuration file) is
ignored.
SCEZ files
A scez file (ScriptCommunicator executable, zipped) is a zipped sce file (including all
necessary files and folders). To ensure the data integrity of a scez file a SHA-512 hash is
appended.
Notes:
• To create a scez file the Create sce file dialog must be used.
• If a scez file is in the command-line arguments then the option -C (configuration file) is
ignored.
If the created executable is started all files are extracted in a temporary folder and the script is
executed. After the script is finished the temporary is deleted.
Notes:
• You can find an example sce project in ScriptCommunicator\winRarSfx\exampleSfx
(to build this sfx example open create.bat, replace the path to winrar and execute
create.bat.
• Another tools for creating self extracting zip/exe files which executes a programm
after extraction of the data (and deletes the temporary folder after the programm has
exited) is Iexpress. But to use this you musst execute this programm as admin and you
have to create a batch file which recovers the necessary ScriptCommunictor folder
structure (Iexpress ectracts all files in one temporary folder) and starts
ScriptCommunicator with the sce oder scez file.
Internal architecture
The following picture illustrates the internal architecture of ScriptCommunicator.
Script interface
The script interface of ScriptCommunicator is able the execute JavaScript files. This is done
with the Qt class QJSEngine.
Worker scripts
Worker scripts can be added in the script window. In this scripts complex functions can be
implemented (sending/receiving data, file operations …).
Every worker script runs in his own thread, therefore ScriptCommunicator can not be blocked
by a worker script directly. The GUI of a worker script runs in the main thread (a call to a
script GUI element normally calls a function in the main thread), therefore to many calls to
script GUI elements can block ScriptCommunicator.
Worker scripts are JavaScript scripts (see chapter Script interface). The worker script
interface extends the standard JavaScript functionality. These extended functionality is
described in the following chapters.
Note:
A worker script can have a user interface (created with QtDesigner (is included) or
QtCreator).
To load a user interface following can be done:
• set the path to the user interface in the script window (the user interface will be loaded
automatically when the script starts)
• or call scriptThread.loadUserInterfaceFile() in the worker script (to load a user
interface manually)
The supported GUI elements and their classes are described in chapter User interface classes
Note:
In the main function (all code outside a function) only the script initialization code should be
placed. The working code should be placed in asynchronous function calls (like timer
callbacks or data receive callbacks). If the main function has been left the script does not
stop. To stop a script call scriptThread.stopScript() or press the stop button (main or script
window).
Example:
//Asynchronous data receive callback.
function dataReceived()
{
//Working code.
if(workDone)
{
scriptThread.stopScript();
}
}
//Initialization code.
var workDone = false;
scriptThread.appendTextToConsole('script has started');
scriptThread.dataReceivedSignal.connect(dataReceived);
If the worker code shall be placed in the main function then scriptThread.scriptShallExit() should be
called to check if the script must exit.
Example:
scriptThread.appendTextToConsole('script has started');
while(!scriptThread.scriptShallExit())
{
//Working code.
}
void stopScript(void)
This script function can be added to a worker script. It is called if the script shall be informed
that it will be stopped (for example if the user presses the stop button)
Example:
function stopScript()
{
scriptThread.appendTextToConsole("script has been stopped ");
}
The scriptThread object is the main interface object for accessing ScriptCommunicator
functions from script. The functions and signals which can be used from script are described
in the following chapters.
Main interface
Worker scripts can send and receive data with the main interface. For more details see The
scriptInf object/class.
Note:
The main interface is the interface which can be adjusted in the settings window .
Separate interfaces
Worker scripts can create separate interfaces (to send and receive data without the main
interface). For more details see The scriptInf object/class.
Standard dialogs
In this chapter all available standard dialog are described.
String showFileDialog (bool isSaveDialog, String caption, String dir, String filter,
Widget parent=0)
Shows a file dialog for selecting one file (QFileDialog::getSaveFileName or
QFileDialog::getOpenFileName).
Arguments:
isSaveDialog: True for a QFileDialog::getSaveFileName and false for a
QFileDialog::getOpenFileName dialog
caption: The caption of the dialog
dir: The initial dir for showing the dialog (may be empty)
filter: Filter for the file dialog (for more details see QFileDialog, http://doc.qt.io/qt-
4.8/qfiledialog.html, may be empty)
parent: The widget to which this dialog belongs to (typically ScriptDialog or
ScriptMainWindow). This is only needed if more then one windows is created by the
script.
String getScriptFolder(void)
Returns the folder in which the main script resides.
Example:
var result = scriptFile.getScriptFolder();
SQL support
Worker scripts can access SQL databases. The Qt SQL classes are nearly 1:1 available in
ScriptCommunicator. The documentation of the Qt SQL classes can be found here:
https://doc.qt.io/qt-6/qsqldatabase.html. The differences are described below.
Creating objects
For creating SQL related Objects the scriptSql Object has following functions:
• QSqlDriver* QSqlDatabase::driver()
• void QsqlDatabase::registerSqlDriver(const String &name, QSqlDriverCreatorBase
*creator)
• QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const String&
connectionName = QLatin1String(defaultConnection))
• QsqlDriver* QSqlQuery::driver()
• QsqlResult* QsqlQuery::result()
var db = scriptSql.addDatabase("QSQLITE");
//Set the numerical precision policy to QSql::LowPrecisionInt32.
db.setNumericalPrecisionPolicy(0x1);
XML support
Worker scripts can access XML files with the ScriptXmlReader and the ScriptXmlWriter
classes. This 2 classes contain a subset of the Qt XML functionality.
Note: Example scripts which demonstrate the usage of the XML script classes class can be
found under exampleScripts/WorkerScripts/TestXml.
ScriptXmlReader* createXmlReader(void)
Creates an XML reader.
Example:
var reader = cust.createXmlReader();
ScriptXmlWriter* createXmlWriter(void)
Creates an XML writer.
Example:
var writer = cust.createXmlWriter();
ScriptXmlReader
Class for reading a xml file.
Number readFile(String fileName, bool isRelativePath=true)
Reads and parses a xml file. The parsed xml file is stored internally.
Arguments:
fileName: The name of the xml file.
isRelativePath: True if the file path is relative to the main script.
Return:
0: success
1: file could not be opened
2: parse error
ScriptXmlElement *getRootElement(void)
Returns the root XML element.
ScriptXmlElement
This class represents an XML element.
String elementName(void)
Returns the name of this element.
Array<ScriptXmlElement*> childElements(void)
Returns all child elements.
Array<String> childTextElements(void)
Returns all child text elements (includes the CDATA elements).
Array<String> childCDataElements(void)
Returns all child CDATA elements.
Array<String> childCommentElements(void)
Returns all child comment elements.
String attributeValue(String attrName)
Returns an attribute value. The attribute is identified by attrName.
Array<ScriptDomAttribute*> attributes(void)
Returns all attributes of this element.
ScriptXmlAttribute
This class represents a xml attributte.
String value(void)
Returns the value of the attribute.
String name(void)
Returns the name of the attribute.
ScriptXmlWriter
This class provides functions for creating/writing XML files.
Note: All function are working on an internal XML buffer.
The function writteBufferToFile must be used to write the content of the internal XML buffer
to a file.
String getInternalBuffer(void)
Returns the content of the internal buffer.
String clearInternalBuffer(void)
Clears the internal buffer.
Number autoFormattingIndent(void)
Returns the autoFormatingIndent property.
void writeEndDocument(void)
Closes all remaining open start elements and writes a newline.
Arguments:
name: The name of the element.
text: The text.
namespaceUri: The namespace URI.
void writeEndElement(void)
Closes the previous start element.
CRC functions
The following functions can be used to create various CRC's.
return crc;
}
return crc;
}
return crc;
}
Inter-WorkerScript communication
The following functions can be used to share variables between single worker scripts (these
variable are stored in ScriptCommunicator global worker script maps).
Process
This chapter contains process related functions.
Miscellaneous
This chapter contains general functions.
Converter functions
The script converter class provides several converter functions. These functions can be
accessed with the conv object (see chapter Script converter object/class).
String getScriptTableName(void)
Returns the script-table (script window) name of the calling script.
void appendTextToConsole(String text, bool newLine=true, bool
bringToForeground=false)
This function can be used to append a text to the script window console.
Arguments:
text: The text which has to be appended to the console
newLine: If true then the text will be appended in a new line
bringToForeground: True if the script window shall be on top of all windows
Example:
scriptThread.appendTextToConsole("exception in dataReceivedSlot: " + e);
bool scriptShallExit(void)
Returns true if the script shall exit. This can occur if:
• the user has pressed the stop button (main or script window)
• the script has called scriptThread.stopScript()
• an uncaught exception has been occurred
void stopScript(void)
This function stops the current script.
Example:
if(error)
{
scriptThread.stopScript(scriptThread);
}
Array<String> getLocalIpAdress(void)
Returns all IP addresses (IPv4 and IPv6) found on the host machine (array with strings).
Example:
var ipList = scriptThread.getLocalIpAdress();
for(var i = 0; i < ipList.length; i++)
{
scriptThread.appendTextToConsole(ipList[i])
}
String getCurrentVersion
Returns the current version of ScriptCommunicator (string) .
Version format: major.minor (eg. 3.09)
String currentCpuArchitecture(void)
Returns the architecture of the CPU that the application is running on, in text format.
Note that this function depends on what the OS will report and may not detect the actual CPU
architecture if the OS hides that information or is unable to provide it. For example, a 32-bit
OS running on a 64-bit CPU is usually unable to determine the CPU is actually capable of
running 64-bit programs.
Values returned by this function are mostly stable: an attempt will be made to ensure that they
stay constant over time and match the values returned by QSysInfo::builldCpuArchitecture().
However, due to the nature of the operating system functions being used, there may be
discrepancies.
Typical returned values are (note: list not exhaustive):
• "arm"
• "arm64"
• "i386"
• "ia64"
• "mips"
• "mips64"
• "power"
• "power64"
• "sparc"
• "sparcv9"
• "x86_64
String productType(void)
Returns the product name of the operating system this application is running in. If the
application is running on some sort of emulation or virtualization layer (such as WINE on a
Unix system), this function will inspect the emulation / virtualization layer.
Values returned by this function are stable and will not change over time, so applications can
rely on the returned value as an identifier, except that new OS types may be added over time.
Linux and Android note: this function returns "android" for Linux systems running Android
userspace, notably when using the Bionic library. For all other Linux systems, regardless of C
library being used, it tries to determine the distribution name and returns that. If determining
the distribution name failed, it returns "unknown".
BlackBerry note: this function returns "blackberry" for QNX systems running the
BlackBerry userspace, but "qnx" for all other QNX-based systems.
Darwin, OS X and iOS note: this function returns "osx" for OS X systems, "ios" for iOS
systems and "darwin" in case the system could not be determined.
FreeBSD note: this function returns "debian" for Debian/kFreeBSD and "unknown"
otherwise.
Windows note: this function returns "winphone" for builds for Windows Phone, "winrt" for
WinRT builds, "wince" for Windows CE and Embedded Compact builds, and "windows" for
normal desktop builds.
For other Unix-type systems, this function usually returns "unknown".
String productVersion(void)
Returns the product version of the operating system in string form. If the version could not be
determined, this function returns "unknown".
It will return the Android, BlackBerry, iOS, OS X, Windows full-product versions on those
systems. In particular, on OS X, iOS and Windows, the returned string is similar to the
macVersion() or windowsVersion() enums.
On Linux systems, it will try to determine the distribution version and will return that. This is
also done on Debian/kFreeBSD, so this function will return Debian version in that case.
In all other Unix-type systems, this function always returns "unknown".
Note: The version string returned from this function is only guaranteed to be orderable on
Android, BlackBerry, OS X and iOS. On Windows, some Windows versions are text ("XP"
and "Vista", for example). On Linux, the version of the distribution may jump unexpectedly,
please refer to the distribution's documentation for versioning practices.
Array<String> getScriptArguments(void)
Returns the script arguments (command-line argument -A).
Example:
var args = scriptThread.getScriptArguments();
for(var i = 0; i < args.length; i++)
{
scriptThread.appendTextToConsole(args[i])
}
String getScriptCommunicatorFolder(void)
Returns the ScriptCommunicator program folder.
String getUserDocumentsFolder(void)
Returns the directory containing user document files.
String getUserHomeFolder(void)
Returns the user home folder.
MAC:"~";
WIN:"C:/Users/<USER>";
LINUX:"~"
String getUserConfigFolder(void)
Returns a directory location where user-specific configuration files should be written. This
may be either a generic value or application-specific.
MAC: "~/Library/Preferences";
WIN:"C:/Users/<USER>/AppData/Local/<APPNAME>","C:/ProgramData/<APPNAME>";
LINUX:"~/.config","/etc/xdg"
String getUserGenericConfigFolder(void)
Returns a directory location where user-specific configuration files shared between multiple
applications should be written.
MAC: "~/Library/Preferences";
WIN:"C:/Users/<USER>/AppData/Local","C:/ProgramData";
LINUX:"~/.config","/etc/xdg"
//Remove the tab from the dialog and add it to the main window.
if(!scriptThread.addTabsToMainWindow(UI_TabWidget))
{
scriptThread.messageBox("Critical", "Error", "addTabsToMainWindow failed");
scriptThread.stopScript();
}
//Remove the pages from the dialog and add it to the main window.
if(!scriptThread.addToolBoxPagesToMainWindow(UI_ToolBox))
{
scriptThread.messageBox("Critical", "Error", "addToolBoxPagesToMainWindow
failed");
scriptThread.stopScript();
}
void mainWindowClearConsoleClickedSignal(void)
Is emitted if the clear console button in the main window is pressed.
Example:
function mainWindowClearConsoleClicked()
{
UI_TextEdit1.clear();
}
scriptThread.mainWindowClearConsoleClickedSignal.connect(mainWindowClearConsoleClicked);
String getMainWindowTitle(void)
Returns the title of the main window.
String getTimestamp(void)
Returns the current time stamp in a specific format (see QDateTime.toString for more details).
If the format string is empty then the format from the settings dialog (console options tab) is used.
Example:
scriptThread.appendTextToConsole(scriptThread.getTimestamp("yyyy-MM-dd hh:mm:ss.zzz"));
ConsoleSettings getConsoleSettings(void)
Returns the console settings (settings dialog).
Return:
ConsoleSettings: The console settings. ConsoleSettings contains following properties:
o bool showReceivedData: True if the received data (main interface) shall be
shown in the console.
o bool showSendData: True if the send data (main interface) shall be shown in
the console.
o Number maxChars: Max. numbers of chars in the consoles.
o bool lockScrolling: If true then the consoles do not scroll to the end after
adding new data.
o String font: The consoles font.
o String fontSize: The consoles font size.
o Number updateInterval: The consoles update interval.
o String receiveColor: The color (hex) of receive data.
o String sendColor: The color (hex) of send data.
o String backgroundColor: The background color (hex) of the consoles.
o String timestampColor: The color (hex) of timestamps.
o Number newLineAfterBytes: New line after ... number of sent/received bytes
(0=off).
o Number newLineAfterPause: New line after ... ms send/receive pause (0=off).
o bool createNewLineAtByte: True if a new line shall be created at a specific
byte. (newLineAtByte).
o Number newLineAtByte: These bytes will be replaced by a new line.
o bool ceateTimestampAtByte: True if a timestamp shall be created at a specific
byte (timestampAtByte)
o Number timestampAtByte: New timestamp at byte.
o bool generateCyclicTimeStamps: True if cyclic timestamps shall be created in
the. consoles (timeStampInterval).
o Number timeStampInterval: The console timestamp interval.
o String imestampFormat: The timestamp format.
Example:
var settings = scriptThread.getConsoleSettings();
scriptThread.appendTextToConsole(settings.backgroundColor);
scriptThread.appendTextToConsole(settings.font);
Array<String> availableSerialPorts(void)
Returns a list with the name of all available serial ports.
Example:
var availablePorts = scriptThread.availableSerialPorts();
for(var i = 0; i < availablePorts.length; i++)
{
UI_serialPortInfoListBox.addItem(availablePorts[i]);
}
Array<PortInfo> availableSerialPortsExt(void)
Returns a list with the information (PortInfo object) of all available serial ports.
Example:
var ports = scriptInf.availableSerialPortsExt();
for(var i = 0; i < ports.length; i++)
{
scriptThread.appendTextToConsole("serial port info name:" + ports[i].portName + " systemLocation:"
+ ports[i].systemLocation
+ " description:" + ports[i].description + " manufacturer:" + ports[i].manufacturer + "
serialNumber:" + ports[i].serialNumber
+ " vendorIdentifier: " + ports[i].vendorIdentifier + " productIdentifier:" +
ports[i].productIdentifier);
}
PortInfo
This object/structure contains information about the serial ports:
• String portName: The name of the serial port.
• String systemLocation: The system location of the serial port.
• String description: The description of the serial port.
• String serialNumber: The serial number of the serial port.
• Number vendorIdentifier: The vendor identifier of the serial port.
• Number productIdentifier: The product identifier of the serial port.
Main interface
The following functions can be used to send and receive data with the main interface.
Note:
• The main interface is the interface which can be adjusted in the settings window
(worker scripts can create/use own interfaces too (see chapter Separate interfaces)).
• Examples of all interface types can be found at the end of this chapter.
Note:
• If ScriptCommunicator is connected to a I2C master interface use i2cMasterReadWrite to
send data.
• If ScriptCommunicator is connected to a CAN interface use sendCanMessage to send data.
• If ScriptCommunicator is connected to a I2C slave or to a SPI slave interface then this function
sets the slave response (the data is only sent if the master request it). If more bytes are
requested in a transaction (from the master), the response will be wrapped as many times as
necessary to complete the transaction. The device buffer space is 64 bytes.
Note:
• If ScriptCommunicator is connected to a I2C master interface use i2cMasterReadWrite to
send data.
• If ScriptCommunicator is connected to a CAN interface use sendCanMessage to send data.
• If ScriptCommunicator is connected to a I2C slave or to a SPI slave interface then this function
sets the slave response (the data is only sent if the master request it). If more bytes are
requested in a transaction (from the master), the response will be wrapped as many times as
necessary to complete the transaction. The device buffer space is 64 bytes.
bool isConnectedWithCan(void)
Returns true if the main interface is a CAN interface (and is connected).
Example:
if(scriptInf.isConnectedWithCan())
{
var result = scriptInf.sendCanMessage(2, 0x0f, Array(0,0,0,0), 0, 0);
}
bool isConnectedWithI2c(void)
Returns true if the main interface is a I2C interface (and is connected).
bool isConnected(void)
Returns true if the main interface is connected.
Example:
if(scriptInf.isConnected())
{
scriptInf.sendString("test string");
}
void disconnect(void)
Disconnects the main interface.
Number getSerialPortSignals(void)
Returns the state of the serial port signals (pins).The signals are bit coded:
• NoSignal = 0x00
• DataTerminalReadySignal = 0x04
• DataCarrierDetectSignal = 0x08
• DataSetReadySignal = 0x10
• RingIndicatorSignal = 0x20
• RequestToSendSignal = 0x40
• ClearToSendSignal = 0x80
SerialPortSettings getMainInterfaceSerialPortSettings(void)
Returns the serial port settings of the main interface.
Return:
SerialPortSettings: The serial port settings. SerialPortSettings contains following
properties:
o String name: The name of the serial port.
o Number baudRate: The baudrate.
o Number dataBits: The number of data bits.
o String parity: The parity.
o String stopBits: The stop bits.
o String flowControl: The flow control.
o bool rts: True if the RTS pin is on.
o bool dtr: True if the DTR pin is on.
Example:
var settings = scriptInf.getMainInterfaceSerialPortSettings();
scriptThread.appendTextToConsole(settings.name);
scriptThread.appendTextToConsole(settings.baudRate);
scriptThread.appendTextToConsole(settings.dataBits);
scriptThread.appendTextToConsole(settings.parity);
scriptThread.appendTextToConsole(settings.stopBits);
scriptThread.appendTextToConsole(settings.flowControl);
scriptThread.appendTextToConsole(settings.rts);
scriptThread.appendTextToConsole(settings.dtr);
SocketSettings getMainInterfaceSocketSettings(void)
Returns the socket (UDP, TCP client/server) settings of the main interface.
Return:
SocketSettings: The socket settings. SocketSettings contains following properties:
o Number destinationPort: The detination port.
o String destinationIpAddress: The destination IP address.
o Number ownPort: The own port.
o String socketType: The socket type ('TCP client', 'TCP server' or 'UDP
socket').
o Number proxySettings: The proxy settings:
0 = no proxy
1 = use system proxy settings
2 = use custom proxy settings
o String proxyIpAddress: The proxy IP address.
o Number proxyPort: The proxy port.
o String proxyUserName: The proxy user name.
o String proxyPassword: The proxy password.
Example:
var settings = scriptInf.getMainInterfaceSocketSettings();
scriptThread.appendTextToConsole(settings.destinationPort);
scriptThread.appendTextToConsole(settings.destinationIpAddress);
scriptThread.appendTextToConsole(settings.ownPort);
scriptThread.appendTextToConsole(settings.socketType);
scriptThread.appendTextToConsole(settings.proxySettings);
scriptThread.appendTextToConsole(settings.proxyIpAddress);
scriptThread.appendTextToConsole(settings.proxyPort);
scriptThread.appendTextToConsole(settings.proxyUserName);
scriptThread.appendTextToConsole(settings.proxyPassword);
String aardvarkI2cSpiDetectDevices(void)
Returns a string which contains informations about all detected Aardvark I2C/SPI devices.
settings.i2cBaudrate = parseInt(UI_AardvarkI2cBaudrate.text());
settings.i2cSlaveAddress = parseInt(UI_AardvarkI2cSlaveAddress.text());
settings.i2cPullupsOn = (UI_AardvarkI2cPullUp.currentText() == "On") ? true : false
settings.spiPolarity = UI_AardvarkSpiPolarity.currentIndex();
settings.spiSSPolarity = UI_AardvarkSpiSSPolarity.currentIndex();
settings.spiBitorder = UI_AardvarkSpiBitorder.currentIndex();
settings.spiPhase = UI_AardvarkSpiPhase.currentIndex();
settings.spiBaudrate = parseInt(UI_AardvarkSpiBaudrate.text());
settings.pinConfigs = Array();
for(var i = 0; i < AARDVARD_I2C_SPI_GPIO_COUNT; i++)
{
settings.pinConfigs[i] = Array();
settings.pinConfigs[i].isInput =
(g_aardvardI2cGpioGuiElements[i].mode.currentText().indexOf("in") != -1) ? true : false;
settings.pinConfigs[i].withPullups =
(g_aardvardI2cGpioGuiElements[i].mode.currentText().indexOf("in pullup") != -1) ? true : false;
settings.pinConfigs[i].outValue = (g_aardvardI2cGpioGuiElements[i].outValue.currentText() == 1) ?
true : false;
}
/**********************************************************************************/
if(!scriptInf.aardvarkI2cSpiConnect(settings))
{
scriptThread.appendTextToConsole("connect error");
}
AardvarkI2cSpiSettings
This object/structure contains the settings for an Aardvark I2C/SPI interface:
• Number devicePort: The device port.
• Number deviceMode: The device mode (0=I2C master and GPIO, 1=I2C slave and
GPIO, 2=SPI master and GPIO, 3=SPI slave and GPIO, 4=GPIO)
• bool device5VIsOn: True if the 5V pins shall be on.
• Number i2cBaudrate: The I2C baudrate.
• Number i2cSlaveAddress: The I2C address in slave mode.
• bool i2cPullupsOn: True if the I2C pullups shall be enabled.
• AardvarkSpiPolarity spiPolarity: The SPI Polarity (0=rising/falling, 1=faling/rising).
• AardvarkSpiSSPolarity spiSSPolarity: The SPI slave select polarity (0=active low,
1=active high).
• AardvarkSpiBitorder spiBitorder: The SPI bitorder (0=MSB, 1=LSB).
• AardvarkSpiPhase spiPhase: The SPI phase (0=sample setup, 1=setup sample).
• Number spiBaudrate: The SPI baudrate.
• AardvarkI2cSpiGpioConfig pinConfigs[6]: The pin configuration (see
AardvarkI2cSpiGpioConfig). Elements of pinConfigs are:0=Pin1/SCL, 1=Pin3/SDA,
2=Pin5/MISO, 3=Pin7/SCK, 4=Pin8/MOSI, 5=Pin9/SS0.
AardvarkI2cSpiGpioConfig
Contains the pin configuration for an Aardvark I2C/SPI interface:
• bool isInput: True if the pin is an input.
• bool withPullups: True if the pin shall have a pullup (works only with inputs).
• bool outValue: The value of the output.
Array<bool> aardvarkI2cSpiReadAllInputs(void)
Reads all inputs of the Aardvark I2C/SPI device.
The indexes of the result array are:0=Pin1/SCL, 1=Pin3/SDA, 2=Pin5/MISO, 3=Pin7/SCK,
4=Pin8/MOSI, 5=Pin9/SS0.
AardvarkI2cSpiSettings aardvarkI2cSpiGetMainInterfaceSettings(void)
Returns the Aardvark I2C/SPI settings (AardvarkI2cSpiSettings) of the main interface.
Example:
var readSettings = scriptInf.aardvarkI2cSpiGetMainInterfaceSettings();
var consoleString = "connected: <br>" + settingsStructToString(readSettings);
scriptThread.appendTextToConsole(consoleString);
function settingsStructToString(readSettings)
{
var result = "devicePort=" + readSettings.devicePort + " deviceMode=" + readSettings.deviceMode + "
device5VIsOn=" + readSettings.device5VIsOn;
result += " i2cBaudrate=" + readSettings.i2cBaudrate + " i2cSlaveAddress=" +
readSettings.i2cSlaveAddress + " i2cPullupsOn=" + readSettings.i2cPullupsOn + "
spiSSPolarity=" + readSettings.spiSSPolarity;
result += " spiBitorder=" + readSettings.spiBitorder + " spiPhase=" + readSettings.spiPhase + "
spiBaudrate=" + readSettings.spiBaudrate;
for(var i = 0; i < AARDVARD_I2C_SPI_GPIO_COUNT; i++)
{
var mode = "out";
if(readSettings.pinConfigs[i].isInput)
{
if(readSettings.pinConfigs[i].withPullups)
{
mode = "in pullups";
}
else
{
mode = "in";
}
}
result += "<br>"+ g_aardvardI2cGpioGuiElements[i].mode.getAdditionalData(0) + " mode=" +
mode;
result += " "+ g_aardvardI2cGpioGuiElements[i].mode.getAdditionalData(0) + " outValue=" +
readSettings.pinConfigs[i].outValue;
}
return result;
}
void i2cMasterFreeBus(void)
Frees the main interface I2C bus (this function can be used if the no stop condition was
created during the last i2cMasterReadWrite call).
//Is called if data has been received with the main interface.
function dataReceivedSlot(data)
{
scriptThread.appendTextToConsole("data received: data=" + conv.byteArrayToHexString(data));
}
scriptInf.dataReceivedSignal.connect(dataReceivedSlot);
if(!scriptInf.connectSerialPort("COM1", 9600))
{
scriptThread.appendTextToConsole("connectSerialPort failed");
scriptThread.stopScript();
}
//Is called if data has been received with the main interface.
function dataReceivedSlot(data)
{
scriptThread.appendTextToConsole("data received: data=" + conv.byteArrayToHexString(data));
}
scriptInf.dataReceivedSignal.connect(dataReceivedSlot);
//Is called if data has been received with the main interface.
function dataReceivedSlot(data)
{
scriptThread.appendTextToConsole("data received: data=" + conv.byteArrayToHexString(data));
}
scriptInf.dataReceivedSignal.connect(dataReceivedSlot);
//Is called if data has been received with the main interface.
function dataReceivedSlot(data)
{
scriptThread.appendTextToConsole("data received: data=" + conv.byteArrayToHexString(data));
}
scriptInf.dataReceivedSignal.connect(dataReceivedSlot);
if(!scriptInf.aardvarkI2cSpiConnect(settings))
{
scriptThread.appendTextToConsole("aardvarkI2cSpiConnect failed");
scriptThread.stopScript();
}
scriptInf.i2cMasterDataReceivedSignal.connect(i2cMasterDataReceivedSlot);
function slaveDataSentSlot(data)
{
scriptThread.appendTextToConsole("data sent: data=" + conv.byteArrayToHexString(data));
}
//Get the current Aardvard I2C/SPI settings.
settings = scriptInf.aardvarkI2cSpiGetMainInterfaceSettings();
settings.devicePort = 0;
settings.deviceMode = 1;//I2C slave
settings.device5VIsOn = false;
settings.i2cBaudrate = 400;
settings.i2cPullupsOn = true;
if(!scriptInf.aardvarkI2cSpiConnect(settings))
{
scriptThread.appendTextToConsole("aardvarkI2cSpiConnect failed");
scriptThread.stopScript();
}
//Set the response (this data is only send if the master requests it).
if(!scriptInf.sendDataArray(Array(0, 1, 2, 3, 4)))
{
UI_Console.append("set slave response failed");
scriptThread.stopScript();
}
scriptInf.dataReceivedSignal.connect(dataReceivedSlot);
scriptInf.slaveDataSentSignal.connect(slaveDataSentSlot);
if(!scriptInf.aardvarkI2cSpiConnect(settings))
{
scriptThread.appendTextToConsole("aardvarkI2cSpiConnect failed");
scriptThread.stopScript();
}
scriptInf.dataReceivedSignal.connect(dataReceivedSlot);
function slaveDataSentSlot(data)
{
scriptThread.appendTextToConsole("data sent: data=" + conv.byteArrayToHexString(data));
}
if(!scriptInf.aardvarkI2cSpiConnect(settings))
{
scriptThread.appendTextToConsole("aardvarkI2cSpiConnect failed");
scriptThread.stopScript();
}
//Set the response (this data is only send if the master requests it).
if(!scriptInf.sendDataArray(Array(0, 1, 2, 3, 4)))
{
UI_Console.append("set slave response failed");
scriptThread.stopScript();
}
scriptInf.dataReceivedSignal.connect(dataReceivedSlot);
scriptInf.slaveDataSentSignal.connect(slaveDataSentSlot);
Separate interfaces
The following functions can be used to create separate interfaces (to send and receive data
without the main interface).
ScriptUdpSocket createUdpSocket(void)
Creates an UDP socket object (for more details see chapter Script UDP socket class).
Return: The created UDP socket object
Example:
var udpSocket = scriptInf.createUdpSocket();
ScriptPcan createPcanInterface(void)
Creates a PCAN interface object (for more details see chapter Script PCAN class).
Return: The created PCAN interface object
Example:
var pcan = scriptInf.createPcanInterface();
ScriptAardvarkI2cSpi aardvarkI2cSpiCreateInterface(void)
Creates an Aardvark I2c/SPI interface (for more details see Script Aardvark I2C/SPI class).
Example:
var g_interface = scriptInf.aardvarkI2cSpiCreateInterface();
The functions and signals which can be used are described in the following chapters.
bool bind(Number port)
Binds the socket to a port.
Arguments:
port: The port
bool isOpen(void)
Returns true if the UDP socket is open/listening.
void close(void)
Closes the socket.
bool hasPendingDatagrams(void)
Returns true if a received datagram can be read from the socket.
Array<Number> readDatagram(void)
Returns the data (byte array) from one received datagram.
Array<Number> readAll(void)
Reads all received datagrams (the data from the single datagrams are inserted in one byte
array)
void disableMainInterfaceRouting(void)
Disables the main interface routing.
bool canReadLine(void)
This function checks if a data line (ends with EOL ('\n')) is ready to be read.
Return: True if a line is ready to be read.
The functions and signals which can be used are described in the following chapters.
bool isOpen(void)
Returns true if the TCP client is open/connected.
void close(void)
This function closes the socket.
bool isReadable(void)
Returns true if data can be read from the socket.
Number bytesAvailable(void)
Returns the number of bytes which are available for reading.
Array<Number> readAll(void)
This function returns all received bytes (byte array).
String getErrorString(void)
Returns a human-readable description of the last error that has been occurred.
void enableMainInterfaceRouting(void)
Enables the main interface routing (all data from the main interface is send with this socket
and
all received (with this socket) data is sent with the main interface).
void disableMainInterfaceRouting(void)
Disables the main interface routing.
QAbstractSocket::Connection 0 The connection was refused by the peer (or timed out).
RefusedError
QAbstractSocket::RemoteHos 1 The remote host closed the connection. Note that the
tClosedError client socket (i.e., this socket) will be closed after the
remote close notification has been sent.
QAbstractSocket::HostNotFo 2 The host address was not found.
undError
QAbstractSocket::SocketAcc 3 The socket operation failed because the application
essError lacked the required privileges.
QAbstractSocket::SocketReso 4 The local system ran out of resources (e.g., too many
urceError sockets).
QAbstractSocket::SocketTim 5 The socket operation timed out.
eoutError
QAbstractSocket::DatagramT 6 The datagram was larger than the operating system's
ooLargeError limit (which can be as low as 8192 bytes).
QAbstractSocket::NetworkEr 7 An error occurred with the network (e.g., the network
ror cable was accidentally plugged out).
QAbstractSocket::AddressIn 8 The address specified to QAbstractSocket::bind() is
UseError already in use and was set to be exclusive.
QAbstractSocket::SocketAdd 9 The address specified to QAbstractSocket::bind() does
ressNotAvailableError not belong to the host.
QAbstractSocket::Unsupporte 10 The requested socket operation is not supported by the
dSocketOperationError local operating system (e.g., lack of IPv6 support).
QAbstractSocket::ProxyAuth 12 The socket is using a proxy, and the proxy requires
enticationRequiredError authentication.
QAbstractSocket::SslHandsha 13 The SSL/TLS handshake failed, so the connection was
keFailedError closed (only used in QSslSocket)
QAbstractSocket::Unfinished 11 Used by QAbstractSocketEngine only, The last
SocketOperationError operation attempted has not finished yet (still in
progress in the background).
QAbstractSocket::ProxyConn 14 Could not contact the proxy server because the
ectionRefusedError connection to that server was denied
QAbstractSocket::ProxyConn 15 The connection to the proxy server was closed
ectionClosedError unexpectedly (before the connection to the final peer
was established)
QAbstractSocket::ProxyConn 16 The connection to the proxy server timed out or the
ectionTimeoutError proxy server stopped responding in the authentication
phase.
QAbstractSocket::ProxyNotF 17 The proxy address set with setProxy() (or the
oundError application proxy) was not found.
QAbstractSocket::ProxyProto 18 The connection negotiation with the proxy server failed,
colError because the response from the proxy server could not be
understood.
QAbstractSocket::OperationE 19 An operation was attempted while the socket was in a
rror state that did not permit it.
QAbstractSocket::SslInternal 20 The SSL library being used reported an internal error.
Error This is probably the result of a bad installation or
misconfiguration of the library.
QAbstractSocket::SslInvalid 21 Invalid data (certificate, key, cypher, etc.) was provided
UserDataError and its use resulted in an error in the SSL library.
QAbstractSocket::Temporary 22 A temporary error occurred (e.g., operation would block
Error and socket is non-blocking).
QAbstractSocket::UnknownS -1 An unidentified error occurred.
ocketError
TCP client example
The following Code shows the typically use of the TCP client class:
//Connection established.
function connectSlot()
{
var array = Array(1,2,3,4,5,6);
//send data to the host
tcpClient.write(array);
}
//Connection closed.
function disconnectSlot()
{
scriptThread.appendTextToConsole("disconnected ");
tcpClient.close();
}
//Data has been received.
function readyReadSlot ()
{
var array = tcpClient.readAll();
scriptThread.appendTextToConsole("data received: " + array);
//send data to the host
tcpClient.write(array);
}
//An error has been ocurred.
function tcpClientErrorSlot(error)
{
if(error != 1)
{//The error is not QAbstractSocket::RemoteHostClosedError.
disconnectSlot();
}
if(error == 0) //QAbstractSocket::ConnectionRefusedError
{
scriptThread.messageBox("Critical", "TCP error",
"The connection was refused. " +
"Make sure the server is running, " +
"and check that the host name and port " +
"settings are correct.");
}
else if(error == 1) //QAbstractSocket::RemoteHostClosedError
{
//The connection has been closed. Do nothing.
}
else if(error == 2) //QAbstractSocket::HostNotFoundError
{
scriptThread.messageBox("Critical", "TCP error",
"The server was not found. Please check the " +
"host name and port settings.");
}
else
{
scriptThread.messageBox("Critical", "TCP error",
"The following error occurred: " +
tcpClient.getErrorString());
}
}
The functions and signals which can be used are described in the following chapters.
Number maxPendingConnections(void)
Returns the max. pending connections.
void close(void)
This function closes the TCP server.
ScriptTcpClient nextPendingConnection(void)
Return the next pending connection (returns a script TCP client).
The functions and signals which can be used are described in the following chapters.
Note:
If the script serial port is connected the RTS (request to send) and DTR (data terminal ready)
signals are automatically set to high (and set low at disconnect).
String portName(void)
Returns the serial port name.
Number baudRate(void)
Returns the baudrate.
Number dataBits(void)
Returns the number of data bits.
String parity(void)
Returns the parity. Possible values are: "None ", "Even", "Odd ", "Space" and "Mark".
String errorString(void)
Returns the error string from the serial port (contains additional information in the case of an
error).
bool open(void)
Opens the serial port.
Return: True on success
void close(void)
Closes the serial port.
Number bytesAvailable(void)
Returns the number of bytes which are available for reading.
Array<Number> readAll(void)
This function returns all received bytes (byte array).
Number bytesToWrite(void)
Returns the number of bytes which are not written yet.
void enableMainInterfaceRouting(void)
Enables the main interface routing (all data from the main interface is send with this socket
and
all received (with this socket) data is sent with the main interface).
void disableMainInterfaceRouting(void)
Disables the main interface routing.
bool canReadLine(void)
This function checks if a data line (ends with EOL ('\n')) is ready to be read.
Return: True if a line is ready to be read.
void readyReadSignal(void)
This signal is emitted if data is available for reading (if data has been received).
Number getSerialPortSignals(void)
Returns the state of the serial port signals (pins).
The signals are bit coded:
• NoSignal = 0x00,
• DataTerminalReadySignal = 0x04
• DataCarrierDetectSignal = 0x08
• DataSetReadySignal = 0x10
• RingIndicatorSignal = 0x20
• RequestToSendSignal = 0x40
• ClearToSendSignal = 0x80
Script serial port example
The following Code shows the typically use of the script serial port class:
function readyReadSlot()
{
var array = serialPort.readAll();
scriptThread.appendTextToConsole("data received: " + array);
//send data to the host
serialPort.write(array);
}
serialPort.setPortName("COM1");
serialPort.setDTR(false);
if (serialPort.open())
{
serialPort.setBaudRate(19200);
serialPort.setDataBits(8);
serialPort.setParity("None");
serialPort.setStopBits("1.5");
serialPort.setFlowControl("None");
serialPort.setDTR(true);
serialPort.setRTS(true);
scriptThread.appendTextToConsole("serial port signals:" +
serialPort.getSerialPortSignals().toString(16) );
}
else
{
scriptThread.messageBox("Critical", 'error', 'could not open serial port');
}
The functions and signals which can be used are described in the following chapters.
void close(void)
Closes the PCAN interface.
bool setFilter(bool filterExtended, Number filterFrom, Number filterTo)
Configures the reception filter.
Arguments:
filterExtended: True if the filer message type is extended (29-bit identifier) or false if
the filter message type is standard (11-bit identifier)
filterFrom: The lowest CAN ID to be received
filterTo: The highest CAN ID to be received
Return: True on success.
bool isConnected(void)
Returns true if connected to a PCAN interface.
String getStatusString(void)
Returns the current status as string.
Number getCurrentStatus(void)
Returns the current status.
//PCAN_CHANNEL_IDENTIFYING=0x15
var valueAndStatus = pcan.getCanParameter(0x15, value);
var status = valueAndStatus >> 15;
var value = valueAndStatus & 0xff;
if(!status)
{
scriptThread.messageBox("Critical", "error", ' getCanParameter failed')
}
The functions and signals which can be used are described in the following chapters.
AardvarkI2cSpiSettings getInterfaceSettings(void)
Returns the Aardvark I2C/SPI settings (AardvarkI2cSpiSettings).
Example:
var g_interface = scriptInf.aardvarkI2cSpiCreateInterface();
var readSettings = g_interface.getInterfaceSettings();
var consoleString = "connected: <br>" + settingsStructToString(readSettings);
scriptThread.appendTextToConsole(consoleString);
function settingsStructToString(readSettings)
{
var result = "devicePort=" + readSettings.devicePort + " deviceMode=" + readSettings.deviceMode + "
device5VIsOn=" + readSettings.device5VIsOn;
result += " i2cBaudrate=" + readSettings.i2cBaudrate + " i2cSlaveAddress=" +
readSettings.i2cSlaveAddress + " i2cPullupsOn=" + readSettings.i2cPullupsOn + "
spiSSPolarity=" + readSettings.spiSSPolarity;
result += " spiBitorder=" + readSettings.spiBitorder + " spiPhase=" + readSettings.spiPhase + "
spiBaudrate=" + readSettings.spiBaudrate;
for(var i = 0; i < AARDVARD_I2C_SPI_GPIO_COUNT; i++)
{
var mode = "out";
if(readSettings.pinConfigs[i].isInput)
{
if(readSettings.pinConfigs[i].withPullups)
{
mode = "in pullups";
}
else
{
mode = "in";
}
}
result += "<br>"+ g_aardvardI2cGpioGuiElements[i].mode.getAdditionalData(0) + " mode=" +
mode;
result += " "+ g_aardvardI2cGpioGuiElements[i].mode.getAdditionalData(0) + " outValue=" +
readSettings.pinConfigs[i].outValue;
}
return result;
}
void i2cMasterFreeBus(void)
Frees the main interface I2C bus (this function can be used if the no stop condition was created
during the last i2cMasterReadWrite call).
String detectDevices(void)
Frees the main interface I2C bus (this function can be used if the no stop condition was created
during the last masterI2cSendReceiveData call).
settings.i2cBaudrate = parseInt(UI_AardvarkI2cBaudrate.text());
settings.i2cSlaveAddress = parseInt(UI_AardvarkI2cSlaveAddress.text());
settings.i2cPullupsOn = (UI_AardvarkI2cPullUp.currentText() == "On") ? true : false
settings.spiPolarity = UI_AardvarkSpiPolarity.currentIndex();
settings.spiSSPolarity = UI_AardvarkSpiSSPolarity.currentIndex();
settings.spiBitorder = UI_AardvarkSpiBitorder.currentIndex();
settings.spiPhase = UI_AardvarkSpiPhase.currentIndex();
settings.spiBaudrate = parseInt(UI_AardvarkSpiBaudrate.text());
settings.pinConfigs = Array();
for(var i = 0; i < AARDVARD_I2C_SPI_GPIO_COUNT; i++)
{
settings.pinConfigs[i] = Array();
settings.pinConfigs[i].isInput =
(g_aardvardI2cGpioGuiElements[i].mode.currentText().indexOf("in") != -1) ? true : false;
settings.pinConfigs[i].withPullups =
(g_aardvardI2cGpioGuiElements[i].mode.currentText().indexOf("in pullup") != -1) ? true : false;
settings.pinConfigs[i].outValue = (g_aardvardI2cGpioGuiElements[i].outValue.currentText() == 1) ?
true : false;
}
/**********************************************************************************/
void disconnect(void)
Disconnects from the interface.
bool i2cMasterReadWrite(Number flags, Number slaveAddress, Number
numberOfBytesToRead, Array<Number> dataToSend = Array<Number>(), Number)
Accesses the I2C bus (write/read). The received data can be read with
i2cMasterReadLastReceivedData.
Arguments:
flags: The I2C flags: 0x00= no flags, 0x01= 10bit address, 0x02=combined
FMT,0x04= no stop condition (use i2cMasterFreeBus to generate the stop condition
later)
slaveAddress: The I2C address
numberOfBytesToRead: The number of bytes wich shall be read.
dataToSend: The bytes which shall be send/written (if this array is empty only a read
is performed)
Return: True on success
Example:
var result = g_interface.i2cMasterReadWrite(0, 0x01, 4, Array(1,2,3,4));
Array<Number> i2cMasterReadLastReceivedData(void)
Returns last received data from the I2C interface (master mode).
Array<Number> spiMasterReadLastReceivedData(void)
Returns last received data from the SPI interface (master mode).
Array<bool> readAllInputs(void)
Reads all inputs.
The indexes of the result array are:0=Pin1/SCL, 1=Pin3/SDA, 2=Pin5/MISO, 3=Pin7/SCK,
4=Pin8/MOSI, 5=Pin9/SS0.
bool isConnected(void)
Returns true if the interface is connected.
if(!g_interface.connectToDevice(settings))
{
scriptThread.appendTextToConsole("connectToDevice failed: " + result);
scriptThread.stopScript();
}
function slaveDataReceivedSlot(data)
{
scriptThread.appendTextToConsole("slave data received: data=" + conv.byteArrayToHexString(data));
}
if(!g_interface.connectToDevice(settings))
{
scriptThread.appendTextToConsole("connectToDevice failed: " + result);
scriptThread.stopScript();
}
if(!g_interface.slaveSetResponse(Array(1, 2, 3, 4, 5)))
{
scriptThread.appendTextToConsole("slaveSetResponse failed");
scriptThread.stopScript();
}
g_interface.slaveDataSentSignal.connect(slaveDataSentSlot);
g_interface.slaveDataReceivedSignal.connect(slaveDataReceivedSlot);
if(!g_interface.connectToDevice(settings))
{
scriptThread.appendTextToConsole("connectToDevice failed: " + result);
scriptThread.stopScript();
}
function slaveDataReceivedSlot(data)
{
scriptThread.appendTextToConsole("slave data received: data=" + conv.byteArrayToHexString(data));
}
if(!g_interface.connectToDevice(settings))
{
scriptThread.appendTextToConsole("connectToDevice failed: " + result);
scriptThread.stopScript();
}
if(!g_interface.slaveSetResponse(Array(1, 2, 3, 4, 5)))
{
scriptThread.appendTextToConsole("slaveSetResponse failed");
scriptThread.stopScript();
}
g_interface.slaveDataSentSignal.connect(slaveDataSentSlot);
g_interface.slaveDataReceivedSignal.connect(slaveDataReceivedSlot);
Script sound class
The script sound class is a wrapper for QSound. It provides a method to play .wav sound files.
String fileName(void)
Returns the filename associated with this script sound object.
bool isFinished(void)
Returns true if the sound has finished playing otherwise returns false.
void play(void)
Starts playing the sound specified by this QSound object.
void stop(void)
Stops the sound playing.
Script sound example
The following code shows the typically use of the script sound class:
var soundObject = scriptThread.createSoundObject("yes-2.wav");
void start(void)
Starts or restarts the timer with the timeout interval set in setInterval. If the timer is already
running, it will be stopped and restarted. If the timer is a single-shot timer, then the timer will
be activated only once.
void stop(void)
Stops the timer.
void setSingleShot(bool singleShot)
Sets the timer to single-shot or non-single-shot. A single-shot timer fires only once, non-
single-shot timers fire every interval milliseconds.
Arguments:
singleShot: True if the timer is a single-shot timer.
bool isSingleShot(void)
Returns true if the timer is a single-shot timer.
Number interval(void)
Returns the timer interval.
bool isActive(void)
Returns true if the timer is running, otherwise false.
Number remainingTime(void)
Returns the timer's remaining value in milliseconds left until the timeout. If the timer is
inactive, the returned value will be -1. If the timer is overdue, the returned value will be 0.
Timer example
The following Code shows the typically use of the timer class:
function updateConsole()
{
scriptThread.appendTextToConsole("updateConsole function called")
}
var consoleTimer = scriptThread.createTimer()
consoleTimer.timeoutSignal.connect(updateConsole);
consoleTimer.start(200);
Note: To plot data in an existing script GUI (and not in a separate window) the Script plot
widget class can be used.
void clearGraphs(void)
This function clears the data of all graphs.
void removeAllGraphs(void)
This function removes all graphs.
PlotAxisRanges
This object/structure contains the axis ranges:
• xMinValue: The min. values of the x axis.
• xMaxValue: The max. value of the x axis.
• yMinValue: The min. values of the y axis.
• ymaxValue: The max. value of the y axis.
• y2MinValue: The min. values of the y axis 2.
• y2maxValue: The max. value of the y axis 2.
bool isAutoUpdateEnabled(void)
Returns the automatic update enabled state.
void updatePlot(void)
Repaints the plot widget.
plotWindow.clearButtonPressedSignal.connect(clearButtonPressed)
plotWindow.closedSignal.connect(plotWindowClosedSlot)
var x = 0;
var y = 0;
for(var i = 0; i < 100; i++)
{
x++;
y++;
plotWindow.addDataToGraph(plotWindowGraph1Index, x, y);
plotWindow.addDataToGraph(plotWindowGraph2Index, x + 10, y);
if(y > 10)
{
y = 0;
}
}
• QDialog
• QMainWindow
• QTabWidget
• QToolBox
• QGroupBox
• QLabel
• QAction
• QStatusBar
• QPushButton
• QToolButton
• QCheckBox
• QRadioButton
• QComboBox
• QFontComboBox
• QLineEdit
• QTableWidget
• QListWidget
• QTreeWidget
• QTreeWidgetItem
• QTextEdit
• QProgressBar
• QSlider
• QSpinBox
• QDoubleSpinBox
• QTimeEdit
• QDateEdit
• QDateTimeEdit
• QCalendarWidget
• QSplitter
• QDial
Note: Only the supported GUI elements can be accessed by worker scripts.
Script dialog
A QDialog in the user interface file is passed to the worker script via a ScriptDialog class
object.
This class is derived from the ScriptWidget class. Therefore all functions from the script
widget class can be used.
The additional functions and signals which can be used from script are described in the
following chapters.
void finishedSignal(void)
This signal is emitted if the user closes the dialog.
creating shortcuts
For creating shortcuts (e.g. Ctrl+V) void createShortCut(QString keys, QScriptValue
scriptFunction) can be used.
creating shortcuts
For creating shortcuts (e.g. Ctrl+V):
• menu items with shortcuts can be created (only main windows can have menus) in
QtDesigner (the menu items can be accessed with Script action (menu entry))
void finishedSignal(void)
This signal is emitted if the user closes the window.
Number currentIndex(void)
Returns the current tab index.
Number currentIndex(void)
Returns the current item index.
String title(void)
Returns the group box title.
ScriptPlotWidget addPlotWidget(void)
Adds a plot widget to the group box (see chapter Script plot widget for more details).
function groupBoxCheckBoxClickedSlot(checked)
{
UI_testTextEdit.append("groupBoxCheckBoxClickedSlot: " + checked)
//Do something.
}
UI_checkableGroupBox.setTitle("new title");
UI_checkableGroupBox.checkBoxClickedSignal.connect(groupBoxCheckBoxClickedSlot)
Script label
A QLabel in the user interface file is passed to the worker script via a ScriptLabel class object.
This class is derived from the ScriptWidget class. Therefore all functions from the
ScriptWidget class can be used.
The additional functions and signals which can be used from script are described in the
following chapters.
String text(void)
Returns the label text.
Example:
var string = UI_createProcessProgramLabel.text();
Important: This class is not derived from the ScriptWidget class. Therefore the functions
from the ScriptWidget class can not be used.
The functions and signals which can be used from script are described in the following
chapters.
String text(void)
Returns the action text.
bool isChecked(void)
Returns true if the action is checked.
Script button
A QPushButton in the user interface file is passed to the worker script via a ScriptButton class
object.
This class is derived from the ScriptWidget class. Therefore all functions from the
ScriptWidget class can be used.
The additional functions and signals which can be used from script are described in the
following chapters.
String text(void)
Returns the button text.
bool isChecked(void)
Returns true if the button is checked and false if not.
String text(void)
Returns the button text.
bool isCheckable(void)
Returns true if the button is checkable and false if not.
bool isChecked(void)
Returns true if the button is checked and false if not.
String text(void)
Returns the check box text.
void setChecked(bool checked)
Sets the checked state of the check box.
Arguments:
check: True=checked, false=not checked
bool isChecked(void)
Returns true if the check box is checked.
Note: If several radio buttons are in the same area, only one radio button can be checked (all
other are unchecked automatically).
String text(void)
Returns the radio button text.
Number currentIndex(void)
Returns the index of the current selected item.
String currentText(void)
Returns the text of the current selected item.
Number count(void)
Returns the number of items in the combo box.
void clear(void)
Clears the combo box and removes all items.
void clear(void)
Clears the line edit.
String text(void)
Returns the text of the line exit.
bool isReadOnly(void)
Returns true of the line edit is editable.
Note:
A selected row in the table can be moved up or down while holding the left mouse button at
the row and moving the mouse up and/or down.
Number columnCount(void)
Return the column count.
void clear(void)
Clears the table (removes all cells).
void setCellBackgroundColorRgb(int row, int column, int r, int g, int b, int alpha =
255)
Sets the background color of a single cell with the RGB value.
Arguments:
row: The row of the cell
column: The column of the cell
r: Red
g: Green
b: Blue
alpha: The alpha channel (transparency) value
Example:
UI_testSetTextLineEdit.setCellBackgroundColorRgb(0, 0, 255, 0, 0);
void setCellForegroundColorRgb(int row, int column, int r, int g, int b, int alpha =
255)
Sets the foreground color of a single cell with the RGB value.
Arguments:
row: The row of the cell
column: The column of the cell
r: Red
g: Green
b: Blue
alpha: The alpha channel (transparency) value
Example:
UI_testSetTextLineEdit.setCellForegroundColorRgb(0, 0, 255, 0, 0);
Number frameWidth(void)
Returns the width of the frame that is drawn.
Number verticalHeaderWidth(void)
Returns the width of the vertical header.
Number verticalScrollBarWidth(void)
Returns the width of the vertical scroll bar.
bool isVerticalScrollBarVisible(void)
Returns true if the vertical scroll bar is visible.
Arguments:
row: The row of the cell
column: The column of the cell
type: The type of the created widget. Possible type values are:
o LineEdit
o ComboBox
o Button
o CheckBox
o SpinBox
o DoubleSpinBox
o VerticalSlider
o HorizontalSlider
o TimeEdit
o DateEdit
o DateTimeEdit
o CalendarWidget
o TextEdit
o Dial
Return: True on success
Example:
function TableCheckBoxClicked(checked)
{
UI_testTextEdit.append("TableCheckBoxClicked: " + checked);
}
UI_testSendTableWidget.insertWidget(3, 1, "CheckBox");
var UI_tableCheckBox1 = UI_testSendTableWidget.getWidget(3, 1);
if(typeof UI_tableCheckBox1 != 'undefined')
{
UI_tableComboBox1.addItem("val1");
UI_tableCheckBox1.clickedSignal.connect(TableCheckBoxClicked)
}
ScriptWidget* getWidget(Number row, Number column)
Returns the cell widget. If the cell has no widget then 'invalid' is returned.
Example: see bool insertWidget(Number row, Number column, String type).
Note: To determine the class name of the returned ScriptWidget String getClassName(void)
can be used.
Array<ScriptTableCellPosition> getAllSelectedCells(void)
Returns an array which contains the the rows and columns of the selected cells. The array
contains one ScriptTableCellPosition object for every selected cell.
The ScriptTableCellPosition object has to attributes which can be accessed: row and column.
Example: see void cellChangedSignal (void).
}
UI_testSendTableWidget.cellSelectionChangedSignal.connect(SendTableSelectionChanged)
Adjusting the width of the columns so that all columns fit in the complete table
The following code shows an example how to adjust the right column so that all columns fit
in the complete table (the table has 2 columns):
//Adjust the width of the right column, so that all columns fit in the complete table.
function adjustTableColmnWidth()
{
var verticalScrollBarWidth = 0;
if(UI_TableWidget.isVerticalScrollBarVisible())
{
verticalScrollBarWidth = UI_TableWidget.verticalScrollBarWidth();
}
UI_TableWidget.setColumnWidth(1, UI_TableWidget.width() -
(UI_TableWidget.columnWidth(0)
+ 2 * UI_TableWidget.frameWidth()
+ UI_TableWidget.verticalHeaderWidth()
+ verticalScrollBarWidth));
}
UI_testSendTableWidget.horizontalHeaderSectionResizedSignal.connect(UI_tableHorizontalHeaderSectionResizedSi
gnal);
Note:
A selected row in the table can be moved up or down while holding the left mouse button at
the row and moving the mouse up and/or down.
Number rowCount(void)
Returns the number of rows in the list widget.
void clear(void)
Clears the list widget.
function UI_listWidgetCurrentRowChanged(currentRow)
{
UI_testTextEdit.append("UI_listWidgetCurrentRowChanged: " + currentRow);
}
function UI_listWidgetItemClicked(currentRow)
{
UI_testTextEdit.append("UI_listWidgetItemClicked: " + currentRow);
}
function UI_listWidgetItemDoubleClicked(currentRow)
{
UI_testTextEdit.append("UI_listWidgetItemDoubleClicked: " + currentRow);
}
UI_sendListWidget.insertNewItem(UI_sendListWidget.rowCount(), "item0",
scriptThread.createAbsolutePath("icons/folder.gif"));
UI_sendListWidget.seItemBackgroundColor(UI_sendListWidget.rowCount() - 1, "red")
UI_sendListWidget.insertNewItem(UI_sendListWidget.rowCount(), "item1",
scriptThread.createAbsolutePath("icons/browser.ico"));
UI_sendListWidget.setCurrentRow(0);
UI_sendListWidget.currentRowChangedSignal.connect(UI_listWidgetCurrentRowChanged);
UI_sendListWidget.itemClickedSignal.connect(UI_listWidgetItemClick)
UI_sendListWidget.itemDoubleClickedSignal.connect(UI_listWidgetItemDoubleClicked);
ScriptTreeWidgetItem* createScriptTreeWidgetItem(void)
Creates a script tree widget item (for more details about the script tree widget item see chapter
Script tree widget item)
Note: A created ScriptTreeWidgetItem has to be inserted in a ScriptTreeWidget or has to be
deleted with ScriptTreeWidgetItem::deleteItem() (memory leak).
Number topLevelItemCount(void)
Returns the number of top level items.
ScriptTreeWidgetItem* invisibleRootItem(void)
Returns the tree widget's invisible root item.
The invisible root item provides access to the tree widget's top-level items through
the ScriptTreeWidgetItem API, making it possible to write functions that can treat top-level
items and their children in a uniform way; for example, recursive functions.
Number columnCount(void)
Returns the number of columns displayed in the tree widget.
void expandAll(void)
Expands all expandable items.
ScriptTreeWidgetItem* currentItem(void)
Returns current item in the tree widget.
UI_treeWidget.itemClickedSignal.connect(UI_treeWidgetItemClicked);
UI_treeWidget.itemDoubleClickedSignal.connect(UI_treeWidgetItemDoubleClicked);
UI_treeWidget.setColumnWidth(0, 100);
UI_treeWidget.expandItem(treeItem1);
Important: This class is not derived from the ScriptWidget class. Therefore the functions
from the ScriptWidget class can not be used.
Number childCount(void)
Returns the number of child items.
void deleteItem(void)
Deletes the current item.
Number columnCount(void)
Returns the number of columns in the item.
bool isExpanded(void)
Returns true if the item is expanded, otherwise returns false.
bool isDisabled(void)
Returns true if the item is disabled; otherwise returns false.
Number verticalScrollBarValue(void)
Returns the vertical scroll bar value.
String toPlainText(void)
Returns the content of the text edit as plain text.
String toHtml(void)
Returns the content of the text edit as html.
void moveTextPositionToEnd(void)
Moves the curser to the end of the text edit.
void clear(void)
Clears the text edit.
Script slider
A QSlider (horizontal and vertical) in the user interface file is passed to the script via a
ScriptSlider class object. This class is derived from the ScriptWidget class. Therefore all
functions from the ScriptWidget class can be used.
The additional functions and signals which can be used from script are described in the
following chapters.
Number value(void)
Returns the slider's current value.
Number value(void)
Returns the spin box's current value.
void setSingleStep(Number value)
If the user uses the arrows to change the spin box's value the value will be
incremented/decremented by the amount of the single step. The default value is 1.
Setting a single step value of less than 0 does nothing.
Arguments:
value: The new value
Number singleStep(void)
Returns the single step value.
Number value(void)
Returns the spin box's current value.
void setSingleStep(Number value)
If the user uses the arrows to change the spin box's value the value will be
incremented/decremented by the amount of the single step. The default value is 1.0.
Setting a single step value of less than 0 does nothing.
Arguments:
value: The new value
Number singleStep(void)
Returns the single step value.
Number decimals(void)
Returns the precision of the spin box, in decimals.
String getDisplayFormat(void)
Returns the display format.
Time format
Following expressions may be used for the time format:
Expression Output
h the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
hh the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
m the minute without a leading zero (0 to 59)
mm the minute with a leading zero (00 to 59)
s the second without a leading zero (0 to 59)
ss the second with a leading zero (00 to 59)
z the milliseconds without leading zeroes (0 to 999)
zzz the milliseconds with leading zeroes (000 to 999)
AP interpret as an AM/PM time. AP must be either "AM" or "PM".
ap Interpret as an AM/PM time. ap must be either "am" or "pm".
All other input characters will be treated as text. Any sequence of characters that are enclosed in
single quotes will also be treated as text and not be used as an expression.
//time is 12:01.00
UI_timeEdit.setDisplayFormat("m'mm'hcarss");
UI_timeEdit.setTime("1mm12car00");
Expressions that do not expect leading zeroes to be given (h, m, s and z) are greedy.
This means that they will use two digits even if this puts them outside the range of accepted
values and leaves too few digits for other sections.
For example, the following string could have meant 00:07:10, but the m will grab two digits,
resulting in an invalid time:
//invalid
UI_timeEdit.setDisplayFormat("hh:ms");
UI_timeEdit.setTime("00:710");
Any field that is not represented in the format will be set to zero. For example:
//time is 00:01:30.000
UI_timeEdit.setDisplayFormat("m.s");
UI_timeEdit.setTime("1.30");
String getDate(void)
Returns the date.
String getDisplayFormat(void)
Returns the display format.
Date format
Following expressions may be used for the date format:
Expression Output
d The day as a number without a leading zero (1 to 31)
dd The day as a number with a leading zero (01 to 31)
ddd The abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses the system locale to localize the
name, i.e. QLocale::system().
dddd The long localized day name (e.g. 'Monday' to 'Sunday'). Uses the system locale to localize the
name, i.e. QLocale::system().
M The month as a number without a leading zero (1 to 12)
MM The month as a number with a leading zero (01 to 12)
MMM The abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses the system locale to localize
the name, i.e. QLocale::system().
MMMM The long localized month name (e.g. 'January' to 'December'). Uses the system locale to
localize the name, i.e. QLocale::system().
yy The year as two digit number (00 to 99)
yyyy The year as four digit number. If the year is negative, a minus sign is prepended in addition.
All other input characters will be treated as text. Any sequence of characters that are enclosed
in single quotes will also be treated as text and will not be used as an expression. For
example:
//date is 1 December 2003
UI_dateEdit.setDisplayFormat("d'MM'MMcaryyyy");
UI_dateEdit.setDate("1MM12car2003");
The expressions that don't expect leading zeroes (d, M) will be greedy. This means that they will use
two digits even if this will put them outside the accepted range of values and leaves too few digits for
other sections. For example, the following format string could have meant January 30 but the M will
grab two digits, resulting in an invalid date:
//invalid
UI_dateEdit.setDisplayFormat("Md");
UI_dateEdit.setDate("130");
For any field that is not represented in the format the following defaults are used:
String getDateTime(void)
Returns the date and time.
String getDisplayFormat(void)
Returns the display format.
String getSelectedDate(void)
Returns the selected date.
String getDateFormat(void)
Returns the date format.
Array<Number> sizes(void)
Returns a list of the size parameters of all the widgets in this splitter.
If the splitter's orientation is horizontal, the list contains the widgets width in pixels,
from left to right; if the orientation is vertical, the list contains the widgets height in pixels,
from top to bottom.
Number value(void)
Returns the dial's current value.
If you want a separate window for plotting data, then use a plot window instead (see chapter
Script plot window class).
To create a ScriptPlotWidget following must be done:
• add a group box to the script GUI (QtDesigner)
• call ScriptGroupBox::addPlotWidget (see chapter ScriptPlotWidget
addPlotWidget(void))
Important: This class is not derived from the ScriptWidget class. Therefore the functions
from the ScriptWidget class can not be used.
The functions and signals which can be used from script are described in the following
chapters.
void clearGraphs(void)
This function clears the data of all graphs.
void removeAllGraphs(void)
This function removes all graphs.
void showHelperElements(bool showXRange, bool showYRange, bool showUpdate,
bool showSave, bool showLoad, bool showClear, bool showGraphVisibility, Number
graphVisibilityMaxSize=100, bool showLegend=true)
Sets the visibility of several plot widget elements.
Arguments:
showXRange: True if the x range input field shall be visible
showYRange: True if the y range input fields shall be visible
showUpdate: True if the x update check box shall be visible
showSave: True if the save button shall be visible
showLoad: True if the load button shall be visible
showClear: True if the clear button shall be visible
showGraphVisibility: True if the show group box
graphVisibilityMaxSize: The max. width of the show group box
showLegend: True if the show legend check box shall be visible
PlotAxisRanges
This object/structure contains the axis ranges:
• xMinValue: The min. values of the x axis.
• xMaxValue: The max. value of the x axis.
• yMinValue: The min. values of the y axis.
• ymaxValue: The max. value of the y axis.
• y2MinValue: The min. values of the y axis 2.
• y2maxValue: The max. value of the y axis 2.
bool isAutoUpdateEnabled(void)
Returns the automatic update enabled state.
void updatePlot(void)
Repaints the plot widget.
var x = 0;
var y = 0;
for(var i = 0; i < 100; i++)
{
x++;
y++;
plotWidget.addDataToGraph(plotWidgetGraph1Index, x, y);
plotWidget.addDataToGraph(plotWidgetGraph2Index, x + 10, y);
if(y > 10)
{
y = 0;
}
}
ScriptWidget class
This is the parent class of almost all user interface classes.
The functions and signals which can be used from the worker script are described in the
following chapters.
void update(void)
Updates the widget.
String windowPositionAndSize(void)
Returns the window size and position (Pixel). The return string has following format: "top left
x, top left y, width, height".
Example:
Ui_Dialog.setWindowPositionAndSize("100,100,500,500");
Example:
UI_testSetTextLineEdit.setBackgroundColor("red");
Note:
Fore some GUI elements (like the RadioButton) setAutoFillBackground must be called if the
background color shall be changed and for some other GUI elements (like the CheckBox) the
background color cannot be changed.
Example:
UI_testReceiveCheckBox.setWindowTextColor("red");
Example:
UI_testReceiveCheckBox.setTextColor("red");
void raise(void)
Raises this widget to the top of the parent widget's stack.
void lower(void)
Lowers the widget to the bottom of the parent widget's stack.
Note: This function calls setParent() when changing the flags for a window, causing the
widget to be hidden. You must call ScriptWidget::show() to make the widget visible again.
Arguments:
flags: The new additional window flags
WindowType_Mask = 0x000000ff,
MSWindowsFixedSizeDialogHint = 0x00000100,
MSWindowsOwnDC = 0x00000200,
BypassWindowManagerHint = 0x00000400,
X11BypassWindowManagerHint = BypassWindowManagerHint,
FramelessWindowHint = 0x00000800,
WindowTitleHint = 0x00001000,
WindowSystemMenuHint = 0x00002000,
WindowMinimizeButtonHint = 0x00004000,
WindowMaximizeButtonHint = 0x00008000,
WindowMinMaxButtonsHint = WindowMinimizeButtonHint |
WindowMaximizeButtonHint,
WindowContextHelpButtonHint = 0x00010000,
WindowShadeButtonHint = 0x00020000,
WindowStaysOnTopHint = 0x00040000,
WindowTransparentForInput = 0x00080000,
WindowOverridesSystemGestures = 0x00100000,
WindowDoesNotAcceptFocus = 0x00200000,
CustomizeWindowHint = 0x02000000,
WindowStaysOnBottomHint = 0x04000000,
WindowCloseButtonHint = 0x08000000,
MacWindowToolBarButtonHint = 0x10000000,
BypassGraphicsProxyWidget = 0x20000000,
WindowOkButtonHint = 0x00080000,
WindowCancelButtonHint = 0x00100000,
NoDropShadowWindowHint = 0x40000000,
WindowFullscreenButtonHint = 0x80000000
};
Example:
UI_ReceiveFileDialog.setWindowFlags(0x00040000);
//show must be called after setWindowFlags
UI_ReceiveFileDialog.show();
Number windowFlags(void)
Returns the window flags.
void setFocus(void)
Gives the keyboard input focus to this widget.
void width(void)
Returns the width of the widget excluding any window frame.
void height(void)
Returns the height of the widget excluding any window frame.
String getClassName(void)
Returns the class name of this object.
//Test shortcut 1.
UI_Dialog.createShortCut("Alt+V", testShortcut1);
//Test shortcut 2.
UI_Dialog.createShortCut("F1", testShortcut2);
UI_Label.setStyleSheet(styleSheet);
Note: All functions and classes must reside in the QtDesigner plug-in library.
Important:
A function from a custom widget class must not be called directly from a worker-script (a
worker script runs in his own thread and the custom widget runs like all GUI elements in the
main thread). Instead a slot must be called (by a signal). This signal must be connected with
Qt::QueuedConnection or Qt::BlockingQueuedConnection.
If the worker script runs in a debugger then Qt::DirectConnection instead of
Qt::BlockingQueuedConnection must be used (the debugger and therefore the worker script
runs in the main thread). Qt::BlockingQueuedConnection would cause a dead-lock.
In this function all objects and functions which are accessible by script must be registered.
C++ Example:
void init(QScriptEngine* engine)
{
qRegisterMetaType<QScriptEngine*>("TestDll*");
engine->globalObject().setProperty("TestDll", engine->newQObject(&testDll));
To load a library the script must call the function bool loadLibrary(String path, bool
isRelativePath=true)
Example:
scriptThread.loadLibrary("TestDll.dll", true);
Sequence script
Sequence scripts can be added to a send sequence (send window). If a sequence is send, the
script function sendData is called. In this function the sequence data can be modified (create a
frame, calculate CRC …). The modified data must be returned.
Note: After sending a sequence the corresponding sequence script is unloaded. Therefore no
data can be stored in a sequence script variable (sequence scripts can store data globally in
ScriptCommunicator (e.g. counter) with special functions (are described below)).
Example:
function sendData(data)
{
var counter = 0;
//Read the stored counter value
var resultArray = seq.getGlobalUnsignedNumber("Counter");
if(resultArray[0] == 1)
{
counter = resultArray[1];
}
//Append a CRC8.
var crc8 = seq.calculateCrc8(data);
data.push(crc8 & 0xff);
counter++;
//Store the new counter value.
seq.setGlobalUnsignedNumber("Counter", counter);
return data;
}
Note:
For complex scripts 'worker scripts' in the script window must be used (see chapter Worker
scripts).
Sequence scripts are running in an own thread, therefore ScriptCommunicator can not be
blocked by a sequence script directly. The GUI of a sequence script runs in the main thread (a
call to a script GUI
element normally calls a function in the main thread), therefore to many calls to script GUI
elements
can block ScriptCommunicator.
Sequence scripts are JavaScript scripts (see chapter Script interface). The sequence scripts
interface extents the standard JavaScript functionality. These extended functionality is
described in the following chapters.
The used code for the CRC calculation is shown on page 50.
The used code for the CRC calculation is shown on page 51.
The used code for the CRC calculation is shown on page 52.
String getCurrentVersion
Returns the current version of ScriptCommunicator (string) .
Version format: major.minor (eg. 3.09)
Converter functions
The script converter class provides several converter functions. These functions can be
accessed with the conv object (see chapter Script converter object/class).
Inter-SequenceScript communication
The following functions can be used to store data from a sequence script globally. If this
sequence script is started again the data can be read (e.g. for a counter). Global stored
sequence script data\variables can be accessed from every sequence script (these variable are
stored in ScriptCommunicator global sequence script maps).
The script converter class provides several converter functions. These functions can be
accessed with the conv object. Example:
var array = conv.addUint16ToArray(array, 61234, true);
The functions which can be used are described in the following chapters.
Example scripts
Under the directory exampleScripts several example scripts can be found which demonstrate
the different script interfaces of ScriptCommunicator.