SMAHub is a flexible and modular solution for collecting data from SMA photovoltaic (PV) products and publishing it to various output channels, such as MQTT.
GNU General Public License v2.0
31
stars
11
forks
source link
Fix brittle sensor definition dictionary loading, and make things properly extensible #10
At the moment, the sensor definitions used by the ha_mqtt plugin are are kept in a central file that contains dictionaries (src/utils/smasensors.py), which looks like this:
This file contains definition dictionaries for all known devices (except for the new EV Charger plugin, all in the same style.
Right now, this is imported in ha_mqtt.py via:
from utils.smasensors import *
And then, I pick individual dictionaries from this file depending on context, with
sensors_dict = f"SENSORS_{name.split('.')[0]}".upper()
(The details don't matter - the essence is that this is selecting dictionaries from that larger file based on their name, at runtime)
There are at least two problems with this:
This dictionary-set should be properly extensible by plugins, without touching the core smasensors.py script
The approach is generally brittle, not very idiomatic, and not very intuitive to understand
So, this should be refactored, eg
Use a Registry Pattern: Instead of separate dictionaries, have one dictionary that acts as a registry. New sensor definitions can be added to this registry.
Use a Function to Register New Sensors: This is similar to the registry pattern but encapsulates the updating logic in a function.
At the moment, the sensor definitions used by the ha_mqtt plugin are are kept in a central file that contains dictionaries (src/utils/smasensors.py), which looks like this:
This file contains definition dictionaries for all known devices (except for the new EV Charger plugin, all in the same style.
Right now, this is imported in ha_mqtt.py via:
from utils.smasensors import *
And then, I pick individual dictionaries from this file depending on context, withsensors_dict = f"SENSORS_{name.split('.')[0]}".upper()
(The details don't matter - the essence is that this is selecting dictionaries from that larger file based on their name, at runtime)There are at least two problems with this:
So, this should be refactored, eg