Periodically send command with Tcl - tcl

I am writing a Tcl/Tk interface to communicate with a temperature controller over Modbus. I would like to periodically (ie. every 5-10s or so) send a query to the temperature controller to get the current temperature.
Right now, I'm doing this by:
while 1 {
get_current_temperature;
after 5000;
}
This works, but it prevents the user from interacting with the GUI for the duration of the after command, which is very undesirable. Could anyone suggest a workaround for this?
Thank you for your help!

You are looking for the every proc: https://wiki.tcl-lang.org/page/every
proc every {ms body} {
after $ms [namespace code [info level 0]]
uplevel #0 $body
}
every 5000 get_current_temperature
The every command reschedules itself after the specified number of milliseconds, then runs the command. This is the other way around from most of the versions on the wiki page. It has the advantage(?) that it isn't affected by the time the command takes to run. It also doesn't stop the next iteration if the command throws an error.

Related

How to run repeatedly a proc in Tcl

I have written a proc in tcl which takes one argument (a positive integer) und displays a text. Lets call it permu (for permutation). I would like to execute this proc permanently, so
puts [permu 3]
and with the same argument (here 3), lets say every 2 or 3 seconds or so, without removing the previous outcome of the code. How can I do this?
The second question: Same question as above but I would like to clear the screen when the new outcome of permu is displayed.
Third question: In case that I decide to stop a running code (I work with Linux), for example the one above, how can I do this?
Thanks in advance!
Here's one way to do the repeated output:
proc repeat_permu {arg delay} {
puts [permu $arg]
after $delay [list repeat_permu $arg $delay]
}
# Note that the delay is in milliseconds
repeat_permu 3 3000
# Now start the event loop
vwait forever
To clear the screen you need to send the appropriate escape sequence before each new output. Most terminal emulators will accept the vt100 code, so you would do puts "\x1b[2J".
Normally you could just stop your program running by typing control-c, or do you want some means of doing this programmatically?
Update: A simpler way to do the repetition if you don't need to process any other events in parallel is just: while 1 {puts [permu 3]; after 3000}

Fileevent executed before proc finishes

i have the following code ...
lassign [ chan pipe ] chan chanW
fileevent $chan readable [ list echo $chan ]
proc echo { chan } {
...
}
proc exec { var1 var2 } {
....
puts $chanW "Some output"
....
}
Now according to man fileevent will be executed when the programs idles
is it possible to forse fileevent to be executed before that. For instance is it possible to force the fileevent to be executed immediately after the channel becomes readable, to somehow give it priority .... without using threads :)
Tcl never executes an event handler at “unexpected” points; it only runs them at points where it is asked to do so explicitly or, in some configurations (such as inside wish) when it is doing nothing else. You can introduce an explicit wait for events via two commands:
update
vwait
The update command clears down the current event queue, but does not wait for incoming events (strictly, it does an OS-level wait of length zero). The vwait command will also allow true waiting to happen, waiting until a named Tcl global variable has been written to. (It uses a C-level variable trace to do this, BTW.) Doing either of these will let your code process events before returning. Note that there are a number of other wrappers around this functionality; the geturl command in the http package (in “synchronous” mode) and the tkwait command in the Tk package both do this.
The complication? It's very easy to make your code reenter itself by accident while running the event loop. This can easily end up with you making lots of nested event loop calls, running you out of stack space; don't do that. Instead, prepare for reentrancy issues (a global variable check is on of the easiest approaches to do that) so that you don't nest event loops.
Alternatively, if you're using Tcl 8.6 you can switch your code around to use coroutines. They let you stop the current procedure evaluation and return to the main event loop to wait for a future event before starting execution again: you end up with code that returns at the expected time, but which was suspended for a while first. If you want more information about this approach, please ask another separate question here.

Button with multiple command line arguments

Can a button in tcl could be linked to multiple command line arguments ?
I have a code which runs when a button is clicked, a progressbar code with time in seconds is also linked with it , and should start at same time when this button is pressed.
I put both procs as a command in button command argument using {} but it fails with Error.
Code Snippet
button .b -image $p -command {progressbar 300 run_structural_comparision}
proc progressbar {seconds} {
ttk::progressbar .pg -orient horizontal -mode determinate -maximum $seconds
pack .pg -side left
update idletasks
# Do some real work here for $seconds seconds
for {set i 0} {$i < $seconds} {incr i} {
after 1000; # Just waiting in this example, might as well do something useful here
.pg step; # After some part of the work, advance the progressbar
update idletasks; # Needed to update the progressbar
}
# Done, clean up the dialog and progressbar
}
proc run_structural_comparision {} {
type_run
global ENTRYfilename ENTRYfilename2 curDIR curDIR2 typep reflib compLib rundir hvt_verilog logfile
set path [concat $reflib $compLib]
## set path [concat $ENTRYfilename $ENTRYfilename2]
puts $path
set str "compare_structure -overlap_when -type {timing constraint} -report compare_structure_"
set trt ".txt"
set structure [concat [string trim $str][string trim $typep][string trim $trt] $path]
puts $structure
puts $rundir
cd $rundir
set filename [concat "compare_structure_" $typep ".tcl"]
if {[ file exists $rundir/$filename] == 1 } {
exec rm -rf $rundir/compare_structure_$typep.tcl
}
A button's -command callback is a Tcl script. It will be evaluated at the global level of the stack. If you want to run two commands, you can just put a script in there to run the two commands:
button .b -command { command_1; command_2 }
This will run them sequentially. Tcl is naturally single-threaded as that is by far the easiest programming model for people to work with. It's possible to make code that works by doing callbacks to appear to be doing multiple things at once (that's how Tk works, just like virtually all other GUIs on the planet) but you're really only doing one thing at a time.
But your real question…
The core of what you need is a way to run the program that takes a long time in the background so that you can monitor it and continue to update the GUI. This is not a trivial topic, unfortunately, and the right answer will depend on exactly what is going on.
One of the simplest techniques is where the CPU-bound processing is done in a subprocess. In that case, you can run the subprocess via a pipeline and set fileevent to give you a notification callback when output is produced or the program terminates. Tcl is very good at this sort of thing; things that many languages have as very advanced techniques just feel natural when done with Tcl, as a great deal of thought has been put into how to make I/O callbacks work nicely.
If it's in-process and long-running without the opportunity for callbacks, things get more complex as you have to have the processing and the GUI updates in different threads. Which isn't too hard if you've got everything set up right, but which might require substantial re-architecting of your program (as it is usual for threads in Tcl to be extremely strongly partitioned from each other).
The simplest thing to do is to create a procedure that calls the two functions. If you wantie:
proc on_button_press {seconds} {
after idle [list progressbar $seconds]
after idle [list run_structural_comparision]
}
You can put multiple calls in the immediate button handler command string but it quickly gets complicated. But in short, use a semicolon to separate the two commands.
Your use if update idletasks should be considered a "code smell". ie: avoid it. In this case, in the progressbar function, setup the bar then just have everything else called by after calls to update the state of the progress.
I suspect your rm -rf may not do what you want. It it likely to lockup the interface as you get nothing back until the command has completed. Better is to write a function to walk the directory tree and delete the files with file delete and you can then raise progress events as you go and keep the UI alive by breaking up the processing into chunks using after again.

TCL command wrapping

I am trying to write a TCL proc that will allow me to wrap statements and then 'execute' them internally.
For example, if I originally have :
set var $tmp
I want to have some procedure :
proc wrapper {command} {
puts "do something here"
puts $command #ie below : write "set var $tmp" to stdout
EXECUTE COMMAND HERE
puts "do something else here"
}
set void [wrapper {set var $tmp}]
My motivation is that I'm trying to write my own timing/profiler for individual statements.
Instead of "EXECUTE COMMAND", use
uplevel 1 $command
Note that if you attempt to time a script using a command like your wrapper, it won't be byte-compiled, which means that it won't perform the way it would inside a procedure.
Documentation: uplevel
You can give a try with time command which is already available with Tcl if your only intention is to just get the time taken by a set of code to execute.
time script ?count?
This command will call the Tcl interpreter count times to evaluate script (or once if count is not specified). It will then return a string of the form
503.2 microseconds per iteration
which indicates the average amount of time required per iteration, in microseconds. Time is measured in elapsed time, not CPU time.
Example :
set code_block {
foreach x "1 2 3" {
set y [expr {$x*20}];
}
}
puts [time $code_block 10]; # Executing the code for 10 times
which might produce random outputs such as
11.9 microseconds per iteration
Update 1 :
If you want to print the commands along with execution which is also possible. You can override the time command with rename command.
rename time _time; # Changing the 'time' to '_time'
# Defining your own 'time' command
proc time {command {count 1}} {
# Printing the commands here
puts $command
# Calling the actual '_time' command
# and returning that value from here
return [_time $command $count]
}
Place the above code at the top of your code and usage of time command after this will be using our customized procedure only.
They are passed as set of command which in turn, yes, a string. But, while the evaluation of the code, it will behave as if like how it will work in a tclsh.
As answered by Mr.Peter, if your code involves accessing the previous level of commands, variables, then you have to use uplevel or upvar based on your needs.
Reference : time, rename

How can I make a given script to be evaluated after each iteration in vwait forever?

vwait forever runs the events loop until the exit command.
I have some stuff to do during each iteration of the event loop. How can I do that?
You don't. What you do is schedule regular timer events that do your work. For user interaction, 10 times a second is quite regular enough. To schedule regular timer events, use the every command from the Tcler's Wiki, like this:
proc every {ms body} {after $ms [info level 0]; eval $body}
every 100 {
puts "I'm saying Hi ten times a second!"
}
That's the simplest form of every; more complex cancelable versions are further down that wiki page.