Using "static variables" for the Conditional Controller

I would recommend using a Conditional Controller. If you haven’t already, I’d read the Electrical Conductivity and pH Regulation section of my Automated Hydroponic System Build article. It lays a good ground work for expanding the functionality of regulating pH and EC.

For the Python Class that is used to run Conditional Controllers, you can simply use the self variable. This can be seen in use in the section I linked to, above. Simply, just create a variable and it will persist across controller loops:

self.my_var = 1

However, you will also need to test for the existence of this variable the first time if you need to read it:

if not hasattr(self, "my_var"):
    self.my_var = 1  # first run
else:
    self.my_var = 2  # after first run

To avoid this, there exists the self.variables dictionary that can be used, since this is created when the Class is instantiated.

if "test" not in self.variables:
    self.variables["test"] = 1
    self.variables["more"] = 2
else:
    self.variables["test"] = 3
    self.variables["more"] = 4

If you want data to persists across reboots or controller restarts, you can save and retrieve data from the database:

my_var = self.get_custom_option("my_variable_name")
self.set_custom_option("my_variable_name", my_var)

If nothing has been stored, it will return None.

Hope this helps.

1 Like