[Tutor] Event loop logic question
Dennis Lee Bieber
wlfraed at ix.netcom.com
Sat Jun 18 15:19:39 EDT 2022
On Sat, 18 Jun 2022 15:04:50 +1000, Phil <phillor9 at gmail.com> declaimed the
following:
>Any hints or alternative methods will be, as always, greatly appreciated.
>
>By the way, this project sends commands to a controller which is easily
>overwhelmed if too many commands are received per second.
>
For the last matter, one solution would be to use an elapsed time
counter.
rate = 1.0 / commands_per_second
last_command_time = 0.0 #or get the time (fractional seconds)
#at start of program
Then, when you issue a command, some logic like
if last_command_time + rate < time_now:
issue_command
last_command_time = time_now
... optional if you return a status that "command skipped -- rate limited"
For the former/general... I see too many flags that should (as I
understand it) be mutually exclusive (only one should be set/cleared
[depending on overall logic] at any moment in the program). Instead I'd
suggest using a "state" variable (maybe check on what Python has for
"enums" -- I've not used them in my dribblings, so the following is just
using "constants"
STATE_QUIT, STATE_FORWARD, STATE_STOPPED = range(3)
current_state = STATE_STOPPED
requested_state = STATE_STOPPED
... key-press
if key == keys.UP:
requested_state = STATE_FORWARD
elif key == keys.SPACE:
requested_state = STATE_QUIT
else:
pass #log an unused key press
... key-release
requested_state = STATE_STOPPED
... update section
if requested_state != current_state:
#if the requested state is the same as current_state,
#it may signal a repeating key (but only if the OS doesn't
#issue a key release and key press at the start of each repeat --
#if it does -- you'll need to incorporate some nasty rate timer
#to determine what is a repeat vs a real release/press)
if requested_state == STATE_QUIT:
#initiate shutdown?
#log change?
elif requested_state == STATE_FORWARD:
#issue forward command to device
#log change
elif requested_state == STATE_STOPPED:
#issue stop command to device
#log change
else:
#unexpected STATE!
current_state = requested_state #update state
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/
More information about the Tutor
mailing list