I am currently developing a IoT sensor value simulator using the PyCharm IDE (along with pygame). Essentially, I am trying to produce/send data to Microsoft Azure IoT platform while there is a GUI available for users, in which they can see the temperatures of each sensor, change the sensor outputs, etc.
Since I do not want to spam Azure with messages, I use sleep function between every messages sent to limit the rate of messages being sent. As a result, this slows down the whole application and it is a bit cumbersome. Is there a way to get around this where I can send messages without affecting the user experience on the GUI? Thanks!
Advertisement
Answer
As Ted pointed out, multithreading is definitely an option, but may be a bit overkill depending on your case.
As an alternative solution you can use the time module of python to calculate the time since the last message was sent and only send a new message if enough time has passed. This way your other processes will continue to run as expected and you don’t have to sleep / freeze your program.
import time start = time.time() message_interval = 5 # in seconds while True: # other application logic if time.time() - start >= message_interval: send_message() start = time.time() # reset timer
You could potentially even combine it with another check to see if it is even necessary to send a message.
import time start = time.time() message_interval = 5 # in seconds update_available = true while True: if time.time() - start >= message_interval and update_available: send_update_message() start = time.time() # reset timer update_available = false # reset variable