Is there a way to continuously change a certain value without stopping the main loop?

Viewed 35

I want to program that changes a rooms lights. The system runs on a controller that I can access via MQTT and REST. I have a way to change the intensity but it is very abrupt. Because I want the rest of the system to continue running while the change is happening (because I have Sensors running the rest of the lighting) I can't just use a loop to steadily increase the intensity. I looked into Timers but I can't get them to work properly for what I need. Is there a way to do that?

Here is my Problem with the loop:

client.message_callback_add(path("zones",Office,"devices",Sensor1_Presence,"data","presence"), on_message_Presence_callback)
client.message_callback_add(path("zones",Office,"devices",Sensor2_Presence,"data","presence"), on_message_colorchange_callback)

#client.message_callback_add(path("zones","#"), on_message_callback)

startTimer()
WeatherTimer()

client.connect(MQTT_HOST, port=MQTT_PORT)
client.loop_forever()

I want to be able to start and stop the function (preferably with a bool)

I have a change function that changes the specific parameters already:

def change_parameter(URL, parameter_name ,parameter_value):

r = requests.put(
    f"https://{MQTT_HOST}/rest/v1/{URL}",
    headers=litecom_headers(),
    verify=False,
    json={f"{parameter_name}": parameter_value}
)
return r.status_code

Is there a way to do what I want to do? Thanks in advance!

1 Answers

I assume you have the python script controlling your lights running on your desktop pc?

If so, you most certainly have at least 2 cpu cores at your disposal and can make use of python's ProcessPoolExecutor to run your parameter changing function in parallel. Then you can just gradually change your parameter in small steps until you reach the desired value. To get a smooth effect you then just have to experiment with the step-size and the sleep value between the steps until you are satisfied with the results.

Pseudo-ish implementation:

def change_param_smooth(URL, parameter_name, target_value, stepsize, duration):
    current_value = 0 // get the current value from your device
    while current_value < target_value:
        current_value += step_size
        # avoid overshooting
        if current_value > target_value:
            current_value = target_value
        change_parameter(URL, parameter_name, current_value)
        time.sleep(duration)
Related